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 completing ALTER TYPE 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(List **wqueue, Relation rel, AlterTableCmd *cmd,
559 : : bool recurse, LOCKMODE lockmode,
560 : : AlterTableUtilityContext *context);
561 : : static void verifyNotNullPKCompatible(HeapTuple tuple, const char *colname);
562 : : static ObjectAddress ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
563 : : IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
564 : : static ObjectAddress ATExecAddStatistics(AlteredTableInfo *tab, Relation rel,
565 : : CreateStatsStmt *stmt, bool is_rebuild, LOCKMODE lockmode);
566 : : static ObjectAddress ATExecAddConstraint(List **wqueue,
567 : : AlteredTableInfo *tab, Relation rel,
568 : : Constraint *newConstraint, bool recurse, bool is_readd,
569 : : LOCKMODE lockmode);
570 : : static char *ChooseForeignKeyConstraintNameAddition(List *colnames);
571 : : static ObjectAddress ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
572 : : IndexStmt *stmt, LOCKMODE lockmode);
573 : : static ObjectAddress ATAddCheckNNConstraint(List **wqueue,
574 : : AlteredTableInfo *tab, Relation rel,
575 : : Constraint *constr,
576 : : bool recurse, bool recursing, bool is_readd,
577 : : LOCKMODE lockmode);
578 : : static ObjectAddress ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab,
579 : : Relation rel, Constraint *fkconstraint,
580 : : bool recurse, bool recursing,
581 : : LOCKMODE lockmode);
582 : : static int validateFkOnDeleteSetColumns(int numfks, const int16 *fkattnums,
583 : : int numfksetcols, int16 *fksetcolsattnums,
584 : : List *fksetcols);
585 : : static ObjectAddress addFkConstraint(addFkConstraintSides fkside,
586 : : char *constraintname,
587 : : Constraint *fkconstraint, Relation rel,
588 : : Relation pkrel, Oid indexOid,
589 : : Oid parentConstr,
590 : : int numfks, int16 *pkattnum, int16 *fkattnum,
591 : : Oid *pfeqoperators, Oid *ppeqoperators,
592 : : Oid *ffeqoperators, int numfkdelsetcols,
593 : : int16 *fkdelsetcols, bool is_internal,
594 : : bool with_period);
595 : : static void addFkRecurseReferenced(Constraint *fkconstraint,
596 : : Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
597 : : int numfks, int16 *pkattnum, int16 *fkattnum,
598 : : Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
599 : : int numfkdelsetcols, int16 *fkdelsetcols,
600 : : bool old_check_ok,
601 : : Oid parentDelTrigger, Oid parentUpdTrigger,
602 : : bool with_period);
603 : : static void addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint,
604 : : Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
605 : : int numfks, int16 *pkattnum, int16 *fkattnum,
606 : : Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
607 : : int numfkdelsetcols, int16 *fkdelsetcols,
608 : : bool old_check_ok, LOCKMODE lockmode,
609 : : Oid parentInsTrigger, Oid parentUpdTrigger,
610 : : bool with_period);
611 : : static void CloneForeignKeyConstraints(List **wqueue, Relation parentRel,
612 : : Relation partitionRel);
613 : : static void CloneFkReferenced(Relation parentRel, Relation partitionRel);
614 : : static void CloneFkReferencing(List **wqueue, Relation parentRel,
615 : : Relation partRel);
616 : : static void createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid,
617 : : Constraint *fkconstraint, Oid constraintOid,
618 : : Oid indexOid,
619 : : Oid parentInsTrigger, Oid parentUpdTrigger,
620 : : Oid *insertTrigOid, Oid *updateTrigOid);
621 : : static void createForeignKeyActionTriggers(Oid myRelOid, Oid refRelOid,
622 : : Constraint *fkconstraint, Oid constraintOid,
623 : : Oid indexOid,
624 : : Oid parentDelTrigger, Oid parentUpdTrigger,
625 : : Oid *deleteTrigOid, Oid *updateTrigOid);
626 : : static bool tryAttachPartitionForeignKey(List **wqueue,
627 : : ForeignKeyCacheInfo *fk,
628 : : Relation partition,
629 : : Oid parentConstrOid, int numfks,
630 : : AttrNumber *mapped_conkey, AttrNumber *confkey,
631 : : Oid *conpfeqop,
632 : : Oid parentInsTrigger,
633 : : Oid parentUpdTrigger,
634 : : Relation trigrel);
635 : : static void AttachPartitionForeignKey(List **wqueue, Relation partition,
636 : : Oid partConstrOid, Oid parentConstrOid,
637 : : Oid parentInsTrigger, Oid parentUpdTrigger,
638 : : Relation trigrel);
639 : : static void RemoveInheritedConstraint(Relation conrel, Relation trigrel,
640 : : Oid conoid, Oid conrelid);
641 : : static void DropForeignKeyConstraintTriggers(Relation trigrel, Oid conoid,
642 : : Oid confrelid, Oid conrelid);
643 : : static void GetForeignKeyActionTriggers(Relation trigrel,
644 : : Oid conoid, Oid confrelid, Oid conrelid,
645 : : Oid *deleteTriggerOid,
646 : : Oid *updateTriggerOid);
647 : : static void GetForeignKeyCheckTriggers(Relation trigrel,
648 : : Oid conoid, Oid confrelid, Oid conrelid,
649 : : Oid *insertTriggerOid,
650 : : Oid *updateTriggerOid);
651 : : static void ATExecDropConstraint(Relation rel, const char *constrName,
652 : : DropBehavior behavior, bool recurse,
653 : : bool missing_ok, LOCKMODE lockmode);
654 : : static ObjectAddress dropconstraint_internal(Relation rel,
655 : : HeapTuple constraintTup, DropBehavior behavior,
656 : : bool recurse, bool recursing,
657 : : bool missing_ok, LOCKMODE lockmode);
658 : : static void ATPrepAlterColumnType(List **wqueue,
659 : : AlteredTableInfo *tab, Relation rel,
660 : : bool recurse, bool recursing,
661 : : AlterTableCmd *cmd, LOCKMODE lockmode,
662 : : AlterTableUtilityContext *context);
663 : : static bool ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno);
664 : : static ObjectAddress ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
665 : : AlterTableCmd *cmd, LOCKMODE lockmode);
666 : : static void RememberAllDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype,
667 : : Relation rel, AttrNumber attnum, const char *colName);
668 : : static void RememberWholeRowDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype, Relation rel);
669 : : static void RememberConstraintForRebuilding(Oid conoid, AlteredTableInfo *tab);
670 : : static void RememberIndexForRebuilding(Oid indoid, AlteredTableInfo *tab);
671 : : static void RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab);
672 : : static void ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab,
673 : : LOCKMODE lockmode);
674 : : static void ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, Oid ownerId,
675 : : const char *cmdstring, List **wqueue,
676 : : LOCKMODE lockmode, bool rewrite);
677 : : static void RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass pass,
678 : : Oid objid, Relation rel, List *domname,
679 : : const char *conname);
680 : : static void TryReuseIndex(Oid oldId, IndexStmt *stmt);
681 : : static void TryReuseForeignKey(Oid oldId, Constraint *con);
682 : : static ObjectAddress ATExecAlterColumnGenericOptions(Relation rel, const char *colName,
683 : : List *options, LOCKMODE lockmode);
684 : : static void change_owner_fix_column_acls(Oid relationOid,
685 : : Oid oldOwnerId, Oid newOwnerId);
686 : : static void change_owner_recurse_to_sequences(Oid relationOid,
687 : : Oid newOwnerId, LOCKMODE lockmode);
688 : : static ObjectAddress ATExecClusterOn(Relation rel, const char *indexName,
689 : : LOCKMODE lockmode);
690 : : static void ATExecDropCluster(Relation rel, LOCKMODE lockmode);
691 : : static void ATPrepSetAccessMethod(AlteredTableInfo *tab, Relation rel, const char *amname);
692 : : static void ATExecSetAccessMethodNoStorage(Relation rel, Oid newAccessMethodId);
693 : : static void ATPrepChangePersistence(AlteredTableInfo *tab, Relation rel,
694 : : bool toLogged);
695 : : static void ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel,
696 : : const char *tablespacename, LOCKMODE lockmode);
697 : : static void ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode);
698 : : static void ATExecSetTableSpaceNoStorage(Relation rel, Oid newTableSpace);
699 : : static void ATExecSetRelOptions(Relation rel, List *defList,
700 : : AlterTableType operation,
701 : : LOCKMODE lockmode);
702 : : static void ATExecEnableDisableTrigger(Relation rel, const char *trigname,
703 : : char fires_when, bool skip_system, bool recurse,
704 : : LOCKMODE lockmode);
705 : : static void ATExecEnableDisableRule(Relation rel, const char *rulename,
706 : : char fires_when, LOCKMODE lockmode);
707 : : static void ATPrepChangeInherit(Relation child_rel);
708 : : static ObjectAddress ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode);
709 : : static ObjectAddress ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode);
710 : : static void drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid,
711 : : DependencyType deptype);
712 : : static ObjectAddress ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode);
713 : : static void ATExecDropOf(Relation rel, LOCKMODE lockmode);
714 : : static void ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode);
715 : : static void ATExecGenericOptions(Relation rel, List *options);
716 : : static void ATExecSetRowSecurity(Relation rel, bool rls);
717 : : static void ATExecForceNoForceRowSecurity(Relation rel, bool force_rls);
718 : : static ObjectAddress ATExecSetCompression(Relation rel,
719 : : const char *column, Node *newValue, LOCKMODE lockmode);
720 : :
721 : : static void index_copy_data(Relation rel, RelFileLocator newrlocator);
722 : : static const char *storage_name(char c);
723 : :
724 : : static void RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid,
725 : : Oid oldRelOid, void *arg);
726 : : static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid,
727 : : Oid oldrelid, void *arg);
728 : : static PartitionSpec *transformPartitionSpec(Relation rel, PartitionSpec *partspec);
729 : : static void ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs,
730 : : List **partexprs, Oid *partopclass, Oid *partcollation,
731 : : PartitionStrategy strategy);
732 : : static void CreateInheritance(Relation child_rel, Relation parent_rel, bool ispartition);
733 : : static void RemoveInheritance(Relation child_rel, Relation parent_rel,
734 : : bool expect_detached);
735 : : static ObjectAddress ATExecAttachPartition(List **wqueue, Relation rel,
736 : : PartitionCmd *cmd,
737 : : AlterTableUtilityContext *context);
738 : : static void AttachPartitionEnsureIndexes(List **wqueue, Relation rel, Relation attachrel);
739 : : static void QueuePartitionConstraintValidation(List **wqueue, Relation scanrel,
740 : : List *partConstraint,
741 : : bool validate_default);
742 : : static void CloneRowTriggersToPartition(Relation parent, Relation partition);
743 : : static void DropClonedTriggersFromPartition(Oid partitionId);
744 : : static ObjectAddress ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab,
745 : : Relation rel, RangeVar *name,
746 : : bool concurrent);
747 : : static void DetachPartitionFinalize(Relation rel, Relation partRel,
748 : : bool concurrent, Oid defaultPartOid);
749 : : static ObjectAddress ATExecDetachPartitionFinalize(Relation rel, RangeVar *name);
750 : : static ObjectAddress ATExecAttachPartitionIdx(List **wqueue, Relation parentIdx,
751 : : RangeVar *name);
752 : : static void validatePartitionedIndex(Relation partedIdx, Relation partedTbl);
753 : : static void refuseDupeIndexAttach(Relation parentIdx, Relation partIdx,
754 : : Relation partitionTbl);
755 : : static void verifyPartitionIndexNotNull(IndexInfo *iinfo, Relation partition);
756 : : static List *GetParentedForeignKeyRefs(Relation partition);
757 : : static void ATDetachCheckNoForeignKeyRefs(Relation partition);
758 : : static char GetAttributeCompression(Oid atttypid, const char *compression);
759 : : static char GetAttributeStorage(Oid atttypid, const char *storagemode);
760 : :
761 : :
762 : : /* ----------------------------------------------------------------
763 : : * DefineRelation
764 : : * Creates a new relation.
765 : : *
766 : : * stmt carries parsetree information from an ordinary CREATE TABLE statement.
767 : : * The other arguments are used to extend the behavior for other cases:
768 : : * relkind: relkind to assign to the new relation
769 : : * ownerId: if not InvalidOid, use this as the new relation's owner.
770 : : * typaddress: if not null, it's set to the pg_type entry's address.
771 : : * queryString: for error reporting
772 : : *
773 : : * Note that permissions checks are done against current user regardless of
774 : : * ownerId. A nonzero ownerId is used when someone is creating a relation
775 : : * "on behalf of" someone else, so we still want to see that the current user
776 : : * has permissions to do it.
777 : : *
778 : : * If successful, returns the address of the new relation.
779 : : * ----------------------------------------------------------------
780 : : */
781 : : ObjectAddress
782 : 40979 : DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
783 : : ObjectAddress *typaddress, const char *queryString)
784 : : {
785 : : char relname[NAMEDATALEN];
786 : : Oid namespaceId;
787 : : Oid relationId;
788 : : Oid tablespaceId;
789 : : Relation rel;
790 : : TupleDesc descriptor;
791 : : List *inheritOids;
792 : : List *old_constraints;
793 : : List *old_notnulls;
794 : : List *rawDefaults;
795 : : List *cookedDefaults;
796 : : List *nncols;
797 : 40979 : List *connames = NIL;
798 : : Datum reloptions;
799 : : ListCell *listptr;
800 : : AttrNumber attnum;
801 : : bool partitioned;
802 : 40979 : const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
803 : : Oid ofTypeId;
804 : : ObjectAddress address;
805 : : LOCKMODE parentLockmode;
806 : 40979 : Oid accessMethodId = InvalidOid;
807 : :
808 : : /*
809 : : * Truncate relname to appropriate length (probably a waste of time, as
810 : : * parser should have done this already).
811 : : */
812 : 40979 : strlcpy(relname, stmt->relation->relname, NAMEDATALEN);
813 : :
814 : : /*
815 : : * Check consistency of arguments
816 : : */
817 [ + + ]: 40979 : if (stmt->oncommit != ONCOMMIT_NOOP
818 [ + + ]: 124 : && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
819 [ + - ]: 8 : ereport(ERROR,
820 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
821 : : errmsg("ON COMMIT can only be used on temporary tables")));
822 : :
823 [ + + ]: 40971 : if (stmt->partspec != NULL)
824 : : {
825 [ - + ]: 3409 : if (relkind != RELKIND_RELATION)
826 [ # # ]: 0 : elog(ERROR, "unexpected relkind: %d", (int) relkind);
827 : :
828 : 3409 : relkind = RELKIND_PARTITIONED_TABLE;
829 : 3409 : partitioned = true;
830 : : }
831 : : else
832 : 37562 : partitioned = false;
833 : :
834 [ + + ]: 40971 : if (relkind == RELKIND_PARTITIONED_TABLE &&
835 [ + + ]: 3409 : stmt->relation->relpersistence == RELPERSISTENCE_UNLOGGED)
836 [ + - ]: 4 : ereport(ERROR,
837 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
838 : : errmsg("partitioned tables cannot be unlogged")));
839 : :
840 : : /*
841 : : * Look up the namespace in which we are supposed to create the relation,
842 : : * check we have permission to create there, lock it against concurrent
843 : : * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
844 : : * namespace is selected.
845 : : */
846 : : namespaceId =
847 : 40967 : RangeVarGetAndCheckCreationNamespace(stmt->relation, NoLock, NULL);
848 : :
849 : : /*
850 : : * Security check: disallow creating temp tables from security-restricted
851 : : * code. This is needed because calling code might not expect untrusted
852 : : * tables to appear in pg_temp at the front of its search path.
853 : : */
854 [ + + ]: 40967 : if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
855 [ - + ]: 2343 : && InSecurityRestrictedOperation())
856 [ # # ]: 0 : ereport(ERROR,
857 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
858 : : errmsg("cannot create temporary table within security-restricted operation")));
859 : :
860 : : /*
861 : : * Determine the lockmode to use when scanning parents. A self-exclusive
862 : : * lock is needed here.
863 : : *
864 : : * For regular inheritance, if two backends attempt to add children to the
865 : : * same parent simultaneously, and that parent has no pre-existing
866 : : * children, then both will attempt to update the parent's relhassubclass
867 : : * field, leading to a "tuple concurrently updated" error. Also, this
868 : : * interlocks against a concurrent ANALYZE on the parent table, which
869 : : * might otherwise be attempting to clear the parent's relhassubclass
870 : : * field, if its previous children were recently dropped.
871 : : *
872 : : * If the child table is a partition, then we instead grab an exclusive
873 : : * lock on the parent because its partition descriptor will be changed by
874 : : * addition of the new partition.
875 : : */
876 [ + + ]: 40967 : parentLockmode = (stmt->partbound != NULL ? AccessExclusiveLock :
877 : : ShareUpdateExclusiveLock);
878 : :
879 : : /* Determine the list of OIDs of the parents. */
880 : 40967 : inheritOids = NIL;
881 [ + + + + : 48621 : foreach(listptr, stmt->inhRelations)
+ + ]
882 : : {
883 : 7654 : RangeVar *rv = (RangeVar *) lfirst(listptr);
884 : : Oid parentOid;
885 : :
886 : 7654 : parentOid = RangeVarGetRelid(rv, parentLockmode, false);
887 : :
888 : : /*
889 : : * Reject duplications in the list of parents.
890 : : */
891 [ - + ]: 7654 : if (list_member_oid(inheritOids, parentOid))
892 [ # # ]: 0 : ereport(ERROR,
893 : : (errcode(ERRCODE_DUPLICATE_TABLE),
894 : : errmsg("relation \"%s\" would be inherited from more than once",
895 : : get_rel_name(parentOid))));
896 : :
897 : 7654 : inheritOids = lappend_oid(inheritOids, parentOid);
898 : : }
899 : :
900 : : /*
901 : : * Select tablespace to use: an explicitly indicated one, or (in the case
902 : : * of a partitioned table) the parent's, if it has one.
903 : : */
904 [ + + ]: 40967 : if (stmt->tablespacename)
905 : : {
906 : 82 : tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
907 : :
908 [ + + + + ]: 78 : if (partitioned && tablespaceId == MyDatabaseTableSpace)
909 [ + - ]: 4 : ereport(ERROR,
910 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
911 : : errmsg("cannot specify default tablespace for partitioned relations")));
912 : : }
913 [ + + ]: 40885 : else if (stmt->partbound)
914 : : {
915 : : Assert(list_length(inheritOids) == 1);
916 : 5976 : tablespaceId = get_rel_tablespace(linitial_oid(inheritOids));
917 : : }
918 : : else
919 : 34909 : tablespaceId = InvalidOid;
920 : :
921 : : /* still nothing? use the default */
922 [ + + ]: 40959 : if (!OidIsValid(tablespaceId))
923 : 40871 : tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence,
924 : : partitioned);
925 : :
926 : : /* Check permissions except when using database's default */
927 [ + + + + ]: 40955 : if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
928 : : {
929 : : AclResult aclresult;
930 : :
931 : 104 : aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, GetUserId(),
932 : : ACL_CREATE);
933 [ + + ]: 104 : if (aclresult != ACLCHECK_OK)
934 : 3 : aclcheck_error(aclresult, OBJECT_TABLESPACE,
935 : 3 : get_tablespace_name(tablespaceId));
936 : : }
937 : :
938 : : /* In all cases disallow placing user relations in pg_global */
939 [ + + ]: 40952 : if (tablespaceId == GLOBALTABLESPACE_OID)
940 [ + - ]: 12 : ereport(ERROR,
941 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
942 : : errmsg("only shared relations can be placed in pg_global tablespace")));
943 : :
944 : : /* Identify user ID that will own the table */
945 [ + + ]: 40940 : if (!OidIsValid(ownerId))
946 : 40785 : ownerId = GetUserId();
947 : :
948 : : /*
949 : : * Parse and validate reloptions, if any.
950 : : */
951 : 40940 : reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
952 : : true, false);
953 : :
954 [ + + + ]: 40928 : switch (relkind)
955 : : {
956 : 10533 : case RELKIND_VIEW:
957 : 10533 : (void) view_reloptions(reloptions, true);
958 : 10521 : break;
959 : 3393 : case RELKIND_PARTITIONED_TABLE:
960 : 3393 : (void) partitioned_table_reloptions(reloptions, true);
961 : 3385 : break;
962 : 27002 : default:
963 : 27002 : (void) heap_reloptions(relkind, reloptions, true);
964 : : }
965 : :
966 [ + + ]: 40840 : if (stmt->ofTypename)
967 : : {
968 : : AclResult aclresult;
969 : :
970 : 57 : ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
971 : :
972 : 57 : aclresult = object_aclcheck(TypeRelationId, ofTypeId, GetUserId(), ACL_USAGE);
973 [ + + ]: 57 : if (aclresult != ACLCHECK_OK)
974 : 4 : aclcheck_error_type(aclresult, ofTypeId);
975 : : }
976 : : else
977 : 40783 : ofTypeId = InvalidOid;
978 : :
979 : : /*
980 : : * Look up inheritance ancestors and generate relation schema, including
981 : : * inherited attributes. (Note that stmt->tableElts is destructively
982 : : * modified by MergeAttributes.)
983 : : */
984 : 40672 : stmt->tableElts =
985 : 40836 : MergeAttributes(stmt->tableElts, inheritOids,
986 : 40836 : stmt->relation->relpersistence,
987 : 40836 : stmt->partbound != NULL,
988 : : &old_constraints, &old_notnulls);
989 : :
990 : : /*
991 : : * NB: The defaults and constraints we just inherited are already cooked,
992 : : * so they don't get the USAGE checks that AddRelationNewConstraints()
993 : : * applies to raw ones. That's intentional: the parent's own catalog
994 : : * entries already depend on those types, so copying them pins nothing
995 : : * new, and creating a child requires owning the parent, anyway.
996 : : */
997 : :
998 : : /*
999 : : * Create a tuple descriptor from the relation schema. Note that this
1000 : : * deals with column names, types, and in-descriptor NOT NULL flags, but
1001 : : * not default values, NOT NULL or CHECK constraints; we handle those
1002 : : * below.
1003 : : */
1004 : 40672 : descriptor = BuildDescForRelation(stmt->tableElts);
1005 : :
1006 : : /*
1007 : : * Find columns with default values and prepare for insertion of the
1008 : : * defaults. Pre-cooked (that is, inherited) defaults go into a list of
1009 : : * CookedConstraint structs that we'll pass to heap_create_with_catalog,
1010 : : * while raw defaults go into a list of RawColumnDefault structs that will
1011 : : * be processed by AddRelationNewConstraints. (We can't deal with raw
1012 : : * expressions until we can do transformExpr.)
1013 : : */
1014 : 40640 : rawDefaults = NIL;
1015 : 40640 : cookedDefaults = NIL;
1016 : 40640 : attnum = 0;
1017 : :
1018 [ + + + + : 203669 : foreach(listptr, stmt->tableElts)
+ + ]
1019 : : {
1020 : 163029 : ColumnDef *colDef = lfirst(listptr);
1021 : :
1022 : 163029 : attnum++;
1023 [ + + ]: 163029 : if (colDef->raw_default != NULL)
1024 : : {
1025 : : RawColumnDefault *rawEnt;
1026 : :
1027 : : Assert(colDef->cooked_default == NULL);
1028 : :
1029 : 2133 : rawEnt = palloc_object(RawColumnDefault);
1030 : 2133 : rawEnt->attnum = attnum;
1031 : 2133 : rawEnt->raw_default = colDef->raw_default;
1032 : 2133 : rawEnt->generated = colDef->generated;
1033 : 2133 : rawDefaults = lappend(rawDefaults, rawEnt);
1034 : : }
1035 [ + + ]: 160896 : else if (colDef->cooked_default != NULL)
1036 : : {
1037 : : CookedConstraint *cooked;
1038 : :
1039 : 270 : cooked = palloc_object(CookedConstraint);
1040 : 270 : cooked->contype = CONSTR_DEFAULT;
1041 : 270 : cooked->conoid = InvalidOid; /* until created */
1042 : 270 : cooked->name = NULL;
1043 : 270 : cooked->attnum = attnum;
1044 : 270 : cooked->expr = colDef->cooked_default;
1045 : 270 : cooked->is_enforced = true;
1046 : 270 : cooked->skip_validation = false;
1047 : 270 : cooked->is_local = true; /* not used for defaults */
1048 : 270 : cooked->inhcount = 0; /* ditto */
1049 : 270 : cooked->is_no_inherit = false;
1050 : 270 : cookedDefaults = lappend(cookedDefaults, cooked);
1051 : : }
1052 : : }
1053 : :
1054 : 40640 : TupleDescFinalize(descriptor);
1055 : :
1056 : : /*
1057 : : * For relations with table AM and partitioned tables, select access
1058 : : * method to use: an explicitly indicated one, or (in the case of a
1059 : : * partitioned table) the parent's, if it has one.
1060 : : */
1061 [ + + ]: 40640 : if (stmt->accessMethod != NULL)
1062 : : {
1063 : : Assert(RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE);
1064 : 79 : accessMethodId = get_table_am_oid(stmt->accessMethod, false);
1065 : : }
1066 [ + + + - : 40561 : else if (RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE)
+ + + + ]
1067 : : {
1068 [ + + ]: 26155 : if (stmt->partbound)
1069 : : {
1070 : : Assert(list_length(inheritOids) == 1);
1071 : 5861 : accessMethodId = get_rel_relam(linitial_oid(inheritOids));
1072 : : }
1073 : :
1074 [ + + + - : 26155 : if (RELKIND_HAS_TABLE_AM(relkind) && !OidIsValid(accessMethodId))
+ + + + ]
1075 : 22761 : accessMethodId = get_table_am_oid(default_table_access_method, false);
1076 : : }
1077 : :
1078 : : /*
1079 : : * Create the relation. Inherited defaults and CHECK constraints are
1080 : : * passed in for immediate handling --- since they don't need parsing,
1081 : : * they can be stored immediately.
1082 : : */
1083 : 40628 : relationId = heap_create_with_catalog(relname,
1084 : : namespaceId,
1085 : : tablespaceId,
1086 : : InvalidOid,
1087 : : InvalidOid,
1088 : : ofTypeId,
1089 : : ownerId,
1090 : : accessMethodId,
1091 : : descriptor,
1092 : : list_concat(cookedDefaults,
1093 : : old_constraints),
1094 : : relkind,
1095 : 40628 : stmt->relation->relpersistence,
1096 : : false,
1097 : : false,
1098 : : stmt->oncommit,
1099 : : reloptions,
1100 : : true,
1101 : : allowSystemTableMods,
1102 : : false,
1103 : : InvalidOid,
1104 : : typaddress);
1105 : :
1106 : : /*
1107 : : * We must bump the command counter to make the newly-created relation
1108 : : * tuple visible for opening.
1109 : : */
1110 : 40595 : CommandCounterIncrement();
1111 : :
1112 : : /*
1113 : : * Open the new relation and acquire exclusive lock on it. This isn't
1114 : : * really necessary for locking out other backends (since they can't see
1115 : : * the new rel anyway until we commit), but it keeps the lock manager from
1116 : : * complaining about deadlock risks.
1117 : : */
1118 : 40595 : rel = relation_open(relationId, AccessExclusiveLock);
1119 : :
1120 : : /*
1121 : : * Now add any newly specified column default and generation expressions
1122 : : * to the new relation. These are passed to us in the form of raw
1123 : : * parsetrees; we need to transform them to executable expression trees
1124 : : * before they can be added. The most convenient way to do that is to
1125 : : * apply the parser's transformExpr routine, but transformExpr doesn't
1126 : : * work unless we have a pre-existing relation. So, the transformation has
1127 : : * to be postponed to this final step of CREATE TABLE.
1128 : : *
1129 : : * This needs to be before processing the partitioning clauses because
1130 : : * those could refer to generated columns.
1131 : : */
1132 [ + + ]: 40595 : if (rawDefaults)
1133 : 1827 : AddRelationNewConstraints(rel, rawDefaults, NIL,
1134 : : true, true, false, queryString);
1135 : :
1136 : : /*
1137 : : * Make column generation expressions visible for use by partitioning.
1138 : : */
1139 : 40463 : CommandCounterIncrement();
1140 : :
1141 : : /* Process and store partition bound, if any. */
1142 [ + + ]: 40463 : if (stmt->partbound)
1143 : : {
1144 : : PartitionBoundSpec *bound;
1145 : : ParseState *pstate;
1146 : 5924 : Oid parentId = linitial_oid(inheritOids),
1147 : : defaultPartOid;
1148 : : Relation parent,
1149 : 5924 : defaultRel = NULL;
1150 : : ParseNamespaceItem *nsitem;
1151 : :
1152 : : /* Already have strong enough lock on the parent */
1153 : 5924 : parent = table_open(parentId, NoLock);
1154 : :
1155 : : /*
1156 : : * We are going to try to validate the partition bound specification
1157 : : * against the partition key of parentRel, so it better have one.
1158 : : */
1159 [ + + ]: 5924 : if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
1160 [ + - ]: 12 : ereport(ERROR,
1161 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1162 : : errmsg("\"%s\" is not partitioned",
1163 : : RelationGetRelationName(parent))));
1164 : :
1165 : : /*
1166 : : * The partition constraint of the default partition depends on the
1167 : : * partition bounds of every other partition. It is possible that
1168 : : * another backend might be about to execute a query on the default
1169 : : * partition table, and that the query relies on previously cached
1170 : : * default partition constraints. We must therefore take a table lock
1171 : : * strong enough to prevent all queries on the default partition from
1172 : : * proceeding until we commit and send out a shared-cache-inval notice
1173 : : * that will make them update their index lists.
1174 : : *
1175 : : * Order of locking: The relation being added won't be visible to
1176 : : * other backends until it is committed, hence here in
1177 : : * DefineRelation() the order of locking the default partition and the
1178 : : * relation being added does not matter. But at all other places we
1179 : : * need to lock the default relation before we lock the relation being
1180 : : * added or removed i.e. we should take the lock in same order at all
1181 : : * the places such that lock parent, lock default partition and then
1182 : : * lock the partition so as to avoid a deadlock.
1183 : : */
1184 : : defaultPartOid =
1185 : 5912 : get_default_oid_from_partdesc(RelationGetPartitionDesc(parent,
1186 : : true));
1187 [ + + ]: 5912 : if (OidIsValid(defaultPartOid))
1188 : 267 : defaultRel = table_open(defaultPartOid, AccessExclusiveLock);
1189 : :
1190 : : /* Transform the bound values */
1191 : 5912 : pstate = make_parsestate(NULL);
1192 : 5912 : pstate->p_sourcetext = queryString;
1193 : :
1194 : : /*
1195 : : * Add an nsitem containing this relation, so that transformExpr
1196 : : * called on partition bound expressions is able to report errors
1197 : : * using a proper context.
1198 : : */
1199 : 5912 : nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
1200 : : NULL, false, false);
1201 : 5912 : addNSItemToQuery(pstate, nsitem, false, true, true);
1202 : :
1203 : 5912 : bound = transformPartitionBound(pstate, parent, stmt->partbound);
1204 : :
1205 : : /*
1206 : : * Check first that the new partition's bound is valid and does not
1207 : : * overlap with any of existing partitions of the parent.
1208 : : */
1209 : 5776 : check_new_partition_bound(relname, parent, bound, pstate);
1210 : :
1211 : : /*
1212 : : * If the default partition exists, its partition constraints will
1213 : : * change after the addition of this new partition such that it won't
1214 : : * allow any row that qualifies for this new partition. So, check that
1215 : : * the existing data in the default partition satisfies the constraint
1216 : : * as it will exist after adding this partition.
1217 : : */
1218 [ + + ]: 5700 : if (OidIsValid(defaultPartOid))
1219 : : {
1220 : 247 : check_default_partition_contents(parent, defaultRel, bound);
1221 : : /* Keep the lock until commit. */
1222 : 235 : table_close(defaultRel, NoLock);
1223 : : }
1224 : :
1225 : : /* Update the pg_class entry. */
1226 : 5688 : StorePartitionBound(rel, parent, bound);
1227 : :
1228 : 5688 : table_close(parent, NoLock);
1229 : : }
1230 : :
1231 : : /* Store inheritance information for new rel. */
1232 : 40227 : StoreCatalogInheritance(relationId, inheritOids, stmt->partbound != NULL);
1233 : :
1234 : : /*
1235 : : * Process the partitioning specification (if any) and store the partition
1236 : : * key information into the catalog.
1237 : : */
1238 [ + + ]: 40227 : if (partitioned)
1239 : : {
1240 : : ParseState *pstate;
1241 : : int partnatts;
1242 : : AttrNumber partattrs[PARTITION_MAX_KEYS];
1243 : : Oid partopclass[PARTITION_MAX_KEYS];
1244 : : Oid partcollation[PARTITION_MAX_KEYS];
1245 : 3384 : List *partexprs = NIL;
1246 : :
1247 : 3384 : pstate = make_parsestate(NULL);
1248 : 3384 : pstate->p_sourcetext = queryString;
1249 : :
1250 : 3384 : partnatts = list_length(stmt->partspec->partParams);
1251 : :
1252 : : /* Protect fixed-size arrays here and in executor */
1253 [ - + ]: 3384 : if (partnatts > PARTITION_MAX_KEYS)
1254 [ # # ]: 0 : ereport(ERROR,
1255 : : (errcode(ERRCODE_TOO_MANY_COLUMNS),
1256 : : errmsg("cannot partition using more than %d columns",
1257 : : PARTITION_MAX_KEYS)));
1258 : :
1259 : : /*
1260 : : * We need to transform the raw parsetrees corresponding to partition
1261 : : * expressions into executable expression trees. Like column defaults
1262 : : * and CHECK constraints, we could not have done the transformation
1263 : : * earlier.
1264 : : */
1265 : 3384 : stmt->partspec = transformPartitionSpec(rel, stmt->partspec);
1266 : :
1267 : 3364 : ComputePartitionAttrs(pstate, rel, stmt->partspec->partParams,
1268 : : partattrs, &partexprs, partopclass,
1269 : 3364 : partcollation, stmt->partspec->strategy);
1270 : :
1271 : 3276 : StorePartitionKey(rel, stmt->partspec->strategy, partnatts, partattrs,
1272 : : partexprs,
1273 : : partopclass, partcollation);
1274 : :
1275 : : /* make it all visible */
1276 : 3272 : CommandCounterIncrement();
1277 : : }
1278 : :
1279 : : /*
1280 : : * If we're creating a partition, create now all the indexes, triggers,
1281 : : * FKs defined in the parent.
1282 : : *
1283 : : * We can't do it earlier, because DefineIndex wants to know the partition
1284 : : * key which we just stored.
1285 : : */
1286 [ + + ]: 40115 : if (stmt->partbound)
1287 : : {
1288 : 5684 : Oid parentId = linitial_oid(inheritOids);
1289 : : Relation parent;
1290 : : List *idxlist;
1291 : : ListCell *cell;
1292 : :
1293 : : /* Already have strong enough lock on the parent */
1294 : 5684 : parent = table_open(parentId, NoLock);
1295 : 5684 : idxlist = RelationGetIndexList(parent);
1296 : :
1297 : : /*
1298 : : * For each index in the parent table, create one in the partition
1299 : : */
1300 [ + + + + : 6625 : foreach(cell, idxlist)
+ + ]
1301 : : {
1302 : 953 : Relation idxRel = index_open(lfirst_oid(cell), AccessShareLock);
1303 : : AttrMap *attmap;
1304 : : IndexStmt *idxstmt;
1305 : : Oid constraintOid;
1306 : :
1307 [ + + ]: 953 : if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1308 : : {
1309 [ + + ]: 24 : if (idxRel->rd_index->indisunique)
1310 [ + - ]: 8 : ereport(ERROR,
1311 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1312 : : errmsg("cannot create foreign partition of partitioned table \"%s\"",
1313 : : RelationGetRelationName(parent)),
1314 : : errdetail("Table \"%s\" contains indexes that are unique.",
1315 : : RelationGetRelationName(parent))));
1316 : : else
1317 : : {
1318 : 16 : index_close(idxRel, AccessShareLock);
1319 : 16 : continue;
1320 : : }
1321 : : }
1322 : :
1323 : 929 : attmap = build_attrmap_by_name(RelationGetDescr(rel),
1324 : : RelationGetDescr(parent),
1325 : : false);
1326 : : idxstmt =
1327 : 929 : generateClonedIndexStmt(NULL, idxRel,
1328 : : attmap, &constraintOid);
1329 : 929 : DefineIndex(NULL,
1330 : : RelationGetRelid(rel),
1331 : : idxstmt,
1332 : : InvalidOid,
1333 : : RelationGetRelid(idxRel),
1334 : : constraintOid,
1335 : : -1,
1336 : : false, false, false, false, false);
1337 : :
1338 : 925 : index_close(idxRel, AccessShareLock);
1339 : : }
1340 : :
1341 : 5672 : list_free(idxlist);
1342 : :
1343 : : /*
1344 : : * If there are any row-level triggers, clone them to the new
1345 : : * partition.
1346 : : */
1347 [ + + ]: 5672 : if (parent->trigdesc != NULL)
1348 : 232 : CloneRowTriggersToPartition(parent, rel);
1349 : :
1350 : : /*
1351 : : * And foreign keys too. Note that because we're freshly creating the
1352 : : * table, there is no need to verify these new constraints.
1353 : : */
1354 : 5672 : CloneForeignKeyConstraints(NULL, parent, rel);
1355 : :
1356 : 5672 : table_close(parent, NoLock);
1357 : : }
1358 : :
1359 : : /*
1360 : : * Now add any newly specified CHECK constraints to the new relation. Same
1361 : : * as for defaults above, but these need to come after partitioning is set
1362 : : * up. We save the constraint names that were used, to avoid dupes below.
1363 : : */
1364 [ + + ]: 40103 : if (stmt->constraints)
1365 : : {
1366 : : List *conlist;
1367 : :
1368 : 522 : conlist = AddRelationNewConstraints(rel, NIL, stmt->constraints,
1369 : : true, true, false, queryString);
1370 [ + + + + : 1569 : foreach_ptr(CookedConstraint, cons, conlist)
+ + ]
1371 : : {
1372 [ + - ]: 573 : if (cons->name != NULL)
1373 : 573 : connames = lappend(connames, cons->name);
1374 : : }
1375 : : }
1376 : :
1377 : : /*
1378 : : * Finally, merge the not-null constraints that are declared directly with
1379 : : * those that come from parent relations (making sure to count inheritance
1380 : : * appropriately for each), create them, and set the attnotnull flag on
1381 : : * columns that don't yet have it.
1382 : : */
1383 : 40079 : nncols = AddRelationNotNullConstraints(rel, stmt->nnconstraints,
1384 : : old_notnulls, connames);
1385 [ + + + + : 89703 : foreach_int(attrnum, nncols)
+ + ]
1386 : 9649 : set_attnotnull(NULL, rel, attrnum, false);
1387 : :
1388 : 40027 : ObjectAddressSet(address, RelationRelationId, relationId);
1389 : :
1390 : : /*
1391 : : * Clean up. We keep lock on new relation (although it shouldn't be
1392 : : * visible to anyone else anyway, until commit).
1393 : : */
1394 : 40027 : relation_close(rel, NoLock);
1395 : :
1396 : 40027 : return address;
1397 : : }
1398 : :
1399 : : /*
1400 : : * BuildDescForRelation
1401 : : *
1402 : : * Given a list of ColumnDef nodes, build a TupleDesc.
1403 : : *
1404 : : * Note: This is only for the limited purpose of table and view creation. Not
1405 : : * everything is filled in. A real tuple descriptor should be obtained from
1406 : : * the relcache.
1407 : : */
1408 : : TupleDesc
1409 : 42802 : BuildDescForRelation(const List *columns)
1410 : : {
1411 : : int natts;
1412 : : AttrNumber attnum;
1413 : : ListCell *l;
1414 : : TupleDesc desc;
1415 : : char *attname;
1416 : : Oid atttypid;
1417 : : int32 atttypmod;
1418 : : Oid attcollation;
1419 : : int attdim;
1420 : :
1421 : : /*
1422 : : * allocate a new tuple descriptor
1423 : : */
1424 : 42802 : natts = list_length(columns);
1425 : 42802 : desc = CreateTemplateTupleDesc(natts);
1426 : :
1427 : 42802 : attnum = 0;
1428 : :
1429 [ + + + + : 208185 : foreach(l, columns)
+ + ]
1430 : : {
1431 : 165423 : ColumnDef *entry = lfirst(l);
1432 : : AclResult aclresult;
1433 : : Form_pg_attribute att;
1434 : :
1435 : : /*
1436 : : * for each entry in the list, get the name and type information from
1437 : : * the list and have TupleDescInitEntry fill in the attribute
1438 : : * information we need.
1439 : : */
1440 : 165423 : attnum++;
1441 : :
1442 : 165423 : attname = entry->colname;
1443 : 165423 : typenameTypeIdAndMod(NULL, entry->typeName, &atttypid, &atttypmod);
1444 : :
1445 : 165423 : aclresult = object_aclcheck(TypeRelationId, atttypid, GetUserId(), ACL_USAGE);
1446 [ + + ]: 165423 : if (aclresult != ACLCHECK_OK)
1447 : 28 : aclcheck_error_type(aclresult, atttypid);
1448 : :
1449 : 165395 : attcollation = GetColumnDefCollation(NULL, entry, atttypid);
1450 : 165395 : attdim = list_length(entry->typeName->arrayBounds);
1451 [ - + ]: 165395 : if (attdim > PG_INT16_MAX)
1452 [ # # ]: 0 : ereport(ERROR,
1453 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1454 : : errmsg("too many array dimensions"));
1455 : :
1456 [ - + ]: 165395 : if (entry->typeName->setof)
1457 [ # # ]: 0 : ereport(ERROR,
1458 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1459 : : errmsg("column \"%s\" cannot be declared SETOF",
1460 : : attname)));
1461 : :
1462 : 165395 : TupleDescInitEntry(desc, attnum, attname,
1463 : : atttypid, atttypmod, attdim);
1464 : 165395 : att = TupleDescAttr(desc, attnum - 1);
1465 : :
1466 : : /* Override TupleDescInitEntry's settings as requested */
1467 : 165395 : TupleDescInitEntryCollation(desc, attnum, attcollation);
1468 : :
1469 : : /* Fill in additional stuff not handled by TupleDescInitEntry */
1470 : 165395 : att->attnotnull = entry->is_not_null;
1471 : 165395 : att->attislocal = entry->is_local;
1472 : 165395 : att->attinhcount = entry->inhcount;
1473 : 165395 : att->attidentity = entry->identity;
1474 : 165395 : att->attgenerated = entry->generated;
1475 : 165395 : att->attcompression = GetAttributeCompression(att->atttypid, entry->compression);
1476 [ + + ]: 165387 : if (entry->storage)
1477 : 14077 : att->attstorage = entry->storage;
1478 [ + + ]: 151310 : else if (entry->storage_name)
1479 : 24 : att->attstorage = GetAttributeStorage(att->atttypid, entry->storage_name);
1480 : :
1481 : 165383 : populate_compact_attribute(desc, attnum - 1);
1482 : : }
1483 : :
1484 : 42762 : TupleDescFinalize(desc);
1485 : :
1486 : 42762 : return desc;
1487 : : }
1488 : :
1489 : : /*
1490 : : * Emit the right error or warning message for a "DROP" command issued on a
1491 : : * non-existent relation
1492 : : */
1493 : : static void
1494 : 613 : DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
1495 : : {
1496 : : const struct dropmsgstrings *rentry;
1497 : :
1498 [ + + + + ]: 693 : if (rel->schemaname != NULL &&
1499 : 80 : !OidIsValid(LookupNamespaceNoError(rel->schemaname)))
1500 : : {
1501 [ - + ]: 28 : if (!missing_ok)
1502 : : {
1503 [ # # ]: 0 : ereport(ERROR,
1504 : : (errcode(ERRCODE_UNDEFINED_SCHEMA),
1505 : : errmsg("schema \"%s\" does not exist", rel->schemaname)));
1506 : : }
1507 : : else
1508 : : {
1509 [ + - ]: 28 : ereport(NOTICE,
1510 : : (errmsg("schema \"%s\" does not exist, skipping",
1511 : : rel->schemaname)));
1512 : : }
1513 : 28 : return;
1514 : : }
1515 : :
1516 [ + - ]: 798 : for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
1517 : : {
1518 [ + + ]: 798 : if (rentry->kind == rightkind)
1519 : : {
1520 [ + + ]: 585 : if (!missing_ok)
1521 : : {
1522 [ + - ]: 86 : ereport(ERROR,
1523 : : (errcode(rentry->nonexistent_code),
1524 : : errmsg(rentry->nonexistent_msg, rel->relname)));
1525 : : }
1526 : : else
1527 : : {
1528 [ + + ]: 499 : ereport(NOTICE, (errmsg(rentry->skipping_msg, rel->relname)));
1529 : 499 : break;
1530 : : }
1531 : : }
1532 : : }
1533 : :
1534 : : Assert(rentry->kind != '\0'); /* Should be impossible */
1535 : : }
1536 : :
1537 : : /*
1538 : : * Emit the right error message for a "DROP" command issued on a
1539 : : * relation of the wrong type
1540 : : */
1541 : : static void
1542 : 0 : DropErrorMsgWrongType(const char *relname, char wrongkind, char rightkind)
1543 : : {
1544 : : const struct dropmsgstrings *rentry;
1545 : : const struct dropmsgstrings *wentry;
1546 : :
1547 [ # # ]: 0 : for (rentry = dropmsgstringarray; rentry->kind != '\0'; rentry++)
1548 [ # # ]: 0 : if (rentry->kind == rightkind)
1549 : 0 : break;
1550 : : Assert(rentry->kind != '\0');
1551 : :
1552 [ # # ]: 0 : for (wentry = dropmsgstringarray; wentry->kind != '\0'; wentry++)
1553 [ # # ]: 0 : if (wentry->kind == wrongkind)
1554 : 0 : break;
1555 : : /* wrongkind could be something we don't have in our table... */
1556 : :
1557 [ # # # # ]: 0 : ereport(ERROR,
1558 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1559 : : errmsg(rentry->nota_msg, relname),
1560 : : (wentry->kind != '\0') ? errhint("%s", _(wentry->drophint_msg)) : 0));
1561 : : }
1562 : :
1563 : : /*
1564 : : * RemoveRelations
1565 : : * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW,
1566 : : * DROP MATERIALIZED VIEW, DROP FOREIGN TABLE
1567 : : */
1568 : : void
1569 : 11457 : RemoveRelations(DropStmt *drop)
1570 : : {
1571 : : ObjectAddresses *objects;
1572 : : char relkind;
1573 : : ListCell *cell;
1574 : 11457 : int flags = 0;
1575 : 11457 : LOCKMODE lockmode = AccessExclusiveLock;
1576 : :
1577 : : /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
1578 [ + + ]: 11457 : if (drop->concurrent)
1579 : : {
1580 : : /*
1581 : : * Note that for temporary relations this lock may get upgraded later
1582 : : * on, but as no other session can access a temporary relation, this
1583 : : * is actually fine.
1584 : : */
1585 : 103 : lockmode = ShareUpdateExclusiveLock;
1586 : : Assert(drop->removeType == OBJECT_INDEX);
1587 [ + + ]: 103 : if (list_length(drop->objects) != 1)
1588 [ + - ]: 4 : ereport(ERROR,
1589 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1590 : : errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
1591 [ - + ]: 99 : if (drop->behavior == DROP_CASCADE)
1592 [ # # ]: 0 : ereport(ERROR,
1593 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1594 : : errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
1595 : : }
1596 : :
1597 : : /*
1598 : : * First we identify all the relations, then we delete them in a single
1599 : : * performMultipleDeletions() call. This is to avoid unwanted DROP
1600 : : * RESTRICT errors if one of the relations depends on another.
1601 : : */
1602 : :
1603 : : /* Determine required relkind */
1604 [ + + + + : 11453 : switch (drop->removeType)
+ + - ]
1605 : : {
1606 : 9914 : case OBJECT_TABLE:
1607 : 9914 : relkind = RELKIND_RELATION;
1608 : 9914 : break;
1609 : :
1610 : 550 : case OBJECT_INDEX:
1611 : 550 : relkind = RELKIND_INDEX;
1612 : 550 : break;
1613 : :
1614 : 123 : case OBJECT_SEQUENCE:
1615 : 123 : relkind = RELKIND_SEQUENCE;
1616 : 123 : break;
1617 : :
1618 : 672 : case OBJECT_VIEW:
1619 : 672 : relkind = RELKIND_VIEW;
1620 : 672 : break;
1621 : :
1622 : 84 : case OBJECT_MATVIEW:
1623 : 84 : relkind = RELKIND_MATVIEW;
1624 : 84 : break;
1625 : :
1626 : 110 : case OBJECT_FOREIGN_TABLE:
1627 : 110 : relkind = RELKIND_FOREIGN_TABLE;
1628 : 110 : break;
1629 : :
1630 : 0 : default:
1631 [ # # ]: 0 : elog(ERROR, "unrecognized drop object type: %d",
1632 : : (int) drop->removeType);
1633 : : relkind = 0; /* keep compiler quiet */
1634 : : break;
1635 : : }
1636 : :
1637 : : /* Lock and validate each relation; build a list of object addresses */
1638 : 11453 : objects = new_object_addresses();
1639 : :
1640 [ + - + + : 25441 : foreach(cell, drop->objects)
+ + ]
1641 : : {
1642 : 14095 : RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
1643 : : Oid relOid;
1644 : : ObjectAddress obj;
1645 : : struct DropRelationCallbackState state;
1646 : :
1647 : : /*
1648 : : * These next few steps are a great deal like relation_openrv, but we
1649 : : * don't bother building a relcache entry since we don't need it.
1650 : : *
1651 : : * Check for shared-cache-inval messages before trying to access the
1652 : : * relation. This is needed to cover the case where the name
1653 : : * identifies a rel that has been dropped and recreated since the
1654 : : * start of our transaction: if we don't flush the old syscache entry,
1655 : : * then we'll latch onto that entry and suffer an error later.
1656 : : */
1657 : 14095 : AcceptInvalidationMessages();
1658 : :
1659 : : /* Look up the appropriate relation using namespace search. */
1660 : 14095 : state.expected_relkind = relkind;
1661 : 28190 : state.heap_lockmode = drop->concurrent ?
1662 [ + + ]: 14095 : ShareUpdateExclusiveLock : AccessExclusiveLock;
1663 : : /* We must initialize these fields to show that no locks are held: */
1664 : 14095 : state.heapOid = InvalidOid;
1665 : 14095 : state.partParentOid = InvalidOid;
1666 : :
1667 : 14095 : relOid = RangeVarGetRelidExtended(rel, lockmode, RVR_MISSING_OK,
1668 : : RangeVarCallbackForDropRelation,
1669 : : &state);
1670 : :
1671 : : /* Not there? */
1672 [ + + ]: 14078 : if (!OidIsValid(relOid))
1673 : : {
1674 : 613 : DropErrorMsgNonExistent(rel, relkind, drop->missing_ok);
1675 : 527 : continue;
1676 : : }
1677 : :
1678 : : /*
1679 : : * Decide if concurrent mode needs to be used here or not. The
1680 : : * callback retrieved the rel's persistence for us.
1681 : : */
1682 [ + + ]: 13465 : if (drop->concurrent &&
1683 [ + + ]: 95 : state.actual_relpersistence != RELPERSISTENCE_TEMP)
1684 : : {
1685 : : Assert(list_length(drop->objects) == 1 &&
1686 : : drop->removeType == OBJECT_INDEX);
1687 : 83 : flags |= PERFORM_DELETION_CONCURRENTLY;
1688 : : }
1689 : :
1690 : : /*
1691 : : * Concurrent index drop cannot be used with partitioned indexes,
1692 : : * either.
1693 : : */
1694 [ + + ]: 13465 : if ((flags & PERFORM_DELETION_CONCURRENTLY) != 0 &&
1695 [ + + ]: 83 : state.actual_relkind == RELKIND_PARTITIONED_INDEX)
1696 [ + - ]: 4 : ereport(ERROR,
1697 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1698 : : errmsg("cannot drop partitioned index \"%s\" concurrently",
1699 : : rel->relname)));
1700 : :
1701 : : /*
1702 : : * If we're told to drop a partitioned index, we must acquire lock on
1703 : : * all the children of its parent partitioned table before proceeding.
1704 : : * Otherwise we'd try to lock the child index partitions before their
1705 : : * tables, leading to potential deadlock against other sessions that
1706 : : * will lock those objects in the other order.
1707 : : */
1708 [ + + ]: 13461 : if (state.actual_relkind == RELKIND_PARTITIONED_INDEX)
1709 : 50 : (void) find_all_inheritors(state.heapOid,
1710 : : state.heap_lockmode,
1711 : : NULL);
1712 : :
1713 : : /* OK, we're ready to delete this one */
1714 : 13461 : obj.classId = RelationRelationId;
1715 : 13461 : obj.objectId = relOid;
1716 : 13461 : obj.objectSubId = 0;
1717 : :
1718 : 13461 : add_exact_object_address(&obj, objects);
1719 : : }
1720 : :
1721 : 11346 : performMultipleDeletions(objects, drop->behavior, flags);
1722 : :
1723 : 11251 : free_object_addresses(objects);
1724 : 11251 : }
1725 : :
1726 : : /*
1727 : : * Before acquiring a table lock, check whether we have sufficient rights.
1728 : : * In the case of DROP INDEX, also try to lock the table before the index.
1729 : : * Also, if the table to be dropped is a partition, we try to lock the parent
1730 : : * first.
1731 : : */
1732 : : static void
1733 : 14308 : RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid,
1734 : : void *arg)
1735 : : {
1736 : : HeapTuple tuple;
1737 : : struct DropRelationCallbackState *state;
1738 : : char expected_relkind;
1739 : : bool is_partition;
1740 : : Form_pg_class classform;
1741 : : LOCKMODE heap_lockmode;
1742 : 14308 : bool invalid_system_index = false;
1743 : :
1744 : 14308 : state = (struct DropRelationCallbackState *) arg;
1745 : 14308 : heap_lockmode = state->heap_lockmode;
1746 : :
1747 : : /*
1748 : : * If we previously locked some other index's heap, and the name we're
1749 : : * looking up no longer refers to that relation, release the now-useless
1750 : : * lock.
1751 : : */
1752 [ + + - + ]: 14308 : if (relOid != oldRelOid && OidIsValid(state->heapOid))
1753 : : {
1754 : 0 : UnlockRelationOid(state->heapOid, heap_lockmode);
1755 : 0 : state->heapOid = InvalidOid;
1756 : : }
1757 : :
1758 : : /*
1759 : : * Similarly, if we previously locked some other partition's heap, and the
1760 : : * name we're looking up no longer refers to that relation, release the
1761 : : * now-useless lock.
1762 : : */
1763 [ + + - + ]: 14308 : if (relOid != oldRelOid && OidIsValid(state->partParentOid))
1764 : : {
1765 : 0 : UnlockRelationOid(state->partParentOid, AccessExclusiveLock);
1766 : 0 : state->partParentOid = InvalidOid;
1767 : : }
1768 : :
1769 : : /* Didn't find a relation, so no need for locking or permission checks. */
1770 [ + + ]: 14308 : if (!OidIsValid(relOid))
1771 : 614 : return;
1772 : :
1773 : 13694 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
1774 [ - + ]: 13694 : if (!HeapTupleIsValid(tuple))
1775 : 0 : return; /* concurrently dropped, so nothing to do */
1776 : 13694 : classform = (Form_pg_class) GETSTRUCT(tuple);
1777 : 13694 : is_partition = classform->relispartition;
1778 : :
1779 : : /* Pass back some data to save lookups in RemoveRelations */
1780 : 13694 : state->actual_relkind = classform->relkind;
1781 : 13694 : state->actual_relpersistence = classform->relpersistence;
1782 : :
1783 : : /*
1784 : : * Both RELKIND_RELATION and RELKIND_PARTITIONED_TABLE are OBJECT_TABLE,
1785 : : * but RemoveRelations() can only pass one relkind for a given relation.
1786 : : * It chooses RELKIND_RELATION for both regular and partitioned tables.
1787 : : * That means we must be careful before giving the wrong type error when
1788 : : * the relation is RELKIND_PARTITIONED_TABLE. An equivalent problem
1789 : : * exists with indexes.
1790 : : */
1791 [ + + ]: 13694 : if (classform->relkind == RELKIND_PARTITIONED_TABLE)
1792 : 1991 : expected_relkind = RELKIND_RELATION;
1793 [ + + ]: 11703 : else if (classform->relkind == RELKIND_PARTITIONED_INDEX)
1794 : 56 : expected_relkind = RELKIND_INDEX;
1795 : : else
1796 : 11647 : expected_relkind = classform->relkind;
1797 : :
1798 [ - + ]: 13694 : if (state->expected_relkind != expected_relkind)
1799 : 0 : DropErrorMsgWrongType(rel->relname, classform->relkind,
1800 : 0 : state->expected_relkind);
1801 : :
1802 : : /* Allow DROP to either table owner or schema owner */
1803 [ + + ]: 13694 : if (!object_ownercheck(RelationRelationId, relOid, GetUserId()) &&
1804 [ + - ]: 12 : !object_ownercheck(NamespaceRelationId, classform->relnamespace, GetUserId()))
1805 : 12 : aclcheck_error(ACLCHECK_NOT_OWNER,
1806 : 12 : get_relkind_objtype(classform->relkind),
1807 : 12 : rel->relname);
1808 : :
1809 : : /*
1810 : : * Check the case of a system index that might have been invalidated by a
1811 : : * failed concurrent process and allow its drop. For the time being, this
1812 : : * only concerns indexes of toast relations that became invalid during a
1813 : : * REINDEX CONCURRENTLY process.
1814 : : */
1815 [ + + - + ]: 13682 : if (IsSystemClass(relOid, classform) && classform->relkind == RELKIND_INDEX)
1816 : : {
1817 : : HeapTuple locTuple;
1818 : : Form_pg_index indexform;
1819 : : bool indisvalid;
1820 : :
1821 : 0 : locTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(relOid));
1822 [ # # ]: 0 : if (!HeapTupleIsValid(locTuple))
1823 : : {
1824 : 0 : ReleaseSysCache(tuple);
1825 : 0 : return;
1826 : : }
1827 : :
1828 : 0 : indexform = (Form_pg_index) GETSTRUCT(locTuple);
1829 : 0 : indisvalid = indexform->indisvalid;
1830 : 0 : ReleaseSysCache(locTuple);
1831 : :
1832 : : /* Mark object as being an invalid index of system catalogs */
1833 [ # # ]: 0 : if (!indisvalid)
1834 : 0 : invalid_system_index = true;
1835 : : }
1836 : :
1837 : : /* In the case of an invalid index, it is fine to bypass this check */
1838 [ + - + + : 13682 : if (!invalid_system_index && !allowSystemTableMods && IsSystemClass(relOid, classform))
+ + ]
1839 [ + - ]: 5 : ereport(ERROR,
1840 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1841 : : errmsg("permission denied: \"%s\" is a system catalog",
1842 : : rel->relname)));
1843 : :
1844 : 13677 : ReleaseSysCache(tuple);
1845 : :
1846 : : /*
1847 : : * In DROP INDEX, attempt to acquire lock on the parent table before
1848 : : * locking the index. index_drop() will need this anyway, and since
1849 : : * regular queries lock tables before their indexes, we risk deadlock if
1850 : : * we do it the other way around. No error if we don't find a pg_index
1851 : : * entry, though --- the relation may have been dropped. Note that this
1852 : : * code will execute for either plain or partitioned indexes.
1853 : : */
1854 [ + + + + ]: 13677 : if (expected_relkind == RELKIND_INDEX &&
1855 : : relOid != oldRelOid)
1856 : : {
1857 : 542 : state->heapOid = IndexGetRelation(relOid, true);
1858 [ + - ]: 542 : if (OidIsValid(state->heapOid))
1859 : 542 : LockRelationOid(state->heapOid, heap_lockmode);
1860 : : }
1861 : :
1862 : : /*
1863 : : * Similarly, if the relation is a partition, we must acquire lock on its
1864 : : * parent before locking the partition. That's because queries lock the
1865 : : * parent before its partitions, so we risk deadlock if we do it the other
1866 : : * way around.
1867 : : */
1868 [ + + + + ]: 13677 : if (is_partition && relOid != oldRelOid)
1869 : : {
1870 : 403 : state->partParentOid = get_partition_parent(relOid, true);
1871 [ + - ]: 403 : if (OidIsValid(state->partParentOid))
1872 : 403 : LockRelationOid(state->partParentOid, AccessExclusiveLock);
1873 : : }
1874 : : }
1875 : :
1876 : : /*
1877 : : * ExecuteTruncate
1878 : : * Executes a TRUNCATE command.
1879 : : *
1880 : : * This is a multi-relation truncate. We first open and grab exclusive
1881 : : * lock on all relations involved, checking permissions and otherwise
1882 : : * verifying that the relation is OK for truncation. Note that if relations
1883 : : * are foreign tables, at this stage, we have not yet checked that their
1884 : : * foreign data in external data sources are OK for truncation. These are
1885 : : * checked when foreign data are actually truncated later. In CASCADE mode,
1886 : : * relations having FK references to the targeted relations are automatically
1887 : : * added to the group; in RESTRICT mode, we check that all FK references are
1888 : : * internal to the group that's being truncated. Finally all the relations
1889 : : * are truncated and reindexed.
1890 : : */
1891 : : void
1892 : 1174 : ExecuteTruncate(TruncateStmt *stmt)
1893 : : {
1894 : 1174 : List *rels = NIL;
1895 : 1174 : List *relids = NIL;
1896 : 1174 : List *relids_logged = NIL;
1897 : : ListCell *cell;
1898 : :
1899 : : /*
1900 : : * Open, exclusive-lock, and check all the explicitly-specified relations
1901 : : */
1902 [ + - + + : 2484 : foreach(cell, stmt->relations)
+ + ]
1903 : : {
1904 : 1346 : RangeVar *rv = lfirst(cell);
1905 : : Relation rel;
1906 : 1346 : bool recurse = rv->inh;
1907 : : Oid myrelid;
1908 : 1346 : LOCKMODE lockmode = AccessExclusiveLock;
1909 : :
1910 : 1346 : myrelid = RangeVarGetRelidExtended(rv, lockmode,
1911 : : 0, RangeVarCallbackForTruncate,
1912 : : NULL);
1913 : :
1914 : : /* don't throw error for "TRUNCATE foo, foo" */
1915 [ + + ]: 1323 : if (list_member_oid(relids, myrelid))
1916 : 1 : continue;
1917 : :
1918 : : /* open the relation, we already hold a lock on it */
1919 : 1322 : rel = table_open(myrelid, NoLock);
1920 : :
1921 : : /*
1922 : : * RangeVarGetRelidExtended() has done most checks with its callback,
1923 : : * but other checks with the now-opened Relation remain.
1924 : : */
1925 : 1322 : truncate_check_activity(rel);
1926 : :
1927 : 1317 : rels = lappend(rels, rel);
1928 : 1317 : relids = lappend_oid(relids, myrelid);
1929 : :
1930 : : /* Log this relation only if needed for logical decoding */
1931 [ + + - + : 1317 : if (RelationIsLogicallyLogged(rel))
+ - - + -
- - - + -
+ + ]
1932 : 39 : relids_logged = lappend_oid(relids_logged, myrelid);
1933 : :
1934 [ + + ]: 1317 : if (recurse)
1935 : : {
1936 : : ListCell *child;
1937 : : List *children;
1938 : :
1939 : 1282 : children = find_all_inheritors(myrelid, lockmode, NULL);
1940 : :
1941 [ + - + + : 3784 : foreach(child, children)
+ + ]
1942 : : {
1943 : 2502 : Oid childrelid = lfirst_oid(child);
1944 : :
1945 [ + + ]: 2502 : if (list_member_oid(relids, childrelid))
1946 : 1282 : continue;
1947 : :
1948 : : /* find_all_inheritors already got lock */
1949 : 1220 : rel = table_open(childrelid, NoLock);
1950 : :
1951 : : /*
1952 : : * It is possible that the parent table has children that are
1953 : : * temp tables of other backends. We cannot safely access
1954 : : * such tables (because of buffering issues), and the best
1955 : : * thing to do is to silently ignore them. Note that this
1956 : : * check is the same as one of the checks done in
1957 : : * truncate_check_activity() called below, still it is kept
1958 : : * here for simplicity.
1959 : : */
1960 [ + + + + ]: 1220 : if (RELATION_IS_OTHER_TEMP(rel))
1961 : : {
1962 : 4 : table_close(rel, lockmode);
1963 : 4 : continue;
1964 : : }
1965 : :
1966 : : /*
1967 : : * Inherited TRUNCATE commands perform access permission
1968 : : * checks on the parent table only. So we skip checking the
1969 : : * children's permissions and don't call
1970 : : * truncate_check_perms() here.
1971 : : */
1972 : 1216 : truncate_check_rel(RelationGetRelid(rel), rel->rd_rel);
1973 : 1216 : truncate_check_activity(rel);
1974 : :
1975 : 1216 : rels = lappend(rels, rel);
1976 : 1216 : relids = lappend_oid(relids, childrelid);
1977 : :
1978 : : /* Log this relation only if needed for logical decoding */
1979 [ + + - + : 1216 : if (RelationIsLogicallyLogged(rel))
+ - - + -
- - - + -
+ - ]
1980 : 11 : relids_logged = lappend_oid(relids_logged, childrelid);
1981 : : }
1982 : : }
1983 [ + + ]: 35 : else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1984 [ + - ]: 8 : ereport(ERROR,
1985 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1986 : : errmsg("cannot truncate only a partitioned table"),
1987 : : errhint("Do not specify the ONLY keyword, or use TRUNCATE ONLY on the partitions directly.")));
1988 : : }
1989 : :
1990 : 1138 : ExecuteTruncateGuts(rels, relids, relids_logged,
1991 : 1138 : stmt->behavior, stmt->restart_seqs, false);
1992 : :
1993 : : /* And close the rels */
1994 [ + - + + : 3509 : foreach(cell, rels)
+ + ]
1995 : : {
1996 : 2424 : Relation rel = (Relation) lfirst(cell);
1997 : :
1998 : 2424 : table_close(rel, NoLock);
1999 : : }
2000 : 1085 : }
2001 : :
2002 : : /*
2003 : : * ExecuteTruncateGuts
2004 : : *
2005 : : * Internal implementation of TRUNCATE. This is called by the actual TRUNCATE
2006 : : * command (see above) as well as replication subscribers that execute a
2007 : : * replicated TRUNCATE action.
2008 : : *
2009 : : * explicit_rels is the list of Relations to truncate that the command
2010 : : * specified. relids is the list of Oids corresponding to explicit_rels.
2011 : : * relids_logged is the list of Oids (a subset of relids) that require
2012 : : * WAL-logging. This is all a bit redundant, but the existing callers have
2013 : : * this information handy in this form.
2014 : : */
2015 : : void
2016 : 1158 : ExecuteTruncateGuts(List *explicit_rels,
2017 : : List *relids,
2018 : : List *relids_logged,
2019 : : DropBehavior behavior, bool restart_seqs,
2020 : : bool run_as_table_owner)
2021 : : {
2022 : : List *rels;
2023 : 1158 : List *seq_relids = NIL;
2024 : 1158 : HTAB *ft_htab = NULL;
2025 : : EState *estate;
2026 : : ResultRelInfo *resultRelInfos;
2027 : : ResultRelInfo *resultRelInfo;
2028 : : SubTransactionId mySubid;
2029 : : ListCell *cell;
2030 : : Oid *logrelids;
2031 : :
2032 : : /*
2033 : : * Check the explicitly-specified relations.
2034 : : *
2035 : : * In CASCADE mode, suck in all referencing relations as well. This
2036 : : * requires multiple iterations to find indirectly-dependent relations. At
2037 : : * each phase, we need to exclusive-lock new rels before looking for their
2038 : : * dependencies, else we might miss something. Also, we check each rel as
2039 : : * soon as we open it, to avoid a faux pas such as holding lock for a long
2040 : : * time on a rel we have no permissions for.
2041 : : */
2042 : 1158 : rels = list_copy(explicit_rels);
2043 [ + + ]: 1158 : if (behavior == DROP_CASCADE)
2044 : : {
2045 : : for (;;)
2046 : 26 : {
2047 : : List *newrelids;
2048 : :
2049 : 51 : newrelids = heap_truncate_find_FKs(relids);
2050 [ + + ]: 51 : if (newrelids == NIL)
2051 : 25 : break; /* nothing else to add */
2052 : :
2053 [ + - + + : 88 : foreach(cell, newrelids)
+ + ]
2054 : : {
2055 : 62 : Oid relid = lfirst_oid(cell);
2056 : : Relation rel;
2057 : :
2058 : 62 : rel = table_open(relid, AccessExclusiveLock);
2059 [ + - ]: 62 : ereport(NOTICE,
2060 : : (errmsg("truncate cascades to table \"%s\"",
2061 : : RelationGetRelationName(rel))));
2062 : 62 : truncate_check_rel(relid, rel->rd_rel);
2063 : 62 : truncate_check_perms(relid, rel->rd_rel);
2064 : 62 : truncate_check_activity(rel);
2065 : 62 : rels = lappend(rels, rel);
2066 : 62 : relids = lappend_oid(relids, relid);
2067 : :
2068 : : /* Log this relation only if needed for logical decoding */
2069 [ + - - + : 62 : if (RelationIsLogicallyLogged(rel))
- - - - -
- - - - -
- - ]
2070 : 0 : relids_logged = lappend_oid(relids_logged, relid);
2071 : : }
2072 : : }
2073 : : }
2074 : :
2075 : : /*
2076 : : * Check foreign key references. In CASCADE mode, this should be
2077 : : * unnecessary since we just pulled in all the references; but as a
2078 : : * cross-check, do it anyway if in an Assert-enabled build.
2079 : : */
2080 : : #ifdef USE_ASSERT_CHECKING
2081 : : heap_truncate_check_FKs(rels, false);
2082 : : #else
2083 [ + + ]: 1158 : if (behavior == DROP_RESTRICT)
2084 : 1133 : heap_truncate_check_FKs(rels, false);
2085 : : #endif
2086 : :
2087 : : /*
2088 : : * If we are asked to restart sequences, find all the sequences, lock them
2089 : : * (we need AccessExclusiveLock for ResetSequence), and check permissions.
2090 : : * We want to do this early since it's pointless to do all the truncation
2091 : : * work only to fail on sequence permissions.
2092 : : */
2093 [ + + ]: 1109 : if (restart_seqs)
2094 : : {
2095 [ + - + + : 32 : foreach(cell, rels)
+ + ]
2096 : : {
2097 : 16 : Relation rel = (Relation) lfirst(cell);
2098 : 16 : List *seqlist = getOwnedSequences(RelationGetRelid(rel));
2099 : : ListCell *seqcell;
2100 : :
2101 [ + + + + : 39 : foreach(seqcell, seqlist)
+ + ]
2102 : : {
2103 : 23 : Oid seq_relid = lfirst_oid(seqcell);
2104 : : Relation seq_rel;
2105 : :
2106 : 23 : seq_rel = relation_open(seq_relid, AccessExclusiveLock);
2107 : :
2108 : : /* This check must match AlterSequence! */
2109 [ - + ]: 23 : if (!object_ownercheck(RelationRelationId, seq_relid, GetUserId()))
2110 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SEQUENCE,
2111 : 0 : RelationGetRelationName(seq_rel));
2112 : :
2113 : 23 : seq_relids = lappend_oid(seq_relids, seq_relid);
2114 : :
2115 : 23 : relation_close(seq_rel, NoLock);
2116 : : }
2117 : : }
2118 : : }
2119 : :
2120 : : /* Prepare to catch AFTER triggers. */
2121 : 1109 : AfterTriggerBeginQuery();
2122 : :
2123 : : /*
2124 : : * To fire triggers, we'll need an EState as well as a ResultRelInfo for
2125 : : * each relation. We don't need to call ExecOpenIndices, though.
2126 : : *
2127 : : * We put the ResultRelInfos in the es_opened_result_relations list, even
2128 : : * though we don't have a range table and don't populate the
2129 : : * es_result_relations array. That's a bit bogus, but it's enough to make
2130 : : * ExecGetTriggerResultRel() find them.
2131 : : */
2132 : 1109 : estate = CreateExecutorState();
2133 : 1109 : resultRelInfos = palloc_array(ResultRelInfo, list_length(rels));
2134 : 1109 : resultRelInfo = resultRelInfos;
2135 [ + - + + : 3635 : foreach(cell, rels)
+ + ]
2136 : : {
2137 : 2526 : Relation rel = (Relation) lfirst(cell);
2138 : :
2139 : 2526 : InitResultRelInfo(resultRelInfo,
2140 : : rel,
2141 : : 0, /* dummy rangetable index */
2142 : : NULL,
2143 : : 0);
2144 : 2526 : estate->es_opened_result_relations =
2145 : 2526 : lappend(estate->es_opened_result_relations, resultRelInfo);
2146 : 2526 : resultRelInfo++;
2147 : : }
2148 : :
2149 : : /*
2150 : : * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
2151 : : * truncating (this is because one of them might throw an error). Also, if
2152 : : * we were to allow them to prevent statement execution, that would need
2153 : : * to be handled here.
2154 : : */
2155 : 1109 : resultRelInfo = resultRelInfos;
2156 [ + - + + : 3635 : foreach(cell, rels)
+ + ]
2157 : : {
2158 : : UserContext ucxt;
2159 : :
2160 [ + + ]: 2526 : if (run_as_table_owner)
2161 : 36 : SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2162 : : &ucxt);
2163 : 2526 : ExecBSTruncateTriggers(estate, resultRelInfo);
2164 [ + + ]: 2526 : if (run_as_table_owner)
2165 : 36 : RestoreUserContext(&ucxt);
2166 : 2526 : resultRelInfo++;
2167 : : }
2168 : :
2169 : : /*
2170 : : * OK, truncate each table.
2171 : : */
2172 : 1109 : mySubid = GetCurrentSubTransactionId();
2173 : :
2174 [ + - + + : 3635 : foreach(cell, rels)
+ + ]
2175 : : {
2176 : 2526 : Relation rel = (Relation) lfirst(cell);
2177 : :
2178 : : /* Skip partitioned tables as there is nothing to do */
2179 [ + + ]: 2526 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2180 : 477 : continue;
2181 : :
2182 : : /*
2183 : : * Build the lists of foreign tables belonging to each foreign server
2184 : : * and pass each list to the foreign data wrapper's callback function,
2185 : : * so that each server can truncate its all foreign tables in bulk.
2186 : : * Each list is saved as a single entry in a hash table that uses the
2187 : : * server OID as lookup key.
2188 : : */
2189 [ + + ]: 2049 : if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2190 : 17 : {
2191 : 17 : Oid serverid = GetForeignServerIdByRelId(RelationGetRelid(rel));
2192 : : bool found;
2193 : : ForeignTruncateInfo *ft_info;
2194 : :
2195 : : /* First time through, initialize hashtable for foreign tables */
2196 [ + + ]: 17 : if (!ft_htab)
2197 : : {
2198 : : HASHCTL hctl;
2199 : :
2200 : 15 : memset(&hctl, 0, sizeof(HASHCTL));
2201 : 15 : hctl.keysize = sizeof(Oid);
2202 : 15 : hctl.entrysize = sizeof(ForeignTruncateInfo);
2203 : 15 : hctl.hcxt = CurrentMemoryContext;
2204 : :
2205 : 15 : ft_htab = hash_create("TRUNCATE for Foreign Tables",
2206 : : 32, /* start small and extend */
2207 : : &hctl,
2208 : : HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
2209 : : }
2210 : :
2211 : : /* Find or create cached entry for the foreign table */
2212 : 17 : ft_info = hash_search(ft_htab, &serverid, HASH_ENTER, &found);
2213 [ + + ]: 17 : if (!found)
2214 : 15 : ft_info->rels = NIL;
2215 : :
2216 : : /*
2217 : : * Save the foreign table in the entry of the server that the
2218 : : * foreign table belongs to.
2219 : : */
2220 : 17 : ft_info->rels = lappend(ft_info->rels, rel);
2221 : 17 : continue;
2222 : : }
2223 : :
2224 : : /*
2225 : : * Normally, we need a transaction-safe truncation here. However, if
2226 : : * the table was either created in the current (sub)transaction or has
2227 : : * a new relfilenumber in the current (sub)transaction, then we can
2228 : : * just truncate it in-place, because a rollback would cause the whole
2229 : : * table or the current physical file to be thrown away anyway.
2230 : : */
2231 [ + + ]: 2032 : if (rel->rd_createSubid == mySubid ||
2232 [ + + ]: 2014 : rel->rd_newRelfilelocatorSubid == mySubid)
2233 : : {
2234 : : /* Immediate, non-rollbackable truncation is OK */
2235 : 50 : heap_truncate_one_rel(rel);
2236 : : }
2237 : : else
2238 : : {
2239 : : Oid heap_relid;
2240 : : Oid toast_relid;
2241 : 1982 : ReindexParams reindex_params = {0};
2242 : :
2243 : : /*
2244 : : * This effectively deletes all rows in the table, and may be done
2245 : : * in a serializable transaction. In that case we must record a
2246 : : * rw-conflict in to this transaction from each transaction
2247 : : * holding a predicate lock on the table.
2248 : : */
2249 : 1982 : CheckTableForSerializableConflictIn(rel);
2250 : :
2251 : : /*
2252 : : * Need the full transaction-safe pushups.
2253 : : *
2254 : : * Create a new empty storage file for the relation, and assign it
2255 : : * as the relfilenumber value. The old storage file is scheduled
2256 : : * for deletion at commit.
2257 : : */
2258 : 1982 : RelationSetNewRelfilenumber(rel, rel->rd_rel->relpersistence);
2259 : :
2260 : 1982 : heap_relid = RelationGetRelid(rel);
2261 : :
2262 : : /*
2263 : : * The same for the toast table, if any.
2264 : : */
2265 : 1982 : toast_relid = rel->rd_rel->reltoastrelid;
2266 [ + + ]: 1982 : if (OidIsValid(toast_relid))
2267 : : {
2268 : 1197 : Relation toastrel = relation_open(toast_relid,
2269 : : AccessExclusiveLock);
2270 : :
2271 : 1197 : RelationSetNewRelfilenumber(toastrel,
2272 : 1197 : toastrel->rd_rel->relpersistence);
2273 : 1197 : table_close(toastrel, NoLock);
2274 : : }
2275 : :
2276 : : /*
2277 : : * Reconstruct the indexes to match, and we're done.
2278 : : */
2279 : 1982 : reindex_relation(NULL, heap_relid, REINDEX_REL_PROCESS_TOAST,
2280 : : &reindex_params);
2281 : : }
2282 : :
2283 : 2032 : pgstat_count_truncate(rel);
2284 : : }
2285 : :
2286 : : /* Now go through the hash table, and truncate foreign tables */
2287 [ + + ]: 1109 : if (ft_htab)
2288 : : {
2289 : : ForeignTruncateInfo *ft_info;
2290 : : HASH_SEQ_STATUS seq;
2291 : :
2292 : 15 : hash_seq_init(&seq, ft_htab);
2293 : :
2294 [ + + ]: 15 : PG_TRY();
2295 : : {
2296 [ + + ]: 26 : while ((ft_info = hash_seq_search(&seq)) != NULL)
2297 : : {
2298 : 15 : FdwRoutine *routine = GetFdwRoutineByServerId(ft_info->serverid);
2299 : :
2300 : : /* truncate_check_rel() has checked that already */
2301 : : Assert(routine->ExecForeignTruncate != NULL);
2302 : :
2303 : 15 : routine->ExecForeignTruncate(ft_info->rels,
2304 : : behavior,
2305 : : restart_seqs);
2306 : : }
2307 : : }
2308 : 4 : PG_FINALLY();
2309 : : {
2310 : 15 : hash_destroy(ft_htab);
2311 : : }
2312 [ + + ]: 15 : PG_END_TRY();
2313 : : }
2314 : :
2315 : : /*
2316 : : * Restart owned sequences if we were asked to.
2317 : : */
2318 [ + + + + : 1128 : foreach(cell, seq_relids)
+ + ]
2319 : : {
2320 : 23 : Oid seq_relid = lfirst_oid(cell);
2321 : :
2322 : 23 : ResetSequence(seq_relid);
2323 : : }
2324 : :
2325 : : /*
2326 : : * Write a WAL record to allow this set of actions to be logically
2327 : : * decoded.
2328 : : *
2329 : : * Assemble an array of relids so we can write a single WAL record for the
2330 : : * whole action.
2331 : : */
2332 [ + + ]: 1105 : if (relids_logged != NIL)
2333 : : {
2334 : : xl_heap_truncate xlrec;
2335 : 33 : int i = 0;
2336 : :
2337 : : /* should only get here if effective_wal_level is 'logical' */
2338 : : Assert(XLogLogicalInfoActive());
2339 : :
2340 : 33 : logrelids = palloc_array(Oid, list_length(relids_logged));
2341 [ + - + + : 84 : foreach(cell, relids_logged)
+ + ]
2342 : 51 : logrelids[i++] = lfirst_oid(cell);
2343 : :
2344 : 33 : xlrec.dbId = MyDatabaseId;
2345 : 33 : xlrec.nrelids = list_length(relids_logged);
2346 : 33 : xlrec.flags = 0;
2347 [ + + ]: 33 : if (behavior == DROP_CASCADE)
2348 : 1 : xlrec.flags |= XLH_TRUNCATE_CASCADE;
2349 [ + + ]: 33 : if (restart_seqs)
2350 : 2 : xlrec.flags |= XLH_TRUNCATE_RESTART_SEQS;
2351 : :
2352 : 33 : XLogBeginInsert();
2353 : 33 : XLogRegisterData(&xlrec, SizeOfHeapTruncate);
2354 : 33 : XLogRegisterData(logrelids, list_length(relids_logged) * sizeof(Oid));
2355 : :
2356 : 33 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
2357 : :
2358 : 33 : (void) XLogInsert(RM_HEAP_ID, XLOG_HEAP_TRUNCATE);
2359 : : }
2360 : :
2361 : : /*
2362 : : * Process all AFTER STATEMENT TRUNCATE triggers.
2363 : : */
2364 : 1105 : resultRelInfo = resultRelInfos;
2365 [ + - + + : 3627 : foreach(cell, rels)
+ + ]
2366 : : {
2367 : : UserContext ucxt;
2368 : :
2369 [ + + ]: 2522 : if (run_as_table_owner)
2370 : 36 : SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2371 : : &ucxt);
2372 : 2522 : ExecASTruncateTriggers(estate, resultRelInfo);
2373 [ + + ]: 2522 : if (run_as_table_owner)
2374 : 36 : RestoreUserContext(&ucxt);
2375 : 2522 : resultRelInfo++;
2376 : : }
2377 : :
2378 : : /* Handle queued AFTER triggers */
2379 : 1105 : AfterTriggerEndQuery(estate);
2380 : :
2381 : : /* We can clean up the EState now */
2382 : 1105 : FreeExecutorState(estate);
2383 : :
2384 : : /*
2385 : : * Close any rels opened by CASCADE (can't do this while EState still
2386 : : * holds refs)
2387 : : */
2388 : 1105 : rels = list_difference_ptr(rels, explicit_rels);
2389 [ + + + + : 1167 : foreach(cell, rels)
+ + ]
2390 : : {
2391 : 62 : Relation rel = (Relation) lfirst(cell);
2392 : :
2393 : 62 : table_close(rel, NoLock);
2394 : : }
2395 : 1105 : }
2396 : :
2397 : : /*
2398 : : * Check that a given relation is safe to truncate. Subroutine for
2399 : : * ExecuteTruncate() and RangeVarCallbackForTruncate().
2400 : : */
2401 : : static void
2402 : 2711 : truncate_check_rel(Oid relid, Form_pg_class reltuple)
2403 : : {
2404 : 2711 : char *relname = NameStr(reltuple->relname);
2405 : :
2406 : : /*
2407 : : * Only allow truncate on regular tables, foreign tables using foreign
2408 : : * data wrappers supporting TRUNCATE and partitioned tables (although, the
2409 : : * latter are only being included here for the following checks; no
2410 : : * physical truncation will occur in their case.).
2411 : : */
2412 [ + + ]: 2711 : if (reltuple->relkind == RELKIND_FOREIGN_TABLE)
2413 : : {
2414 : 19 : Oid serverid = GetForeignServerIdByRelId(relid);
2415 : 19 : FdwRoutine *fdwroutine = GetFdwRoutineByServerId(serverid);
2416 : :
2417 [ + + ]: 18 : if (!fdwroutine->ExecForeignTruncate)
2418 [ + - ]: 1 : ereport(ERROR,
2419 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2420 : : errmsg("cannot truncate foreign table \"%s\"",
2421 : : relname)));
2422 : : }
2423 [ + + ]: 2692 : else if (reltuple->relkind != RELKIND_RELATION &&
2424 [ - + ]: 490 : reltuple->relkind != RELKIND_PARTITIONED_TABLE)
2425 [ # # ]: 0 : ereport(ERROR,
2426 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2427 : : errmsg("\"%s\" is not a table", relname)));
2428 : :
2429 : : /*
2430 : : * Most system catalogs can't be truncated at all, or at least not unless
2431 : : * allow_system_table_mods=on. As an exception, however, we allow
2432 : : * pg_largeobject and pg_largeobject_metadata to be truncated as part of
2433 : : * pg_upgrade, because we need to change its relfilenode to match the old
2434 : : * cluster, and allowing a TRUNCATE command to be executed is the easiest
2435 : : * way of doing that. We also allow TRUNCATE on the conflict log tables,
2436 : : * to permit users to manually prune conflict data to manage disk space.
2437 : : */
2438 [ + + + + ]: 2709 : if (!allowSystemTableMods && IsSystemClass(relid, reltuple) &&
2439 [ + + ]: 73 : !IsConflictLogTableClass(reltuple)
2440 [ + + + + ]: 65 : && (!IsBinaryUpgrade ||
2441 [ - + ]: 32 : (relid != LargeObjectRelationId &&
2442 : : relid != LargeObjectMetadataRelationId)))
2443 [ + - ]: 1 : ereport(ERROR,
2444 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2445 : : errmsg("permission denied: \"%s\" is a system catalog",
2446 : : relname)));
2447 : :
2448 [ - + ]: 2708 : InvokeObjectTruncateHook(relid);
2449 : 2708 : }
2450 : :
2451 : : /*
2452 : : * Check that current user has the permission to truncate given relation.
2453 : : */
2454 : : static void
2455 : 1492 : truncate_check_perms(Oid relid, Form_pg_class reltuple)
2456 : : {
2457 : 1492 : char *relname = NameStr(reltuple->relname);
2458 : : AclResult aclresult;
2459 : :
2460 : : /* Permissions checks */
2461 : 1492 : aclresult = pg_class_aclcheck(relid, GetUserId(), ACL_TRUNCATE);
2462 [ + + ]: 1492 : if (aclresult != ACLCHECK_OK)
2463 : 20 : aclcheck_error(aclresult, get_relkind_objtype(reltuple->relkind),
2464 : : relname);
2465 : 1472 : }
2466 : :
2467 : : /*
2468 : : * Set of extra sanity checks to check if a given relation is safe to
2469 : : * truncate. This is split with truncate_check_rel() as
2470 : : * RangeVarCallbackForTruncate() cannot open a Relation yet.
2471 : : */
2472 : : static void
2473 : 2600 : truncate_check_activity(Relation rel)
2474 : : {
2475 : : /*
2476 : : * Don't allow truncate on temp tables of other backends ... their local
2477 : : * buffer manager is not going to cope.
2478 : : */
2479 [ + + + + ]: 2600 : if (RELATION_IS_OTHER_TEMP(rel))
2480 [ + - ]: 1 : ereport(ERROR,
2481 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2482 : : errmsg("cannot truncate temporary tables of other sessions")));
2483 : :
2484 : : /*
2485 : : * Also check for active uses of the relation in the current transaction,
2486 : : * including open scans and pending AFTER trigger events.
2487 : : */
2488 : 2599 : CheckTableNotInUse(rel, "TRUNCATE");
2489 : 2595 : }
2490 : :
2491 : : /*
2492 : : * storage_name
2493 : : * returns the name corresponding to a typstorage/attstorage enum value
2494 : : */
2495 : : static const char *
2496 : 16 : storage_name(char c)
2497 : : {
2498 [ - - + + : 16 : switch (c)
- ]
2499 : : {
2500 : 0 : case TYPSTORAGE_PLAIN:
2501 : 0 : return "PLAIN";
2502 : 0 : case TYPSTORAGE_EXTERNAL:
2503 : 0 : return "EXTERNAL";
2504 : 8 : case TYPSTORAGE_EXTENDED:
2505 : 8 : return "EXTENDED";
2506 : 8 : case TYPSTORAGE_MAIN:
2507 : 8 : return "MAIN";
2508 : 0 : default:
2509 : 0 : return "???";
2510 : : }
2511 : : }
2512 : :
2513 : : /*----------
2514 : : * MergeAttributes
2515 : : * Returns new schema given initial schema and superclasses.
2516 : : *
2517 : : * Input arguments:
2518 : : * 'columns' is the column/attribute definition for the table. (It's a list
2519 : : * of ColumnDef's.) It is destructively changed.
2520 : : * 'supers' is a list of OIDs of parent relations, already locked by caller.
2521 : : * 'relpersistence' is the persistence type of the table.
2522 : : * 'is_partition' tells if the table is a partition.
2523 : : *
2524 : : * Output arguments:
2525 : : * 'supconstr' receives a list of CookedConstraint representing
2526 : : * CHECK constraints belonging to parent relations, updated as
2527 : : * necessary to be valid for the child.
2528 : : * 'supnotnulls' receives a list of CookedConstraint representing
2529 : : * not-null constraints based on those from parent relations.
2530 : : *
2531 : : * Return value:
2532 : : * Completed schema list.
2533 : : *
2534 : : * Notes:
2535 : : * The order in which the attributes are inherited is very important.
2536 : : * Intuitively, the inherited attributes should come first. If a table
2537 : : * inherits from multiple parents, the order of those attributes are
2538 : : * according to the order of the parents specified in CREATE TABLE.
2539 : : *
2540 : : * Here's an example:
2541 : : *
2542 : : * create table person (name text, age int4, location point);
2543 : : * create table emp (salary int4, manager text) inherits(person);
2544 : : * create table student (gpa float8) inherits (person);
2545 : : * create table stud_emp (percent int4) inherits (emp, student);
2546 : : *
2547 : : * The order of the attributes of stud_emp is:
2548 : : *
2549 : : * person {1:name, 2:age, 3:location}
2550 : : * / \
2551 : : * {6:gpa} student emp {4:salary, 5:manager}
2552 : : * \ /
2553 : : * stud_emp {7:percent}
2554 : : *
2555 : : * If the same attribute name appears multiple times, then it appears
2556 : : * in the result table in the proper location for its first appearance.
2557 : : *
2558 : : * Constraints (including not-null constraints) for the child table
2559 : : * are the union of all relevant constraints, from both the child schema
2560 : : * and parent tables. In addition, in legacy inheritance, each column that
2561 : : * appears in a primary key in any of the parents also gets a NOT NULL
2562 : : * constraint (partitioning doesn't need this, because the PK itself gets
2563 : : * inherited.)
2564 : : *
2565 : : * The default value for a child column is defined as:
2566 : : * (1) If the child schema specifies a default, that value is used.
2567 : : * (2) If neither the child nor any parent specifies a default, then
2568 : : * the column will not have a default.
2569 : : * (3) If conflicting defaults are inherited from different parents
2570 : : * (and not overridden by the child), an error is raised.
2571 : : * (4) Otherwise the inherited default is used.
2572 : : *
2573 : : * Note that the default-value infrastructure is used for generated
2574 : : * columns' expressions too, so most of the preceding paragraph applies
2575 : : * to generation expressions too. We insist that a child column be
2576 : : * generated if and only if its parent(s) are, but it need not have
2577 : : * the same generation expression.
2578 : : *----------
2579 : : */
2580 : : static List *
2581 : 40836 : MergeAttributes(List *columns, const List *supers, char relpersistence,
2582 : : bool is_partition, List **supconstr, List **supnotnulls)
2583 : : {
2584 : 40836 : List *inh_columns = NIL;
2585 : 40836 : List *constraints = NIL;
2586 : 40836 : List *nnconstraints = NIL;
2587 : 40836 : bool have_bogus_defaults = false;
2588 : : int child_attno;
2589 : : static Node bogus_marker = {0}; /* marks conflicting defaults */
2590 : 40836 : List *saved_columns = NIL;
2591 : : ListCell *lc;
2592 : :
2593 : : /*
2594 : : * Check for and reject tables with too many columns. We perform this
2595 : : * check relatively early for two reasons: (a) we don't run the risk of
2596 : : * overflowing an AttrNumber in subsequent code (b) an O(n^2) algorithm is
2597 : : * okay if we're processing <= 1600 columns, but could take minutes to
2598 : : * execute if the user attempts to create a table with hundreds of
2599 : : * thousands of columns.
2600 : : *
2601 : : * Note that we also need to check that we do not exceed this figure after
2602 : : * including columns from inherited relations.
2603 : : */
2604 [ - + ]: 40836 : if (list_length(columns) > MaxHeapAttributeNumber)
2605 [ # # ]: 0 : ereport(ERROR,
2606 : : (errcode(ERRCODE_TOO_MANY_COLUMNS),
2607 : : errmsg("tables can have at most %d columns",
2608 : : MaxHeapAttributeNumber)));
2609 : :
2610 : : /*
2611 : : * Check for duplicate names in the explicit list of attributes.
2612 : : *
2613 : : * Although we might consider merging such entries in the same way that we
2614 : : * handle name conflicts for inherited attributes, it seems to make more
2615 : : * sense to assume such conflicts are errors.
2616 : : *
2617 : : * We don't use foreach() here because we have two nested loops over the
2618 : : * columns list, with possible element deletions in the inner one. If we
2619 : : * used foreach_delete_current() it could only fix up the state of one of
2620 : : * the loops, so it seems cleaner to use looping over list indexes for
2621 : : * both loops. Note that any deletion will happen beyond where the outer
2622 : : * loop is, so its index never needs adjustment.
2623 : : */
2624 [ + + ]: 190376 : for (int coldefpos = 0; coldefpos < list_length(columns); coldefpos++)
2625 : : {
2626 : 149556 : ColumnDef *coldef = list_nth_node(ColumnDef, columns, coldefpos);
2627 : :
2628 [ + + + + ]: 149556 : if (!is_partition && coldef->typeName == NULL)
2629 : : {
2630 : : /*
2631 : : * Typed table column option that does not belong to a column from
2632 : : * the type. This works because the columns from the type come
2633 : : * first in the list. (We omit this check for partition column
2634 : : * lists; those are processed separately below.)
2635 : : */
2636 [ + - ]: 4 : ereport(ERROR,
2637 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
2638 : : errmsg("column \"%s\" does not exist",
2639 : : coldef->colname)));
2640 : : }
2641 : :
2642 : : /* restpos scans all entries beyond coldef; incr is in loop body */
2643 [ + + ]: 4106965 : for (int restpos = coldefpos + 1; restpos < list_length(columns);)
2644 : : {
2645 : 3957425 : ColumnDef *restdef = list_nth_node(ColumnDef, columns, restpos);
2646 : :
2647 [ + + ]: 3957425 : if (strcmp(coldef->colname, restdef->colname) == 0)
2648 : : {
2649 [ + + ]: 33 : if (coldef->is_from_type)
2650 : : {
2651 : : /*
2652 : : * merge the column options into the column from the type
2653 : : */
2654 : 21 : coldef->is_not_null = restdef->is_not_null;
2655 : 21 : coldef->raw_default = restdef->raw_default;
2656 : 21 : coldef->cooked_default = restdef->cooked_default;
2657 : 21 : coldef->constraints = restdef->constraints;
2658 : 21 : coldef->is_from_type = false;
2659 : 21 : columns = list_delete_nth_cell(columns, restpos);
2660 : : }
2661 : : else
2662 [ + - ]: 12 : ereport(ERROR,
2663 : : (errcode(ERRCODE_DUPLICATE_COLUMN),
2664 : : errmsg("column \"%s\" specified more than once",
2665 : : coldef->colname)));
2666 : : }
2667 : : else
2668 : 3957392 : restpos++;
2669 : : }
2670 : : }
2671 : :
2672 : : /*
2673 : : * In case of a partition, there are no new column definitions, only dummy
2674 : : * ColumnDefs created for column constraints. Set them aside for now and
2675 : : * process them at the end.
2676 : : */
2677 [ + + ]: 40820 : if (is_partition)
2678 : : {
2679 : 5968 : saved_columns = columns;
2680 : 5968 : columns = NIL;
2681 : : }
2682 : :
2683 : : /*
2684 : : * Scan the parents left-to-right, and merge their attributes to form a
2685 : : * list of inherited columns (inh_columns).
2686 : : */
2687 : 40820 : child_attno = 0;
2688 [ + + + + : 48398 : foreach(lc, supers)
+ + ]
2689 : : {
2690 : 7638 : Oid parent = lfirst_oid(lc);
2691 : : Relation relation;
2692 : : TupleDesc tupleDesc;
2693 : : TupleConstr *constr;
2694 : : AttrMap *newattmap;
2695 : : List *inherited_defaults;
2696 : : List *cols_with_defaults;
2697 : : List *nnconstrs;
2698 : : ListCell *lc1;
2699 : : ListCell *lc2;
2700 : 7638 : Bitmapset *nncols = NULL;
2701 : :
2702 : : /* caller already got lock */
2703 : 7638 : relation = table_open(parent, NoLock);
2704 : :
2705 : : /*
2706 : : * Check for active uses of the parent partitioned table in the
2707 : : * current transaction, such as being used in some manner by an
2708 : : * enclosing command.
2709 : : */
2710 [ + + ]: 7638 : if (is_partition)
2711 : 5968 : CheckTableNotInUse(relation, "CREATE TABLE .. PARTITION OF");
2712 : :
2713 : : /*
2714 : : * We do not allow partitioned tables and partitions to participate in
2715 : : * regular inheritance.
2716 : : */
2717 [ + + + + ]: 7634 : if (relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !is_partition)
2718 [ + - ]: 4 : ereport(ERROR,
2719 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2720 : : errmsg("cannot inherit from partitioned table \"%s\"",
2721 : : RelationGetRelationName(relation))));
2722 [ + + + + ]: 7630 : if (relation->rd_rel->relispartition && !is_partition)
2723 [ + - ]: 4 : ereport(ERROR,
2724 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2725 : : errmsg("cannot inherit from partition \"%s\"",
2726 : : RelationGetRelationName(relation))));
2727 : :
2728 : : /*
2729 : : * Conflict log tables are managed by the system for logical
2730 : : * replication and should not be used as parent tables, as inheritance
2731 : : * could interfere with the logging behavior.
2732 : : */
2733 [ + + ]: 7626 : if (IsConflictLogTableNamespace(relation->rd_rel->relnamespace))
2734 [ + - ]: 4 : ereport(ERROR,
2735 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2736 : : errmsg("cannot inherit from conflict log table \"%s\"",
2737 : : RelationGetRelationName(relation)),
2738 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
2739 : :
2740 [ + + ]: 7622 : if (relation->rd_rel->relkind != RELKIND_RELATION &&
2741 [ + + ]: 5964 : relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2742 [ - + ]: 5952 : relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2743 [ # # ]: 0 : ereport(ERROR,
2744 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2745 : : errmsg("inherited relation \"%s\" is not a table or foreign table",
2746 : : RelationGetRelationName(relation))));
2747 : :
2748 : : /*
2749 : : * If the parent is permanent, so must be all of its partitions. Note
2750 : : * that inheritance allows that case.
2751 : : */
2752 [ + + ]: 7622 : if (is_partition &&
2753 [ + + + + ]: 5964 : relation->rd_rel->relpersistence != RELPERSISTENCE_TEMP &&
2754 : : relpersistence == RELPERSISTENCE_TEMP)
2755 [ + - ]: 4 : ereport(ERROR,
2756 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2757 : : errmsg("cannot create a temporary relation as partition of permanent relation \"%s\"",
2758 : : RelationGetRelationName(relation))));
2759 : :
2760 : : /* Permanent rels cannot inherit from temporary ones */
2761 [ + + ]: 7618 : if (relpersistence != RELPERSISTENCE_TEMP &&
2762 [ + + ]: 7380 : relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
2763 [ + - + + ]: 16 : ereport(ERROR,
2764 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2765 : : errmsg(!is_partition
2766 : : ? "cannot inherit from temporary relation \"%s\""
2767 : : : "cannot create a permanent relation as partition of temporary relation \"%s\"",
2768 : : RelationGetRelationName(relation))));
2769 : :
2770 : : /* If existing rel is temp, it must belong to this session */
2771 [ + + - + ]: 7602 : if (RELATION_IS_OTHER_TEMP(relation))
2772 [ # # # # ]: 0 : ereport(ERROR,
2773 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2774 : : errmsg(!is_partition
2775 : : ? "cannot inherit from temporary relation of another session"
2776 : : : "cannot create as partition of temporary relation of another session")));
2777 : :
2778 : : /*
2779 : : * We should have an UNDER permission flag for this, but for now,
2780 : : * demand that creator of a child table own the parent.
2781 : : */
2782 [ - + ]: 7602 : if (!object_ownercheck(RelationRelationId, RelationGetRelid(relation), GetUserId()))
2783 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(relation->rd_rel->relkind),
2784 : 0 : RelationGetRelationName(relation));
2785 : :
2786 : 7602 : tupleDesc = RelationGetDescr(relation);
2787 : 7602 : constr = tupleDesc->constr;
2788 : :
2789 : : /*
2790 : : * newattmap->attnums[] will contain the child-table attribute numbers
2791 : : * for the attributes of this parent table. (They are not the same
2792 : : * for parents after the first one, nor if we have dropped columns.)
2793 : : */
2794 : 7602 : newattmap = make_attrmap(tupleDesc->natts);
2795 : :
2796 : : /* We can't process inherited defaults until newattmap is complete. */
2797 : 7602 : inherited_defaults = cols_with_defaults = NIL;
2798 : :
2799 : : /*
2800 : : * Request attnotnull on columns that have a not-null constraint
2801 : : * that's not marked NO INHERIT (even if not valid).
2802 : : */
2803 : 7602 : nnconstrs = RelationGetNotNullConstraints(RelationGetRelid(relation),
2804 : : true, false);
2805 [ + + + + : 16808 : foreach_ptr(CookedConstraint, cc, nnconstrs)
+ + ]
2806 : 1604 : nncols = bms_add_member(nncols, cc->attnum);
2807 : :
2808 [ + + ]: 22214 : for (AttrNumber parent_attno = 1; parent_attno <= tupleDesc->natts;
2809 : 14612 : parent_attno++)
2810 : : {
2811 : 14636 : Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
2812 : : parent_attno - 1);
2813 : 14636 : char *attributeName = NameStr(attribute->attname);
2814 : : int exist_attno;
2815 : : ColumnDef *newdef;
2816 : : ColumnDef *mergeddef;
2817 : :
2818 : : /*
2819 : : * Ignore dropped columns in the parent.
2820 : : */
2821 [ + + ]: 14636 : if (attribute->attisdropped)
2822 : 132 : continue; /* leave newattmap->attnums entry as zero */
2823 : :
2824 : : /*
2825 : : * Create new column definition
2826 : : */
2827 : 14504 : newdef = makeColumnDef(attributeName, attribute->atttypid,
2828 : : attribute->atttypmod, attribute->attcollation);
2829 : 14504 : newdef->storage = attribute->attstorage;
2830 : 14504 : newdef->generated = attribute->attgenerated;
2831 [ + + ]: 14504 : if (CompressionMethodIsValid(attribute->attcompression))
2832 : 24 : newdef->compression =
2833 : 24 : pstrdup(GetCompressionMethodName(attribute->attcompression));
2834 : :
2835 : : /*
2836 : : * Regular inheritance children are independent enough not to
2837 : : * inherit identity columns. But partitions are integral part of
2838 : : * a partitioned table and inherit identity column.
2839 : : */
2840 [ + + ]: 14504 : if (is_partition)
2841 : 11548 : newdef->identity = attribute->attidentity;
2842 : :
2843 : : /*
2844 : : * Does it match some previously considered column from another
2845 : : * parent?
2846 : : */
2847 : 14504 : exist_attno = findAttrByName(attributeName, inh_columns);
2848 [ + + ]: 14504 : if (exist_attno > 0)
2849 : : {
2850 : : /*
2851 : : * Yes, try to merge the two column definitions.
2852 : : */
2853 : 253 : mergeddef = MergeInheritedAttribute(inh_columns, exist_attno, newdef);
2854 : :
2855 : 229 : newattmap->attnums[parent_attno - 1] = exist_attno;
2856 : :
2857 : : /*
2858 : : * Partitions have only one parent, so conflict should never
2859 : : * occur.
2860 : : */
2861 : : Assert(!is_partition);
2862 : : }
2863 : : else
2864 : : {
2865 : : /*
2866 : : * No, create a new inherited column
2867 : : */
2868 : 14251 : newdef->inhcount = 1;
2869 : 14251 : newdef->is_local = false;
2870 : 14251 : inh_columns = lappend(inh_columns, newdef);
2871 : :
2872 : 14251 : newattmap->attnums[parent_attno - 1] = ++child_attno;
2873 : 14251 : mergeddef = newdef;
2874 : : }
2875 : :
2876 : : /*
2877 : : * mark attnotnull if parent has it
2878 : : */
2879 [ + + ]: 14480 : if (bms_is_member(parent_attno, nncols))
2880 : 1604 : mergeddef->is_not_null = true;
2881 : :
2882 : : /*
2883 : : * Locate default/generation expression if any
2884 : : */
2885 [ + + ]: 14480 : if (attribute->atthasdef)
2886 : : {
2887 : : Node *this_default;
2888 : :
2889 : 462 : this_default = TupleDescGetDefault(tupleDesc, parent_attno);
2890 [ - + ]: 462 : if (this_default == NULL)
2891 [ # # ]: 0 : elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
2892 : : parent_attno, RelationGetRelationName(relation));
2893 : :
2894 : : /*
2895 : : * If it's a GENERATED default, it might contain Vars that
2896 : : * need to be mapped to the inherited column(s)' new numbers.
2897 : : * We can't do that till newattmap is ready, so just remember
2898 : : * all the inherited default expressions for the moment.
2899 : : */
2900 : 462 : inherited_defaults = lappend(inherited_defaults, this_default);
2901 : 462 : cols_with_defaults = lappend(cols_with_defaults, mergeddef);
2902 : : }
2903 : : }
2904 : :
2905 : : /*
2906 : : * Now process any inherited default expressions, adjusting attnos
2907 : : * using the completed newattmap map.
2908 : : */
2909 [ + + + + : 8040 : forboth(lc1, inherited_defaults, lc2, cols_with_defaults)
+ + + + +
+ + - +
+ ]
2910 : : {
2911 : 462 : Node *this_default = (Node *) lfirst(lc1);
2912 : 462 : ColumnDef *def = (ColumnDef *) lfirst(lc2);
2913 : : bool found_whole_row;
2914 : :
2915 : : /* Adjust Vars to match new table's column numbering */
2916 : 462 : this_default = map_variable_attnos(this_default,
2917 : : 1, 0,
2918 : : newattmap,
2919 : : InvalidOid, &found_whole_row);
2920 : :
2921 : : /*
2922 : : * For the moment we have to reject whole-row variables. We could
2923 : : * convert them, if we knew the new table's rowtype OID, but that
2924 : : * hasn't been assigned yet. (A variable could only appear in a
2925 : : * generation expression, so the error message is correct.)
2926 : : */
2927 [ - + ]: 462 : if (found_whole_row)
2928 [ # # ]: 0 : ereport(ERROR,
2929 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2930 : : errmsg("cannot convert whole-row table reference"),
2931 : : errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
2932 : : def->colname,
2933 : : RelationGetRelationName(relation))));
2934 : :
2935 : : /*
2936 : : * If we already had a default from some prior parent, check to
2937 : : * see if they are the same. If so, no problem; if not, mark the
2938 : : * column as having a bogus default. Below, we will complain if
2939 : : * the bogus default isn't overridden by the child columns.
2940 : : */
2941 : : Assert(def->raw_default == NULL);
2942 [ + + ]: 462 : if (def->cooked_default == NULL)
2943 : 434 : def->cooked_default = this_default;
2944 [ + + ]: 28 : else if (!equal(def->cooked_default, this_default))
2945 : : {
2946 : 24 : def->cooked_default = &bogus_marker;
2947 : 24 : have_bogus_defaults = true;
2948 : : }
2949 : : }
2950 : :
2951 : : /*
2952 : : * Now copy the CHECK constraints of this parent, adjusting attnos
2953 : : * using the completed newattmap map. Identically named constraints
2954 : : * are merged if possible, else we throw error.
2955 : : */
2956 [ + + + + ]: 7578 : if (constr && constr->num_check > 0)
2957 : : {
2958 : 281 : ConstrCheck *check = constr->check;
2959 : :
2960 [ + + ]: 842 : for (int i = 0; i < constr->num_check; i++)
2961 : : {
2962 : 561 : char *name = check[i].ccname;
2963 : : Node *expr;
2964 : : bool found_whole_row;
2965 : :
2966 : : /* ignore if the constraint is non-inheritable */
2967 [ + + ]: 561 : if (check[i].ccnoinherit)
2968 : 32 : continue;
2969 : :
2970 : : /* Adjust Vars to match new table's column numbering */
2971 : 529 : expr = map_variable_attnos(stringToNode(check[i].ccbin),
2972 : : 1, 0,
2973 : : newattmap,
2974 : : InvalidOid, &found_whole_row);
2975 : :
2976 : : /*
2977 : : * For the moment we have to reject whole-row variables. We
2978 : : * could convert them, if we knew the new table's rowtype OID,
2979 : : * but that hasn't been assigned yet.
2980 : : */
2981 [ - + ]: 529 : if (found_whole_row)
2982 [ # # ]: 0 : ereport(ERROR,
2983 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2984 : : errmsg("cannot convert whole-row table reference"),
2985 : : errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
2986 : : name,
2987 : : RelationGetRelationName(relation))));
2988 : :
2989 : 529 : constraints = MergeCheckConstraint(constraints, name, expr,
2990 : 529 : check[i].ccenforced);
2991 : : }
2992 : : }
2993 : :
2994 : : /*
2995 : : * Also copy the not-null constraints from this parent. The
2996 : : * attnotnull markings were already installed above.
2997 : : */
2998 [ + + + + : 16760 : foreach_ptr(CookedConstraint, nn, nnconstrs)
+ + ]
2999 : : {
3000 : : Assert(nn->contype == CONSTR_NOTNULL);
3001 : :
3002 : 1604 : nn->attnum = newattmap->attnums[nn->attnum - 1];
3003 : :
3004 : 1604 : nnconstraints = lappend(nnconstraints, nn);
3005 : : }
3006 : :
3007 : 7578 : free_attrmap(newattmap);
3008 : :
3009 : : /*
3010 : : * Close the parent rel, but keep our lock on it until xact commit.
3011 : : * That will prevent someone else from deleting or ALTERing the parent
3012 : : * before the child is committed.
3013 : : */
3014 : 7578 : table_close(relation, NoLock);
3015 : : }
3016 : :
3017 : : /*
3018 : : * If we had no inherited attributes, the result columns are just the
3019 : : * explicitly declared columns. Otherwise, we need to merge the declared
3020 : : * columns into the inherited column list. Although, we never have any
3021 : : * explicitly declared columns if the table is a partition.
3022 : : */
3023 [ + + ]: 40760 : if (inh_columns != NIL)
3024 : : {
3025 : 7280 : int newcol_attno = 0;
3026 : :
3027 [ + + + + : 7928 : foreach(lc, columns)
+ + ]
3028 : : {
3029 : 700 : ColumnDef *newdef = lfirst_node(ColumnDef, lc);
3030 : 700 : char *attributeName = newdef->colname;
3031 : : int exist_attno;
3032 : :
3033 : : /*
3034 : : * Partitions have only one parent and have no column definitions
3035 : : * of their own, so conflict should never occur.
3036 : : */
3037 : : Assert(!is_partition);
3038 : :
3039 : 700 : newcol_attno++;
3040 : :
3041 : : /*
3042 : : * Does it match some inherited column?
3043 : : */
3044 : 700 : exist_attno = findAttrByName(attributeName, inh_columns);
3045 [ + + ]: 700 : if (exist_attno > 0)
3046 : : {
3047 : : /*
3048 : : * Yes, try to merge the two column definitions.
3049 : : */
3050 : 251 : MergeChildAttribute(inh_columns, exist_attno, newcol_attno, newdef);
3051 : : }
3052 : : else
3053 : : {
3054 : : /*
3055 : : * No, attach new column unchanged to result columns.
3056 : : */
3057 : 449 : inh_columns = lappend(inh_columns, newdef);
3058 : : }
3059 : : }
3060 : :
3061 : 7228 : columns = inh_columns;
3062 : :
3063 : : /*
3064 : : * Check that we haven't exceeded the legal # of columns after merging
3065 : : * in inherited columns.
3066 : : */
3067 [ - + ]: 7228 : if (list_length(columns) > MaxHeapAttributeNumber)
3068 [ # # ]: 0 : ereport(ERROR,
3069 : : (errcode(ERRCODE_TOO_MANY_COLUMNS),
3070 : : errmsg("tables can have at most %d columns",
3071 : : MaxHeapAttributeNumber)));
3072 : : }
3073 : :
3074 : : /*
3075 : : * Now that we have the column definition list for a partition, we can
3076 : : * check whether the columns referenced in the column constraint specs
3077 : : * actually exist. Also, merge column defaults.
3078 : : */
3079 [ + + ]: 40708 : if (is_partition)
3080 : : {
3081 [ + + + + : 6075 : foreach(lc, saved_columns)
+ + ]
3082 : : {
3083 : 151 : ColumnDef *restdef = lfirst(lc);
3084 : 151 : bool found = false;
3085 : : ListCell *l;
3086 : :
3087 [ + - + + : 549 : foreach(l, columns)
+ + ]
3088 : : {
3089 : 422 : ColumnDef *coldef = lfirst(l);
3090 : :
3091 [ + + ]: 422 : if (strcmp(coldef->colname, restdef->colname) == 0)
3092 : : {
3093 : 151 : found = true;
3094 : :
3095 : : /*
3096 : : * Check for conflicts related to generated columns.
3097 : : *
3098 : : * Same rules as above: generated-ness has to match the
3099 : : * parent, but the contents of the generation expression
3100 : : * can be different.
3101 : : */
3102 [ + + ]: 151 : if (coldef->generated)
3103 : : {
3104 [ + - + + ]: 80 : if (restdef->raw_default && !restdef->generated)
3105 [ + - ]: 8 : ereport(ERROR,
3106 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3107 : : errmsg("column \"%s\" inherits from generated column but specifies default",
3108 : : restdef->colname)));
3109 [ - + ]: 72 : if (restdef->identity)
3110 [ # # ]: 0 : ereport(ERROR,
3111 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3112 : : errmsg("column \"%s\" inherits from generated column but specifies identity",
3113 : : restdef->colname)));
3114 : : }
3115 : : else
3116 : : {
3117 [ + + ]: 71 : if (restdef->generated)
3118 [ + - ]: 8 : ereport(ERROR,
3119 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3120 : : errmsg("child column \"%s\" specifies generation expression",
3121 : : restdef->colname),
3122 : : errhint("A child table column cannot be generated unless its parent column is.")));
3123 : : }
3124 : :
3125 [ + + + - : 135 : if (coldef->generated && restdef->generated && coldef->generated != restdef->generated)
+ + ]
3126 [ + - + + : 8 : ereport(ERROR,
+ + ]
3127 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3128 : : errmsg("column \"%s\" inherits from generated column of different kind",
3129 : : restdef->colname),
3130 : : errdetail("Parent column is %s, child column is %s.",
3131 : : coldef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
3132 : : restdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
3133 : :
3134 : : /*
3135 : : * Override the parent's default value for this column
3136 : : * (coldef->cooked_default) with the partition's local
3137 : : * definition (restdef->raw_default), if there's one. It
3138 : : * should be physically impossible to get a cooked default
3139 : : * in the local definition or a raw default in the
3140 : : * inherited definition, but make sure they're nulls, for
3141 : : * future-proofing.
3142 : : */
3143 : : Assert(restdef->cooked_default == NULL);
3144 : : Assert(coldef->raw_default == NULL);
3145 [ + + ]: 127 : if (restdef->raw_default)
3146 : : {
3147 : 79 : coldef->raw_default = restdef->raw_default;
3148 : 79 : coldef->cooked_default = NULL;
3149 : : }
3150 : : }
3151 : : }
3152 : :
3153 : : /* complain for constraints on columns not in parent */
3154 [ - + ]: 127 : if (!found)
3155 [ # # ]: 0 : ereport(ERROR,
3156 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
3157 : : errmsg("column \"%s\" does not exist",
3158 : : restdef->colname)));
3159 : : }
3160 : : }
3161 : :
3162 : : /*
3163 : : * If we found any conflicting parent default values, check to make sure
3164 : : * they were overridden by the child.
3165 : : */
3166 [ + + ]: 40684 : if (have_bogus_defaults)
3167 : : {
3168 [ + - + + : 60 : foreach(lc, columns)
+ + ]
3169 : : {
3170 : 48 : ColumnDef *def = lfirst(lc);
3171 : :
3172 [ + + ]: 48 : if (def->cooked_default == &bogus_marker)
3173 : : {
3174 [ + + ]: 12 : if (def->generated)
3175 [ + - ]: 8 : ereport(ERROR,
3176 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3177 : : errmsg("column \"%s\" inherits conflicting generation expressions",
3178 : : def->colname),
3179 : : errhint("To resolve the conflict, specify a generation expression explicitly.")));
3180 : : else
3181 [ + - ]: 4 : ereport(ERROR,
3182 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3183 : : errmsg("column \"%s\" inherits conflicting default values",
3184 : : def->colname),
3185 : : errhint("To resolve the conflict, specify a default explicitly.")));
3186 : : }
3187 : : }
3188 : : }
3189 : :
3190 : 40672 : *supconstr = constraints;
3191 : 40672 : *supnotnulls = nnconstraints;
3192 : :
3193 : 40672 : return columns;
3194 : : }
3195 : :
3196 : :
3197 : : /*
3198 : : * MergeCheckConstraint
3199 : : * Try to merge an inherited CHECK constraint with previous ones
3200 : : *
3201 : : * If we inherit identically-named constraints from multiple parents, we must
3202 : : * merge them, or throw an error if they don't have identical definitions.
3203 : : *
3204 : : * constraints is a list of CookedConstraint structs for previous constraints.
3205 : : *
3206 : : * If the new constraint matches an existing one, then the existing
3207 : : * constraint's inheritance count is updated. If there is a conflict (same
3208 : : * name but different expression), throw an error. If the constraint neither
3209 : : * matches nor conflicts with an existing one, a new constraint is appended to
3210 : : * the list.
3211 : : */
3212 : : static List *
3213 : 529 : MergeCheckConstraint(List *constraints, const char *name, Node *expr, bool is_enforced)
3214 : : {
3215 : : ListCell *lc;
3216 : : CookedConstraint *newcon;
3217 : :
3218 [ + + + + : 1557 : foreach(lc, constraints)
+ + ]
3219 : : {
3220 : 1136 : CookedConstraint *ccon = (CookedConstraint *) lfirst(lc);
3221 : :
3222 : : Assert(ccon->contype == CONSTR_CHECK);
3223 : :
3224 : : /* Non-matching names never conflict */
3225 [ + + ]: 1136 : if (strcmp(ccon->name, name) != 0)
3226 : 1028 : continue;
3227 : :
3228 [ + - ]: 108 : if (equal(expr, ccon->expr))
3229 : : {
3230 : : /* OK to merge constraint with existing */
3231 [ - + ]: 108 : if (pg_add_s16_overflow(ccon->inhcount, 1,
3232 : : &ccon->inhcount))
3233 [ # # ]: 0 : ereport(ERROR,
3234 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3235 : : errmsg("too many inheritance parents"));
3236 : :
3237 : : /*
3238 : : * When enforceability differs, the merged constraint should be
3239 : : * marked as ENFORCED because one of the parents is ENFORCED.
3240 : : */
3241 [ + + + + ]: 108 : if (!ccon->is_enforced && is_enforced)
3242 : : {
3243 : 32 : ccon->is_enforced = true;
3244 : 32 : ccon->skip_validation = false;
3245 : : }
3246 : :
3247 : 108 : return constraints;
3248 : : }
3249 : :
3250 [ # # ]: 0 : ereport(ERROR,
3251 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
3252 : : errmsg("check constraint name \"%s\" appears multiple times but with different expressions",
3253 : : name)));
3254 : : }
3255 : :
3256 : : /*
3257 : : * Constraint couldn't be merged with an existing one and also didn't
3258 : : * conflict with an existing one, so add it as a new one to the list.
3259 : : */
3260 : 421 : newcon = palloc0_object(CookedConstraint);
3261 : 421 : newcon->contype = CONSTR_CHECK;
3262 : 421 : newcon->name = pstrdup(name);
3263 : 421 : newcon->expr = expr;
3264 : 421 : newcon->inhcount = 1;
3265 : 421 : newcon->is_enforced = is_enforced;
3266 : 421 : newcon->skip_validation = !is_enforced;
3267 : 421 : return lappend(constraints, newcon);
3268 : : }
3269 : :
3270 : : /*
3271 : : * MergeChildAttribute
3272 : : * Merge given child attribute definition into given inherited attribute.
3273 : : *
3274 : : * Input arguments:
3275 : : * 'inh_columns' is the list of inherited ColumnDefs.
3276 : : * 'exist_attno' is the number of the inherited attribute in inh_columns
3277 : : * 'newcol_attno' is the attribute number in child table's schema definition
3278 : : * 'newdef' is the column/attribute definition from the child table.
3279 : : *
3280 : : * The ColumnDef in 'inh_columns' list is modified. The child attribute's
3281 : : * ColumnDef remains unchanged.
3282 : : *
3283 : : * Notes:
3284 : : * - The attribute is merged according to the rules laid out in the prologue
3285 : : * of MergeAttributes().
3286 : : * - If matching inherited attribute exists but the child attribute can not be
3287 : : * merged into it, the function throws respective errors.
3288 : : * - A partition can not have its own column definitions. Hence this function
3289 : : * is applicable only to a regular inheritance child.
3290 : : */
3291 : : static void
3292 : 251 : MergeChildAttribute(List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef)
3293 : : {
3294 : 251 : char *attributeName = newdef->colname;
3295 : : ColumnDef *inhdef;
3296 : : Oid inhtypeid,
3297 : : newtypeid;
3298 : : int32 inhtypmod,
3299 : : newtypmod;
3300 : : Oid inhcollid,
3301 : : newcollid;
3302 : :
3303 [ + + ]: 251 : if (exist_attno == newcol_attno)
3304 [ + - ]: 229 : ereport(NOTICE,
3305 : : (errmsg("merging column \"%s\" with inherited definition",
3306 : : attributeName)));
3307 : : else
3308 [ + - ]: 22 : ereport(NOTICE,
3309 : : (errmsg("moving and merging column \"%s\" with inherited definition", attributeName),
3310 : : errdetail("User-specified column moved to the position of the inherited column.")));
3311 : :
3312 : 251 : inhdef = list_nth_node(ColumnDef, inh_columns, exist_attno - 1);
3313 : :
3314 : : /*
3315 : : * Must have the same type and typmod
3316 : : */
3317 : 251 : typenameTypeIdAndMod(NULL, inhdef->typeName, &inhtypeid, &inhtypmod);
3318 : 251 : typenameTypeIdAndMod(NULL, newdef->typeName, &newtypeid, &newtypmod);
3319 [ + + + + ]: 251 : if (inhtypeid != newtypeid || inhtypmod != newtypmod)
3320 [ + - ]: 8 : ereport(ERROR,
3321 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3322 : : errmsg("column \"%s\" has a type conflict",
3323 : : attributeName),
3324 : : errdetail("%s versus %s",
3325 : : format_type_with_typemod(inhtypeid, inhtypmod),
3326 : : format_type_with_typemod(newtypeid, newtypmod))));
3327 : :
3328 : : /*
3329 : : * Must have the same collation
3330 : : */
3331 : 243 : inhcollid = GetColumnDefCollation(NULL, inhdef, inhtypeid);
3332 : 243 : newcollid = GetColumnDefCollation(NULL, newdef, newtypeid);
3333 [ + + ]: 243 : if (inhcollid != newcollid)
3334 [ + - ]: 4 : ereport(ERROR,
3335 : : (errcode(ERRCODE_COLLATION_MISMATCH),
3336 : : errmsg("column \"%s\" has a collation conflict",
3337 : : attributeName),
3338 : : errdetail("\"%s\" versus \"%s\"",
3339 : : get_collation_name(inhcollid),
3340 : : get_collation_name(newcollid))));
3341 : :
3342 : : /*
3343 : : * Identity is never inherited by a regular inheritance child. Pick
3344 : : * child's identity definition if there's one.
3345 : : */
3346 : 239 : inhdef->identity = newdef->identity;
3347 : :
3348 : : /*
3349 : : * Copy storage parameter
3350 : : */
3351 [ - + ]: 239 : if (inhdef->storage == 0)
3352 : 0 : inhdef->storage = newdef->storage;
3353 [ + + + + ]: 239 : else if (newdef->storage != 0 && inhdef->storage != newdef->storage)
3354 [ + - ]: 4 : ereport(ERROR,
3355 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3356 : : errmsg("column \"%s\" has a storage parameter conflict",
3357 : : attributeName),
3358 : : errdetail("%s versus %s",
3359 : : storage_name(inhdef->storage),
3360 : : storage_name(newdef->storage))));
3361 : :
3362 : : /*
3363 : : * Copy compression parameter
3364 : : */
3365 [ + + ]: 235 : if (inhdef->compression == NULL)
3366 : 231 : inhdef->compression = newdef->compression;
3367 [ + - ]: 4 : else if (newdef->compression != NULL)
3368 : : {
3369 [ + - ]: 4 : if (strcmp(inhdef->compression, newdef->compression) != 0)
3370 [ + - ]: 4 : ereport(ERROR,
3371 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3372 : : errmsg("column \"%s\" has a compression method conflict",
3373 : : attributeName),
3374 : : errdetail("%s versus %s", inhdef->compression, newdef->compression)));
3375 : : }
3376 : :
3377 : : /*
3378 : : * Merge of not-null constraints = OR 'em together
3379 : : */
3380 : 231 : inhdef->is_not_null |= newdef->is_not_null;
3381 : :
3382 : : /*
3383 : : * Check for conflicts related to generated columns.
3384 : : *
3385 : : * If the parent column is generated, the child column will be made a
3386 : : * generated column if it isn't already. If it is a generated column,
3387 : : * we'll take its generation expression in preference to the parent's. We
3388 : : * must check that the child column doesn't specify a default value or
3389 : : * identity, which matches the rules for a single column in
3390 : : * parse_utilcmd.c.
3391 : : *
3392 : : * Conversely, if the parent column is not generated, the child column
3393 : : * can't be either. (We used to allow that, but it results in being able
3394 : : * to override the generation expression via UPDATEs through the parent.)
3395 : : */
3396 [ + + ]: 231 : if (inhdef->generated)
3397 : : {
3398 [ + + + + ]: 41 : if (newdef->raw_default && !newdef->generated)
3399 [ + - ]: 8 : ereport(ERROR,
3400 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3401 : : errmsg("column \"%s\" inherits from generated column but specifies default",
3402 : : inhdef->colname)));
3403 [ + + ]: 33 : if (newdef->identity)
3404 [ + - ]: 8 : ereport(ERROR,
3405 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3406 : : errmsg("column \"%s\" inherits from generated column but specifies identity",
3407 : : inhdef->colname)));
3408 : : }
3409 : : else
3410 : : {
3411 [ + + ]: 190 : if (newdef->generated)
3412 [ + - ]: 8 : ereport(ERROR,
3413 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3414 : : errmsg("child column \"%s\" specifies generation expression",
3415 : : inhdef->colname),
3416 : : errhint("A child table column cannot be generated unless its parent column is.")));
3417 : : }
3418 : :
3419 [ + + + + : 207 : if (inhdef->generated && newdef->generated && newdef->generated != inhdef->generated)
+ + ]
3420 [ + - + + : 8 : ereport(ERROR,
+ + ]
3421 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
3422 : : errmsg("column \"%s\" inherits from generated column of different kind",
3423 : : inhdef->colname),
3424 : : errdetail("Parent column is %s, child column is %s.",
3425 : : inhdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
3426 : : newdef->generated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
3427 : :
3428 : : /*
3429 : : * If new def has a default, override previous default
3430 : : */
3431 [ + + ]: 199 : if (newdef->raw_default != NULL)
3432 : : {
3433 : 20 : inhdef->raw_default = newdef->raw_default;
3434 : 20 : inhdef->cooked_default = newdef->cooked_default;
3435 : : }
3436 : :
3437 : : /* Mark the column as locally defined */
3438 : 199 : inhdef->is_local = true;
3439 : 199 : }
3440 : :
3441 : : /*
3442 : : * MergeInheritedAttribute
3443 : : * Merge given parent attribute definition into specified attribute
3444 : : * inherited from the previous parents.
3445 : : *
3446 : : * Input arguments:
3447 : : * 'inh_columns' is the list of previously inherited ColumnDefs.
3448 : : * 'exist_attno' is the number the existing matching attribute in inh_columns.
3449 : : * 'newdef' is the new parent column/attribute definition to be merged.
3450 : : *
3451 : : * The matching ColumnDef in 'inh_columns' list is modified and returned.
3452 : : *
3453 : : * Notes:
3454 : : * - The attribute is merged according to the rules laid out in the prologue
3455 : : * of MergeAttributes().
3456 : : * - If matching inherited attribute exists but the new attribute can not be
3457 : : * merged into it, the function throws respective errors.
3458 : : * - A partition inherits from only a single parent. Hence this function is
3459 : : * applicable only to a regular inheritance.
3460 : : */
3461 : : static ColumnDef *
3462 : 253 : MergeInheritedAttribute(List *inh_columns,
3463 : : int exist_attno,
3464 : : const ColumnDef *newdef)
3465 : : {
3466 : 253 : char *attributeName = newdef->colname;
3467 : : ColumnDef *prevdef;
3468 : : Oid prevtypeid,
3469 : : newtypeid;
3470 : : int32 prevtypmod,
3471 : : newtypmod;
3472 : : Oid prevcollid,
3473 : : newcollid;
3474 : :
3475 [ + - ]: 253 : ereport(NOTICE,
3476 : : (errmsg("merging multiple inherited definitions of column \"%s\"",
3477 : : attributeName)));
3478 : 253 : prevdef = list_nth_node(ColumnDef, inh_columns, exist_attno - 1);
3479 : :
3480 : : /*
3481 : : * Must have the same type and typmod
3482 : : */
3483 : 253 : typenameTypeIdAndMod(NULL, prevdef->typeName, &prevtypeid, &prevtypmod);
3484 : 253 : typenameTypeIdAndMod(NULL, newdef->typeName, &newtypeid, &newtypmod);
3485 [ + - - + ]: 253 : if (prevtypeid != newtypeid || prevtypmod != newtypmod)
3486 [ # # ]: 0 : ereport(ERROR,
3487 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3488 : : errmsg("inherited column \"%s\" has a type conflict",
3489 : : attributeName),
3490 : : errdetail("%s versus %s",
3491 : : format_type_with_typemod(prevtypeid, prevtypmod),
3492 : : format_type_with_typemod(newtypeid, newtypmod))));
3493 : :
3494 : : /*
3495 : : * Must have the same collation
3496 : : */
3497 : 253 : prevcollid = GetColumnDefCollation(NULL, prevdef, prevtypeid);
3498 : 253 : newcollid = GetColumnDefCollation(NULL, newdef, newtypeid);
3499 [ - + ]: 253 : if (prevcollid != newcollid)
3500 [ # # ]: 0 : ereport(ERROR,
3501 : : (errcode(ERRCODE_COLLATION_MISMATCH),
3502 : : errmsg("inherited column \"%s\" has a collation conflict",
3503 : : attributeName),
3504 : : errdetail("\"%s\" versus \"%s\"",
3505 : : get_collation_name(prevcollid),
3506 : : get_collation_name(newcollid))));
3507 : :
3508 : : /*
3509 : : * Copy/check storage parameter
3510 : : */
3511 [ - + ]: 253 : if (prevdef->storage == 0)
3512 : 0 : prevdef->storage = newdef->storage;
3513 [ + + ]: 253 : else if (prevdef->storage != newdef->storage)
3514 [ + - ]: 4 : ereport(ERROR,
3515 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3516 : : errmsg("inherited column \"%s\" has a storage parameter conflict",
3517 : : attributeName),
3518 : : errdetail("%s versus %s",
3519 : : storage_name(prevdef->storage),
3520 : : storage_name(newdef->storage))));
3521 : :
3522 : : /*
3523 : : * Copy/check compression parameter
3524 : : */
3525 [ + + ]: 249 : if (prevdef->compression == NULL)
3526 : 237 : prevdef->compression = newdef->compression;
3527 [ + + ]: 12 : else if (newdef->compression != NULL)
3528 : : {
3529 [ + - ]: 4 : if (strcmp(prevdef->compression, newdef->compression) != 0)
3530 [ + - ]: 4 : ereport(ERROR,
3531 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3532 : : errmsg("column \"%s\" has a compression method conflict",
3533 : : attributeName),
3534 : : errdetail("%s versus %s",
3535 : : prevdef->compression, newdef->compression)));
3536 : : }
3537 : :
3538 : : /*
3539 : : * Check for GENERATED conflicts
3540 : : */
3541 [ + + ]: 245 : if (prevdef->generated != newdef->generated)
3542 [ + - ]: 16 : ereport(ERROR,
3543 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
3544 : : errmsg("inherited column \"%s\" has a generation conflict",
3545 : : attributeName)));
3546 : :
3547 : : /*
3548 : : * Default and other constraints are handled by the caller.
3549 : : */
3550 : :
3551 [ - + ]: 229 : if (pg_add_s16_overflow(prevdef->inhcount, 1,
3552 : : &prevdef->inhcount))
3553 [ # # ]: 0 : ereport(ERROR,
3554 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3555 : : errmsg("too many inheritance parents"));
3556 : :
3557 : 229 : return prevdef;
3558 : : }
3559 : :
3560 : : /*
3561 : : * StoreCatalogInheritance
3562 : : * Updates the system catalogs with proper inheritance information.
3563 : : *
3564 : : * supers is a list of the OIDs of the new relation's direct ancestors.
3565 : : */
3566 : : static void
3567 : 40227 : StoreCatalogInheritance(Oid relationId, List *supers,
3568 : : bool child_is_partition)
3569 : : {
3570 : : Relation relation;
3571 : : int32 seqNumber;
3572 : : ListCell *entry;
3573 : :
3574 : : /*
3575 : : * sanity checks
3576 : : */
3577 : : Assert(OidIsValid(relationId));
3578 : :
3579 [ + + ]: 40227 : if (supers == NIL)
3580 : 33239 : return;
3581 : :
3582 : : /*
3583 : : * Store INHERITS information in pg_inherits using direct ancestors only.
3584 : : * Also enter dependencies on the direct ancestors, and make sure they are
3585 : : * marked with relhassubclass = true.
3586 : : *
3587 : : * (Once upon a time, both direct and indirect ancestors were found here
3588 : : * and then entered into pg_ipl. Since that catalog doesn't exist
3589 : : * anymore, there's no need to look for indirect ancestors.)
3590 : : */
3591 : 6988 : relation = table_open(InheritsRelationId, RowExclusiveLock);
3592 : :
3593 : 6988 : seqNumber = 1;
3594 [ + - + + : 14206 : foreach(entry, supers)
+ + ]
3595 : : {
3596 : 7218 : Oid parentOid = lfirst_oid(entry);
3597 : :
3598 : 7218 : StoreCatalogInheritance1(relationId, parentOid, seqNumber, relation,
3599 : : child_is_partition);
3600 : 7218 : seqNumber++;
3601 : : }
3602 : :
3603 : 6988 : table_close(relation, RowExclusiveLock);
3604 : : }
3605 : :
3606 : : /*
3607 : : * Make catalog entries showing relationId as being an inheritance child
3608 : : * of parentOid. inhRelation is the already-opened pg_inherits catalog.
3609 : : */
3610 : : static void
3611 : 8776 : StoreCatalogInheritance1(Oid relationId, Oid parentOid,
3612 : : int32 seqNumber, Relation inhRelation,
3613 : : bool child_is_partition)
3614 : : {
3615 : : ObjectAddress childobject,
3616 : : parentobject;
3617 : :
3618 : : /* store the pg_inherits row */
3619 : 8776 : StoreSingleInheritance(relationId, parentOid, seqNumber);
3620 : :
3621 : : /*
3622 : : * Store a dependency too
3623 : : */
3624 : 8776 : parentobject.classId = RelationRelationId;
3625 : 8776 : parentobject.objectId = parentOid;
3626 : 8776 : parentobject.objectSubId = 0;
3627 : 8776 : childobject.classId = RelationRelationId;
3628 : 8776 : childobject.objectId = relationId;
3629 : 8776 : childobject.objectSubId = 0;
3630 : :
3631 [ + + ]: 8776 : recordDependencyOn(&childobject, &parentobject,
3632 : : child_dependency_type(child_is_partition));
3633 : :
3634 : : /*
3635 : : * Post creation hook of this inheritance. Since object_access_hook
3636 : : * doesn't take multiple object identifiers, we relay oid of parent
3637 : : * relation using auxiliary_id argument.
3638 : : */
3639 [ - + ]: 8776 : InvokeObjectPostAlterHookArg(InheritsRelationId,
3640 : : relationId, 0,
3641 : : parentOid, false);
3642 : :
3643 : : /*
3644 : : * Mark the parent as having subclasses.
3645 : : */
3646 : 8776 : SetRelationHasSubclass(parentOid, true);
3647 : 8776 : }
3648 : :
3649 : : /*
3650 : : * Look for an existing column entry with the given name.
3651 : : *
3652 : : * Returns the index (starting with 1) if attribute already exists in columns,
3653 : : * 0 if it doesn't.
3654 : : */
3655 : : static int
3656 : 15204 : findAttrByName(const char *attributeName, const List *columns)
3657 : : {
3658 : : ListCell *lc;
3659 : 15204 : int i = 1;
3660 : :
3661 [ + + + + : 26553 : foreach(lc, columns)
+ + ]
3662 : : {
3663 [ + + ]: 11853 : if (strcmp(attributeName, lfirst_node(ColumnDef, lc)->colname) == 0)
3664 : 504 : return i;
3665 : :
3666 : 11349 : i++;
3667 : : }
3668 : 14700 : return 0;
3669 : : }
3670 : :
3671 : :
3672 : : /*
3673 : : * SetRelationHasSubclass
3674 : : * Set the value of the relation's relhassubclass field in pg_class.
3675 : : *
3676 : : * It's always safe to set this field to true, because all SQL commands are
3677 : : * ready to see true and then find no children. On the other hand, commands
3678 : : * generally assume zero children if this is false.
3679 : : *
3680 : : * Caller must hold any self-exclusive lock until end of transaction. If the
3681 : : * new value is false, caller must have acquired that lock before reading the
3682 : : * evidence that justified the false value. That way, it properly waits if
3683 : : * another backend is simultaneously concluding no need to change the tuple
3684 : : * (new and old values are true).
3685 : : *
3686 : : * NOTE: an important side-effect of this operation is that an SI invalidation
3687 : : * message is sent out to all backends --- including me --- causing plans
3688 : : * referencing the relation to be rebuilt with the new list of children.
3689 : : * This must happen even if we find that no change is needed in the pg_class
3690 : : * row.
3691 : : */
3692 : : void
3693 : 10832 : SetRelationHasSubclass(Oid relationId, bool relhassubclass)
3694 : : {
3695 : : Relation relationRelation;
3696 : : HeapTuple tuple;
3697 : : Form_pg_class classtuple;
3698 : :
3699 : : Assert(CheckRelationOidLockedByMe(relationId,
3700 : : ShareUpdateExclusiveLock, false) ||
3701 : : CheckRelationOidLockedByMe(relationId,
3702 : : ShareRowExclusiveLock, true));
3703 : :
3704 : : /*
3705 : : * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3706 : : */
3707 : 10832 : relationRelation = table_open(RelationRelationId, RowExclusiveLock);
3708 : 10832 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
3709 [ - + ]: 10832 : if (!HeapTupleIsValid(tuple))
3710 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relationId);
3711 : 10832 : classtuple = (Form_pg_class) GETSTRUCT(tuple);
3712 : :
3713 [ + + ]: 10832 : if (classtuple->relhassubclass != relhassubclass)
3714 : : {
3715 : 5248 : classtuple->relhassubclass = relhassubclass;
3716 : 5248 : CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
3717 : : }
3718 : : else
3719 : : {
3720 : : /* no need to change tuple, but force relcache rebuild anyway */
3721 : 5584 : CacheInvalidateRelcacheByTuple(tuple);
3722 : : }
3723 : :
3724 : 10832 : heap_freetuple(tuple);
3725 : 10832 : table_close(relationRelation, RowExclusiveLock);
3726 : 10832 : }
3727 : :
3728 : : /*
3729 : : * CheckRelationTableSpaceMove
3730 : : * Check if relation can be moved to new tablespace.
3731 : : *
3732 : : * NOTE: The caller must hold AccessExclusiveLock on the relation.
3733 : : *
3734 : : * Returns true if the relation can be moved to the new tablespace; raises
3735 : : * an error if it is not possible to do the move; returns false if the move
3736 : : * would have no effect.
3737 : : */
3738 : : bool
3739 : 156 : CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
3740 : : {
3741 : : Oid oldTableSpaceId;
3742 : :
3743 : : /*
3744 : : * No work if no change in tablespace. Note that MyDatabaseTableSpace is
3745 : : * stored as 0.
3746 : : */
3747 : 156 : oldTableSpaceId = rel->rd_rel->reltablespace;
3748 [ + + ]: 156 : if (newTableSpaceId == oldTableSpaceId ||
3749 [ + + + + ]: 151 : (newTableSpaceId == MyDatabaseTableSpace && oldTableSpaceId == 0))
3750 : 10 : return false;
3751 : :
3752 : : /*
3753 : : * We cannot support moving mapped relations into different tablespaces.
3754 : : * (In particular this eliminates all shared catalogs.)
3755 : : */
3756 [ + + + + : 146 : if (RelationIsMapped(rel))
+ - + + +
+ - + ]
3757 [ # # ]: 0 : ereport(ERROR,
3758 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3759 : : errmsg("cannot move system relation \"%s\"",
3760 : : RelationGetRelationName(rel))));
3761 : :
3762 : : /* Cannot move a non-shared relation into pg_global */
3763 [ + + ]: 146 : if (newTableSpaceId == GLOBALTABLESPACE_OID)
3764 [ + - ]: 8 : ereport(ERROR,
3765 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3766 : : errmsg("only shared relations can be placed in pg_global tablespace")));
3767 : :
3768 : : /*
3769 : : * Do not allow moving temp tables of other backends ... their local
3770 : : * buffer manager is not going to cope.
3771 : : */
3772 [ + + - + ]: 138 : if (RELATION_IS_OTHER_TEMP(rel))
3773 [ # # ]: 0 : ereport(ERROR,
3774 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3775 : : errmsg("cannot move temporary tables of other sessions")));
3776 : :
3777 : 138 : return true;
3778 : : }
3779 : :
3780 : : /*
3781 : : * SetRelationTableSpace
3782 : : * Set new reltablespace and relfilenumber in pg_class entry.
3783 : : *
3784 : : * newTableSpaceId is the new tablespace for the relation, and
3785 : : * newRelFilenumber its new filenumber. If newRelFilenumber is
3786 : : * InvalidRelFileNumber, this field is not updated.
3787 : : *
3788 : : * NOTE: The caller must hold AccessExclusiveLock on the relation.
3789 : : *
3790 : : * The caller of this routine had better check if a relation can be
3791 : : * moved to this new tablespace by calling CheckRelationTableSpaceMove()
3792 : : * first, and is responsible for making the change visible with
3793 : : * CommandCounterIncrement().
3794 : : */
3795 : : void
3796 : 138 : SetRelationTableSpace(Relation rel,
3797 : : Oid newTableSpaceId,
3798 : : RelFileNumber newRelFilenumber)
3799 : : {
3800 : : Relation pg_class;
3801 : : HeapTuple tuple;
3802 : : ItemPointerData otid;
3803 : : Form_pg_class rd_rel;
3804 : 138 : Oid reloid = RelationGetRelid(rel);
3805 : :
3806 : : Assert(CheckRelationTableSpaceMove(rel, newTableSpaceId));
3807 : :
3808 : : /* Get a modifiable copy of the relation's pg_class row. */
3809 : 138 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
3810 : :
3811 : 138 : tuple = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(reloid));
3812 [ - + ]: 138 : if (!HeapTupleIsValid(tuple))
3813 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", reloid);
3814 : 138 : otid = tuple->t_self;
3815 : 138 : rd_rel = (Form_pg_class) GETSTRUCT(tuple);
3816 : :
3817 : : /* Update the pg_class row. */
3818 : 276 : rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
3819 [ + + ]: 138 : InvalidOid : newTableSpaceId;
3820 [ + + ]: 138 : if (RelFileNumberIsValid(newRelFilenumber))
3821 : 109 : rd_rel->relfilenode = newRelFilenumber;
3822 : 138 : CatalogTupleUpdate(pg_class, &otid, tuple);
3823 : 138 : UnlockTuple(pg_class, &otid, InplaceUpdateTupleLock);
3824 : :
3825 : : /*
3826 : : * Record dependency on tablespace. This is only required for relations
3827 : : * that have no physical storage.
3828 : : */
3829 [ + + + + : 138 : if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
+ - + + +
+ ]
3830 : 20 : changeDependencyOnTablespace(RelationRelationId, reloid,
3831 : : rd_rel->reltablespace);
3832 : :
3833 : 138 : heap_freetuple(tuple);
3834 : 138 : table_close(pg_class, RowExclusiveLock);
3835 : 138 : }
3836 : :
3837 : : /*
3838 : : * renameatt_check - basic sanity checks before attribute rename
3839 : : */
3840 : : static void
3841 : 683 : renameatt_check(Oid myrelid, Form_pg_class classform, bool recursing)
3842 : : {
3843 : 683 : char relkind = classform->relkind;
3844 : :
3845 [ + + + + ]: 683 : if (classform->reloftype && !recursing)
3846 [ + - ]: 4 : ereport(ERROR,
3847 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3848 : : errmsg("cannot rename column of typed table")));
3849 : :
3850 : : /*
3851 : : * Renaming the columns of sequences or toast tables doesn't actually
3852 : : * break anything from the system's point of view, since internal
3853 : : * references are by attnum. But it doesn't seem right to allow users to
3854 : : * change names that are hardcoded into the system, hence the following
3855 : : * restriction.
3856 : : */
3857 [ + + + + ]: 679 : if (relkind != RELKIND_RELATION &&
3858 [ + - ]: 56 : relkind != RELKIND_VIEW &&
3859 [ + + ]: 56 : relkind != RELKIND_MATVIEW &&
3860 [ + - ]: 24 : relkind != RELKIND_COMPOSITE_TYPE &&
3861 [ + - ]: 24 : relkind != RELKIND_INDEX &&
3862 [ - + ]: 24 : relkind != RELKIND_PARTITIONED_INDEX &&
3863 [ # # ]: 0 : relkind != RELKIND_FOREIGN_TABLE &&
3864 : : relkind != RELKIND_PARTITIONED_TABLE)
3865 [ # # ]: 0 : ereport(ERROR,
3866 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3867 : : errmsg("cannot rename columns of relation \"%s\"",
3868 : : NameStr(classform->relname)),
3869 : : errdetail_relkind_not_supported(relkind)));
3870 : :
3871 : : /*
3872 : : * permissions checking. only the owner of a class can change its schema.
3873 : : */
3874 [ - + ]: 679 : if (!object_ownercheck(RelationRelationId, myrelid, GetUserId()))
3875 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(myrelid)),
3876 : 0 : NameStr(classform->relname));
3877 : :
3878 : : /*
3879 : : * Conflict log tables are used internally for logical replication
3880 : : * conflict logging and should not be modified directly, as it could
3881 : : * disrupt conflict logging.
3882 : : */
3883 [ + + ]: 679 : if (IsConflictLogTableClass(classform))
3884 [ + - ]: 4 : ereport(ERROR,
3885 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3886 : : errmsg("cannot rename columns of conflict log table \"%s\"",
3887 : : NameStr(classform->relname)),
3888 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
3889 : :
3890 [ + + + + ]: 675 : if (!allowSystemTableMods && IsSystemClass(myrelid, classform))
3891 [ + - ]: 1 : ereport(ERROR,
3892 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3893 : : errmsg("permission denied: \"%s\" is a system catalog",
3894 : : NameStr(classform->relname))));
3895 : 674 : }
3896 : :
3897 : : /*
3898 : : * renameatt_internal - workhorse for renameatt
3899 : : *
3900 : : * Return value is the attribute number in the 'myrelid' relation.
3901 : : */
3902 : : static AttrNumber
3903 : 366 : renameatt_internal(Oid myrelid,
3904 : : const char *oldattname,
3905 : : const char *newattname,
3906 : : bool recurse,
3907 : : bool recursing,
3908 : : int expected_parents,
3909 : : DropBehavior behavior)
3910 : : {
3911 : : Relation targetrelation;
3912 : : Relation attrelation;
3913 : : HeapTuple atttup;
3914 : : Form_pg_attribute attform;
3915 : : AttrNumber attnum;
3916 : :
3917 : : /*
3918 : : * Grab an exclusive lock on the target table, which we will NOT release
3919 : : * until end of transaction.
3920 : : */
3921 : 366 : targetrelation = relation_open(myrelid, AccessExclusiveLock);
3922 : 366 : renameatt_check(myrelid, RelationGetForm(targetrelation), recursing);
3923 : :
3924 : : /*
3925 : : * if the 'recurse' flag is set then we are supposed to rename this
3926 : : * attribute in all classes that inherit from 'relname' (as well as in
3927 : : * 'relname').
3928 : : *
3929 : : * any permissions or problems with duplicate attributes will cause the
3930 : : * whole transaction to abort, which is what we want -- all or nothing.
3931 : : */
3932 [ + + ]: 366 : if (recurse)
3933 : : {
3934 : : List *child_oids,
3935 : : *child_numparents;
3936 : : ListCell *lo,
3937 : : *li;
3938 : :
3939 : : /*
3940 : : * we need the number of parents for each child so that the recursive
3941 : : * calls to renameatt() can determine whether there are any parents
3942 : : * outside the inheritance hierarchy being processed.
3943 : : */
3944 : 164 : child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
3945 : : &child_numparents);
3946 : :
3947 : : /*
3948 : : * find_all_inheritors does the recursive search of the inheritance
3949 : : * hierarchy, so all we have to do is process all of the relids in the
3950 : : * list that it returns.
3951 : : */
3952 [ + - + + : 486 : forboth(lo, child_oids, li, child_numparents)
+ - + + +
+ + - +
+ ]
3953 : : {
3954 : 342 : Oid childrelid = lfirst_oid(lo);
3955 : 342 : int numparents = lfirst_int(li);
3956 : :
3957 [ + + ]: 342 : if (childrelid == myrelid)
3958 : 164 : continue;
3959 : : /* note we need not recurse again */
3960 : 178 : renameatt_internal(childrelid, oldattname, newattname, false, true, numparents, behavior);
3961 : : }
3962 : : }
3963 : : else
3964 : : {
3965 : : /*
3966 : : * If we are told not to recurse, there had better not be any child
3967 : : * tables; else the rename would put them out of step.
3968 : : *
3969 : : * expected_parents will only be 0 if we are not already recursing.
3970 : : */
3971 [ + + + + ]: 226 : if (expected_parents == 0 &&
3972 : 24 : find_inheritance_children(myrelid, NoLock) != NIL)
3973 [ + - ]: 8 : ereport(ERROR,
3974 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3975 : : errmsg("inherited column \"%s\" must be renamed in child tables too",
3976 : : oldattname)));
3977 : : }
3978 : :
3979 : : /* rename attributes in typed tables of composite type */
3980 [ + + ]: 338 : if (targetrelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
3981 : : {
3982 : : List *child_oids;
3983 : : ListCell *lo;
3984 : :
3985 : 16 : child_oids = find_typed_table_dependencies(targetrelation->rd_rel->reltype,
3986 : 16 : RelationGetRelationName(targetrelation),
3987 : : behavior);
3988 : :
3989 [ + + + + : 16 : foreach(lo, child_oids)
+ + ]
3990 : 4 : renameatt_internal(lfirst_oid(lo), oldattname, newattname, true, true, 0, behavior);
3991 : : }
3992 : :
3993 : 334 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
3994 : :
3995 : 334 : atttup = SearchSysCacheCopyAttName(myrelid, oldattname);
3996 [ + + ]: 334 : if (!HeapTupleIsValid(atttup))
3997 [ + - ]: 16 : ereport(ERROR,
3998 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
3999 : : errmsg("column \"%s\" does not exist",
4000 : : oldattname)));
4001 : 318 : attform = (Form_pg_attribute) GETSTRUCT(atttup);
4002 : :
4003 : 318 : attnum = attform->attnum;
4004 [ - + ]: 318 : if (attnum <= 0)
4005 [ # # ]: 0 : ereport(ERROR,
4006 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4007 : : errmsg("cannot rename system column \"%s\"",
4008 : : oldattname)));
4009 : :
4010 : : /*
4011 : : * if the attribute is inherited, forbid the renaming. if this is a
4012 : : * top-level call to renameatt(), then expected_parents will be 0, so the
4013 : : * effect of this code will be to prohibit the renaming if the attribute
4014 : : * is inherited at all. if this is a recursive call to renameatt(),
4015 : : * expected_parents will be the number of parents the current relation has
4016 : : * within the inheritance hierarchy being processed, so we'll prohibit the
4017 : : * renaming only if there are additional parents from elsewhere.
4018 : : */
4019 [ + + ]: 318 : if (attform->attinhcount > expected_parents)
4020 [ + - ]: 20 : ereport(ERROR,
4021 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4022 : : errmsg("cannot rename inherited column \"%s\"",
4023 : : oldattname)));
4024 : :
4025 : : /* new name should not already exist */
4026 : 298 : (void) check_for_column_name_collision(targetrelation, newattname, false);
4027 : :
4028 : : /* apply the update */
4029 : 290 : namestrcpy(&(attform->attname), newattname);
4030 : :
4031 : 290 : CatalogTupleUpdate(attrelation, &atttup->t_self, atttup);
4032 : :
4033 [ - + ]: 290 : InvokeObjectPostAlterHook(RelationRelationId, myrelid, attnum);
4034 : :
4035 : 290 : heap_freetuple(atttup);
4036 : :
4037 : 290 : table_close(attrelation, RowExclusiveLock);
4038 : :
4039 : 290 : relation_close(targetrelation, NoLock); /* close rel but keep lock */
4040 : :
4041 : 290 : return attnum;
4042 : : }
4043 : :
4044 : : /*
4045 : : * Perform permissions and integrity checks before acquiring a relation lock.
4046 : : */
4047 : : static void
4048 : 281 : RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid,
4049 : : void *arg)
4050 : : {
4051 : : HeapTuple tuple;
4052 : : Form_pg_class form;
4053 : :
4054 : 281 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
4055 [ + + ]: 281 : if (!HeapTupleIsValid(tuple))
4056 : 24 : return; /* concurrently dropped */
4057 : 257 : form = (Form_pg_class) GETSTRUCT(tuple);
4058 : 257 : renameatt_check(relid, form, false);
4059 : 248 : ReleaseSysCache(tuple);
4060 : : }
4061 : :
4062 : : /*
4063 : : * renameatt - changes the name of an attribute in a relation
4064 : : *
4065 : : * The returned ObjectAddress is that of the renamed column.
4066 : : */
4067 : : ObjectAddress
4068 : 213 : renameatt(RenameStmt *stmt)
4069 : : {
4070 : : Oid relid;
4071 : : AttrNumber attnum;
4072 : : ObjectAddress address;
4073 : :
4074 : : /* lock level taken here should match renameatt_internal */
4075 : 213 : relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
4076 : 213 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4077 : : RangeVarCallbackForRenameAttribute,
4078 : : NULL);
4079 : :
4080 [ + + ]: 200 : if (!OidIsValid(relid))
4081 : : {
4082 [ + - ]: 16 : ereport(NOTICE,
4083 : : (errmsg("relation \"%s\" does not exist, skipping",
4084 : : stmt->relation->relname)));
4085 : 16 : return InvalidObjectAddress;
4086 : : }
4087 : :
4088 : : attnum =
4089 : 184 : renameatt_internal(relid,
4090 : 184 : stmt->subname, /* old att name */
4091 : 184 : stmt->newname, /* new att name */
4092 : 184 : stmt->relation->inh, /* recursive? */
4093 : : false, /* recursing? */
4094 : : 0, /* expected inhcount */
4095 : : stmt->behavior);
4096 : :
4097 : 128 : ObjectAddressSubSet(address, RelationRelationId, relid, attnum);
4098 : :
4099 : 128 : return address;
4100 : : }
4101 : :
4102 : : /*
4103 : : * same logic as renameatt_internal
4104 : : */
4105 : : static ObjectAddress
4106 : 64 : rename_constraint_internal(Oid myrelid,
4107 : : Oid mytypid,
4108 : : const char *oldconname,
4109 : : const char *newconname,
4110 : : bool recurse,
4111 : : bool recursing,
4112 : : int expected_parents)
4113 : : {
4114 : 64 : Relation targetrelation = NULL;
4115 : : Oid constraintOid;
4116 : : HeapTuple tuple;
4117 : : Form_pg_constraint con;
4118 : : ObjectAddress address;
4119 : :
4120 : : Assert(!myrelid || !mytypid);
4121 : :
4122 [ + + ]: 64 : if (mytypid)
4123 : : {
4124 : 4 : constraintOid = get_domain_constraint_oid(mytypid, oldconname, false);
4125 : : }
4126 : : else
4127 : : {
4128 : 60 : targetrelation = relation_open(myrelid, AccessExclusiveLock);
4129 : :
4130 : : /*
4131 : : * don't tell it whether we're recursing; we allow changing typed
4132 : : * tables here
4133 : : */
4134 : 60 : renameatt_check(myrelid, RelationGetForm(targetrelation), false);
4135 : :
4136 : 60 : constraintOid = get_relation_constraint_oid(myrelid, oldconname, false);
4137 : : }
4138 : :
4139 : 64 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constraintOid));
4140 [ - + ]: 64 : if (!HeapTupleIsValid(tuple))
4141 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u",
4142 : : constraintOid);
4143 : 64 : con = (Form_pg_constraint) GETSTRUCT(tuple);
4144 : :
4145 [ + + ]: 64 : if (myrelid &&
4146 [ + + ]: 60 : (con->contype == CONSTRAINT_CHECK ||
4147 [ + + ]: 20 : con->contype == CONSTRAINT_NOTNULL) &&
4148 [ + + ]: 44 : !con->connoinherit)
4149 : : {
4150 [ + + ]: 36 : if (recurse)
4151 : : {
4152 : : List *child_oids,
4153 : : *child_numparents;
4154 : : ListCell *lo,
4155 : : *li;
4156 : :
4157 : 24 : child_oids = find_all_inheritors(myrelid, AccessExclusiveLock,
4158 : : &child_numparents);
4159 : :
4160 [ + - + + : 56 : forboth(lo, child_oids, li, child_numparents)
+ - + + +
+ + - +
+ ]
4161 : : {
4162 : 32 : Oid childrelid = lfirst_oid(lo);
4163 : 32 : int numparents = lfirst_int(li);
4164 : :
4165 [ + + ]: 32 : if (childrelid == myrelid)
4166 : 24 : continue;
4167 : :
4168 : 8 : rename_constraint_internal(childrelid, InvalidOid, oldconname, newconname, false, true, numparents);
4169 : : }
4170 : : }
4171 : : else
4172 : : {
4173 [ + + + - ]: 16 : if (expected_parents == 0 &&
4174 : 4 : find_inheritance_children(myrelid, NoLock) != NIL)
4175 [ + - ]: 4 : ereport(ERROR,
4176 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4177 : : errmsg("inherited constraint \"%s\" must be renamed in child tables too",
4178 : : oldconname)));
4179 : : }
4180 : :
4181 [ + + ]: 32 : if (con->coninhcount > expected_parents)
4182 [ + - ]: 4 : ereport(ERROR,
4183 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4184 : : errmsg("cannot rename inherited constraint \"%s\"",
4185 : : oldconname)));
4186 : : }
4187 : :
4188 [ + + ]: 56 : if (con->conindid
4189 [ + + ]: 16 : && (con->contype == CONSTRAINT_PRIMARY
4190 [ + + ]: 8 : || con->contype == CONSTRAINT_UNIQUE
4191 [ - + ]: 4 : || con->contype == CONSTRAINT_EXCLUSION))
4192 : : /* rename the index; this renames the constraint as well */
4193 : 12 : RenameRelationInternal(con->conindid, newconname, false, true);
4194 : : else
4195 : 44 : RenameConstraintById(constraintOid, newconname);
4196 : :
4197 : 56 : ObjectAddressSet(address, ConstraintRelationId, constraintOid);
4198 : :
4199 : 56 : ReleaseSysCache(tuple);
4200 : :
4201 [ + + ]: 56 : if (targetrelation)
4202 : : {
4203 : : /*
4204 : : * Invalidate relcache so as others can see the new constraint name.
4205 : : */
4206 : 52 : CacheInvalidateRelcache(targetrelation);
4207 : :
4208 : 52 : relation_close(targetrelation, NoLock); /* close rel but keep lock */
4209 : : }
4210 : :
4211 : 56 : return address;
4212 : : }
4213 : :
4214 : : ObjectAddress
4215 : 60 : RenameConstraint(RenameStmt *stmt)
4216 : : {
4217 : 60 : Oid relid = InvalidOid;
4218 : 60 : Oid typid = InvalidOid;
4219 : :
4220 [ + + ]: 60 : if (stmt->renameType == OBJECT_DOMCONSTRAINT)
4221 : : {
4222 : : Relation rel;
4223 : : HeapTuple tup;
4224 : :
4225 : 4 : typid = typenameTypeId(NULL, makeTypeNameFromNameList(castNode(List, stmt->object)));
4226 : 4 : rel = table_open(TypeRelationId, RowExclusiveLock);
4227 : 4 : tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
4228 [ - + ]: 4 : if (!HeapTupleIsValid(tup))
4229 [ # # ]: 0 : elog(ERROR, "cache lookup failed for type %u", typid);
4230 : 4 : checkDomainOwner(tup);
4231 : 4 : ReleaseSysCache(tup);
4232 : 4 : table_close(rel, NoLock);
4233 : : }
4234 : : else
4235 : : {
4236 : : /* lock level taken here should match rename_constraint_internal */
4237 : 56 : relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
4238 : 56 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4239 : : RangeVarCallbackForRenameAttribute,
4240 : : NULL);
4241 [ + + ]: 56 : if (!OidIsValid(relid))
4242 : : {
4243 [ + - ]: 4 : ereport(NOTICE,
4244 : : (errmsg("relation \"%s\" does not exist, skipping",
4245 : : stmt->relation->relname)));
4246 : 4 : return InvalidObjectAddress;
4247 : : }
4248 : : }
4249 : :
4250 : : return
4251 : 56 : rename_constraint_internal(relid, typid,
4252 : 56 : stmt->subname,
4253 : 56 : stmt->newname,
4254 [ + + ]: 108 : (stmt->relation &&
4255 [ + + ]: 52 : stmt->relation->inh), /* recursive? */
4256 : : false, /* recursing? */
4257 : 56 : 0 /* expected inhcount */ );
4258 : : }
4259 : :
4260 : : /*
4261 : : * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/MATERIALIZED VIEW/FOREIGN TABLE
4262 : : * RENAME
4263 : : */
4264 : : ObjectAddress
4265 : 303 : RenameRelation(RenameStmt *stmt)
4266 : : {
4267 : 303 : bool is_index_stmt = stmt->renameType == OBJECT_INDEX;
4268 : : Oid relid;
4269 : : ObjectAddress address;
4270 : :
4271 : : /*
4272 : : * Grab an exclusive lock on the target table, index, sequence, view,
4273 : : * materialized view, or foreign table, which we will NOT release until
4274 : : * end of transaction.
4275 : : *
4276 : : * Lock level used here should match RenameRelationInternal, to avoid lock
4277 : : * escalation. However, because ALTER INDEX can be used with any relation
4278 : : * type, we mustn't believe without verification.
4279 : : */
4280 : : for (;;)
4281 : 8 : {
4282 : : LOCKMODE lockmode;
4283 : : char relkind;
4284 : : bool obj_is_index;
4285 : :
4286 [ + + ]: 311 : lockmode = is_index_stmt ? ShareUpdateExclusiveLock : AccessExclusiveLock;
4287 : :
4288 : 311 : relid = RangeVarGetRelidExtended(stmt->relation, lockmode,
4289 : 311 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4290 : : RangeVarCallbackForAlterRelation,
4291 : : stmt);
4292 : :
4293 [ + + ]: 278 : if (!OidIsValid(relid))
4294 : : {
4295 [ + - ]: 12 : ereport(NOTICE,
4296 : : (errmsg("relation \"%s\" does not exist, skipping",
4297 : : stmt->relation->relname)));
4298 : 12 : return InvalidObjectAddress;
4299 : : }
4300 : :
4301 : : /*
4302 : : * We allow mismatched statement and object types (e.g., ALTER INDEX
4303 : : * to rename a table), but we might've used the wrong lock level. If
4304 : : * that happens, retry with the correct lock level. We don't bother
4305 : : * if we already acquired AccessExclusiveLock with an index, however.
4306 : : */
4307 : 266 : relkind = get_rel_relkind(relid);
4308 [ + + + + ]: 266 : obj_is_index = (relkind == RELKIND_INDEX ||
4309 : : relkind == RELKIND_PARTITIONED_INDEX);
4310 [ + + + + ]: 266 : if (obj_is_index || is_index_stmt == obj_is_index)
4311 : : break;
4312 : :
4313 : 8 : UnlockRelationOid(relid, lockmode);
4314 : 8 : is_index_stmt = obj_is_index;
4315 : : }
4316 : :
4317 : : /* Do the work */
4318 : 258 : RenameRelationInternal(relid, stmt->newname, false, is_index_stmt);
4319 : :
4320 : 250 : ObjectAddressSet(address, RelationRelationId, relid);
4321 : :
4322 : 250 : return address;
4323 : : }
4324 : :
4325 : : /*
4326 : : * RenameRelationInternal - change the name of a relation
4327 : : */
4328 : : void
4329 : 1052 : RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
4330 : : {
4331 : : Relation targetrelation;
4332 : : Relation relrelation; /* for RELATION relation */
4333 : : ItemPointerData otid;
4334 : : HeapTuple reltup;
4335 : : Form_pg_class relform;
4336 : : Oid namespaceId;
4337 : :
4338 : : /*
4339 : : * Grab a lock on the target relation, which we will NOT release until end
4340 : : * of transaction. We need at least a self-exclusive lock so that
4341 : : * concurrent DDL doesn't overwrite the rename if they start updating
4342 : : * while still seeing the old version. The lock also guards against
4343 : : * triggering relcache reloads in concurrent sessions, which might not
4344 : : * handle this information changing under them. For indexes, we can use a
4345 : : * reduced lock level because RelationReloadIndexInfo() handles indexes
4346 : : * specially.
4347 : : */
4348 [ + + ]: 1052 : targetrelation = relation_open(myrelid, is_index ? ShareUpdateExclusiveLock : AccessExclusiveLock);
4349 : 1052 : namespaceId = RelationGetNamespace(targetrelation);
4350 : :
4351 : : /*
4352 : : * Find relation's pg_class tuple, and make sure newrelname isn't in use.
4353 : : */
4354 : 1052 : relrelation = table_open(RelationRelationId, RowExclusiveLock);
4355 : :
4356 : 1052 : reltup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(myrelid));
4357 [ - + ]: 1052 : if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4358 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", myrelid);
4359 : 1052 : otid = reltup->t_self;
4360 : 1052 : relform = (Form_pg_class) GETSTRUCT(reltup);
4361 : :
4362 [ + + ]: 1052 : if (get_relname_relid(newrelname, namespaceId) != InvalidOid)
4363 [ + - ]: 8 : ereport(ERROR,
4364 : : (errcode(ERRCODE_DUPLICATE_TABLE),
4365 : : errmsg("relation \"%s\" already exists",
4366 : : newrelname)));
4367 : :
4368 : : /*
4369 : : * RenameRelation is careful not to believe the caller's idea of the
4370 : : * relation kind being handled. We don't have to worry about this, but
4371 : : * let's not be totally oblivious to it. We can process an index as
4372 : : * not-an-index, but not the other way around.
4373 : : */
4374 : : Assert(!is_index ||
4375 : : is_index == (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4376 : : targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX));
4377 : :
4378 : : /*
4379 : : * Update pg_class tuple with new relname. (Scribbling on reltup is OK
4380 : : * because it's a copy...)
4381 : : */
4382 : 1044 : namestrcpy(&(relform->relname), newrelname);
4383 : :
4384 : 1044 : CatalogTupleUpdate(relrelation, &otid, reltup);
4385 : 1044 : UnlockTuple(relrelation, &otid, InplaceUpdateTupleLock);
4386 : :
4387 [ - + ]: 1044 : InvokeObjectPostAlterHookArg(RelationRelationId, myrelid, 0,
4388 : : InvalidOid, is_internal);
4389 : :
4390 : 1044 : heap_freetuple(reltup);
4391 : 1044 : table_close(relrelation, RowExclusiveLock);
4392 : :
4393 : : /*
4394 : : * Also rename the associated type, if any.
4395 : : */
4396 [ + + ]: 1044 : if (OidIsValid(targetrelation->rd_rel->reltype))
4397 : 86 : RenameTypeInternal(targetrelation->rd_rel->reltype,
4398 : : newrelname, namespaceId);
4399 : :
4400 : : /*
4401 : : * Also rename the associated constraint, if any.
4402 : : */
4403 [ + + ]: 1044 : if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4404 [ + + ]: 551 : targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
4405 : : {
4406 : 505 : Oid constraintId = get_index_constraint(myrelid);
4407 : :
4408 [ + + ]: 505 : if (OidIsValid(constraintId))
4409 : 24 : RenameConstraintById(constraintId, newrelname);
4410 : : }
4411 : :
4412 : : /*
4413 : : * Close rel, but keep lock!
4414 : : */
4415 : 1044 : relation_close(targetrelation, NoLock);
4416 : 1044 : }
4417 : :
4418 : : /*
4419 : : * ResetRelRewrite - reset relrewrite
4420 : : */
4421 : : void
4422 : 384 : ResetRelRewrite(Oid myrelid)
4423 : : {
4424 : : Relation relrelation; /* for RELATION relation */
4425 : : HeapTuple reltup;
4426 : : Form_pg_class relform;
4427 : :
4428 : : /*
4429 : : * Find relation's pg_class tuple.
4430 : : */
4431 : 384 : relrelation = table_open(RelationRelationId, RowExclusiveLock);
4432 : :
4433 : 384 : reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
4434 [ - + ]: 384 : if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4435 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", myrelid);
4436 : 384 : relform = (Form_pg_class) GETSTRUCT(reltup);
4437 : :
4438 : : /*
4439 : : * Update pg_class tuple.
4440 : : */
4441 : 384 : relform->relrewrite = InvalidOid;
4442 : :
4443 : 384 : CatalogTupleUpdate(relrelation, &reltup->t_self, reltup);
4444 : :
4445 : 384 : heap_freetuple(reltup);
4446 : 384 : table_close(relrelation, RowExclusiveLock);
4447 : 384 : }
4448 : :
4449 : : /*
4450 : : * Disallow ALTER TABLE (and similar commands) when the current backend has
4451 : : * any open reference to the target table besides the one just acquired by
4452 : : * the calling command; this implies there's an open cursor or active plan.
4453 : : * We need this check because our lock doesn't protect us against stomping
4454 : : * on our own foot, only other people's feet!
4455 : : *
4456 : : * For ALTER TABLE, the only case known to cause serious trouble is ALTER
4457 : : * COLUMN TYPE, and some changes are obviously pretty benign, so this could
4458 : : * possibly be relaxed to only error out for certain types of alterations.
4459 : : * But the use-case for allowing any of these things is not obvious, so we
4460 : : * won't work hard at it for now.
4461 : : *
4462 : : * We also reject these commands if there are any pending AFTER trigger events
4463 : : * for the rel. This is certainly necessary for the rewriting variants of
4464 : : * ALTER TABLE, because they don't preserve tuple TIDs and so the pending
4465 : : * events would try to fetch the wrong tuples. It might be overly cautious
4466 : : * in other cases, but again it seems better to err on the side of paranoia.
4467 : : *
4468 : : * REINDEX calls this with "rel" referencing the index to be rebuilt; here
4469 : : * we are worried about active indexscans on the index. The trigger-event
4470 : : * check can be skipped, since we are doing no damage to the parent table.
4471 : : *
4472 : : * The statement name (eg, "ALTER TABLE") is passed for use in error messages.
4473 : : */
4474 : : void
4475 : 111615 : CheckTableNotInUse(Relation rel, const char *stmt)
4476 : : {
4477 : : int expected_refcnt;
4478 : :
4479 [ + + ]: 111615 : expected_refcnt = rel->rd_isnailed ? 2 : 1;
4480 [ + + ]: 111615 : if (rel->rd_refcnt != expected_refcnt)
4481 [ + - ]: 28 : ereport(ERROR,
4482 : : (errcode(ERRCODE_OBJECT_IN_USE),
4483 : : /* translator: first %s is a SQL command, eg ALTER TABLE */
4484 : : errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
4485 : : stmt, RelationGetRelationName(rel))));
4486 : :
4487 [ + + ]: 111587 : if (rel->rd_rel->relkind != RELKIND_INDEX &&
4488 [ + + + + ]: 182512 : rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
4489 : 90546 : AfterTriggerPendingOnRel(RelationGetRelid(rel)))
4490 [ + - ]: 12 : ereport(ERROR,
4491 : : (errcode(ERRCODE_OBJECT_IN_USE),
4492 : : /* translator: first %s is a SQL command, eg ALTER TABLE */
4493 : : errmsg("cannot %s \"%s\" because it has pending trigger events",
4494 : : stmt, RelationGetRelationName(rel))));
4495 : 111575 : }
4496 : :
4497 : : /*
4498 : : * CheckAlterTableIsSafe
4499 : : * Verify that it's safe to allow ALTER TABLE on this relation.
4500 : : *
4501 : : * This consists of CheckTableNotInUse() plus a check that the relation
4502 : : * isn't another session's temp table. We must split out the temp-table
4503 : : * check because there are callers of CheckTableNotInUse() that don't want
4504 : : * that, notably DROP TABLE. (We must allow DROP or we couldn't clean out
4505 : : * an orphaned temp schema.) Compare truncate_check_activity().
4506 : : */
4507 : : static void
4508 : 39441 : CheckAlterTableIsSafe(Relation rel)
4509 : : {
4510 : : /*
4511 : : * Don't allow ALTER on temp tables of other backends. Their local buffer
4512 : : * manager is not going to cope if we need to change the table's contents.
4513 : : * Even if we don't, there may be optimizations that assume temp tables
4514 : : * aren't subject to such interference.
4515 : : */
4516 [ + + + + ]: 39441 : if (RELATION_IS_OTHER_TEMP(rel))
4517 [ + - ]: 2 : ereport(ERROR,
4518 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4519 : : errmsg("cannot alter temporary tables of other sessions")));
4520 : :
4521 : : /*
4522 : : * Also check for active uses of the relation in the current transaction,
4523 : : * including open scans and pending AFTER trigger events.
4524 : : */
4525 : 39439 : CheckTableNotInUse(rel, "ALTER TABLE");
4526 : 39415 : }
4527 : :
4528 : : /*
4529 : : * AlterTableLookupRelation
4530 : : * Look up, and lock, the OID for the relation named by an alter table
4531 : : * statement.
4532 : : */
4533 : : Oid
4534 : 21011 : AlterTableLookupRelation(AlterTableStmt *stmt, LOCKMODE lockmode)
4535 : : {
4536 : 41956 : return RangeVarGetRelidExtended(stmt->relation, lockmode,
4537 : 21011 : stmt->missing_ok ? RVR_MISSING_OK : 0,
4538 : : RangeVarCallbackForAlterRelation,
4539 : : stmt);
4540 : : }
4541 : :
4542 : : /*
4543 : : * AlterTable
4544 : : * Execute ALTER TABLE, which can be a list of subcommands
4545 : : *
4546 : : * ALTER TABLE is performed in three phases:
4547 : : * 1. Examine subcommands and perform pre-transformation checking.
4548 : : * 2. Validate and transform subcommands, and update system catalogs.
4549 : : * 3. Scan table(s) to check new constraints, and optionally recopy
4550 : : * the data into new table(s).
4551 : : * Phase 3 is not performed unless one or more of the subcommands requires
4552 : : * it. The intention of this design is to allow multiple independent
4553 : : * updates of the table schema to be performed with only one pass over the
4554 : : * data.
4555 : : *
4556 : : * ATPrepCmd performs phase 1. A "work queue" entry is created for
4557 : : * each table to be affected (there may be multiple affected tables if the
4558 : : * commands traverse a table inheritance hierarchy). Also we do preliminary
4559 : : * validation of the subcommands. Because earlier subcommands may change
4560 : : * the catalog state seen by later commands, there are limits to what can
4561 : : * be done in this phase. Generally, this phase acquires table locks,
4562 : : * checks permissions and relkind, and recurses to find child tables.
4563 : : *
4564 : : * ATRewriteCatalogs performs phase 2 for each affected table.
4565 : : * Certain subcommands need to be performed before others to avoid
4566 : : * unnecessary conflicts; for example, DROP COLUMN should come before
4567 : : * ADD COLUMN. Therefore phase 1 divides the subcommands into multiple
4568 : : * lists, one for each logical "pass" of phase 2.
4569 : : *
4570 : : * ATRewriteTables performs phase 3 for those tables that need it.
4571 : : *
4572 : : * For most subcommand types, phases 2 and 3 do no explicit recursion,
4573 : : * since phase 1 already does it. However, for certain subcommand types
4574 : : * it is only possible to determine how to recurse at phase 2 time; for
4575 : : * those cases, phase 1 sets the cmd->recurse flag.
4576 : : *
4577 : : * Thanks to the magic of MVCC, an error anywhere along the way rolls back
4578 : : * the whole operation; we don't have to do anything special to clean up.
4579 : : *
4580 : : * The caller must lock the relation, with an appropriate lock level
4581 : : * for the subcommands requested, using AlterTableGetLockLevel(stmt->cmds)
4582 : : * or higher. We pass the lock level down
4583 : : * so that we can apply it recursively to inherited tables. Note that the
4584 : : * lock level we want as we recurse might well be higher than required for
4585 : : * that specific subcommand. So we pass down the overall lock requirement,
4586 : : * rather than reassess it at lower levels.
4587 : : *
4588 : : * The caller also provides a "context" which is to be passed back to
4589 : : * utility.c when we need to execute a subcommand such as CREATE INDEX.
4590 : : * Some of the fields therein, such as the relid, are used here as well.
4591 : : */
4592 : : void
4593 : 20837 : AlterTable(AlterTableStmt *stmt, LOCKMODE lockmode,
4594 : : AlterTableUtilityContext *context)
4595 : : {
4596 : : Relation rel;
4597 : :
4598 : : /* Caller is required to provide an adequate lock. */
4599 : 20837 : rel = relation_open(context->relid, NoLock);
4600 : :
4601 : 20837 : CheckAlterTableIsSafe(rel);
4602 : :
4603 : 20823 : ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4604 : 18099 : }
4605 : :
4606 : : /*
4607 : : * AlterTableInternal
4608 : : *
4609 : : * ALTER TABLE with target specified by OID
4610 : : *
4611 : : * We do not reject if the relation is already open, because it's quite
4612 : : * likely that one or more layers of caller have it open. That means it
4613 : : * is unsafe to use this entry point for alterations that could break
4614 : : * existing query plans. On the assumption it's not used for such, we
4615 : : * don't have to reject pending AFTER triggers, either.
4616 : : *
4617 : : * Also, since we don't have an AlterTableUtilityContext, this cannot be
4618 : : * used for any subcommand types that require parse transformation or
4619 : : * could generate subcommands that have to be passed to ProcessUtility.
4620 : : */
4621 : : void
4622 : 193 : AlterTableInternal(Oid relid, List *cmds, bool recurse)
4623 : : {
4624 : : Relation rel;
4625 : 193 : LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4626 : :
4627 : 193 : rel = relation_open(relid, lockmode);
4628 : :
4629 : 193 : EventTriggerAlterTableRelid(relid);
4630 : :
4631 : 193 : ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4632 : 193 : }
4633 : :
4634 : : /*
4635 : : * AlterTableGetLockLevel
4636 : : *
4637 : : * Sets the overall lock level required for the supplied list of subcommands.
4638 : : * Policy for doing this set according to needs of AlterTable(), see
4639 : : * comments there for overall explanation.
4640 : : *
4641 : : * Function is called before and after parsing, so it must give same
4642 : : * answer each time it is called. Some subcommands are transformed
4643 : : * into other subcommand types, so the transform must never be made to a
4644 : : * lower lock level than previously assigned. All transforms are noted below.
4645 : : *
4646 : : * Since this is called before we lock the table we cannot use table metadata
4647 : : * to influence the type of lock we acquire.
4648 : : *
4649 : : * There should be no lockmodes hardcoded into the subcommand functions. All
4650 : : * lockmode decisions for ALTER TABLE are made here only. The one exception is
4651 : : * ALTER TABLE RENAME which is treated as a different statement type T_RenameStmt
4652 : : * and does not travel through this section of code and cannot be combined with
4653 : : * any of the subcommands given here.
4654 : : *
4655 : : * Note that Hot Standby only knows about AccessExclusiveLocks on the primary
4656 : : * so any changes that might affect SELECTs running on standbys need to use
4657 : : * AccessExclusiveLocks even if you think a lesser lock would do, unless you
4658 : : * have a solution for that also.
4659 : : *
4660 : : * Also note that pg_dump uses only an AccessShareLock, meaning that anything
4661 : : * that takes a lock less than AccessExclusiveLock can change object definitions
4662 : : * while pg_dump is running. Be careful to check that the appropriate data is
4663 : : * derived by pg_dump using an MVCC snapshot, rather than syscache lookups,
4664 : : * otherwise we might end up with an inconsistent dump that can't restore.
4665 : : */
4666 : : LOCKMODE
4667 : 21204 : AlterTableGetLockLevel(List *cmds)
4668 : : {
4669 : : /*
4670 : : * This only works if we read catalog tables using MVCC snapshots.
4671 : : */
4672 : : ListCell *lcmd;
4673 : 21204 : LOCKMODE lockmode = ShareUpdateExclusiveLock;
4674 : :
4675 [ + - + + : 43229 : foreach(lcmd, cmds)
+ + ]
4676 : : {
4677 : 22025 : AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4678 : 22025 : LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
4679 : :
4680 [ + + + + : 22025 : switch (cmd->subtype)
+ + + + +
+ + + + +
+ + + + +
- ]
4681 : : {
4682 : : /*
4683 : : * These subcommands rewrite the heap, so require full locks.
4684 : : */
4685 : 2622 : case AT_AddColumn: /* may rewrite heap, in some cases and visible
4686 : : * to SELECT */
4687 : : case AT_SetAccessMethod: /* must rewrite heap */
4688 : : case AT_SetTableSpace: /* must rewrite heap */
4689 : : case AT_AlterColumnType: /* must rewrite heap */
4690 : 2622 : cmd_lockmode = AccessExclusiveLock;
4691 : 2622 : break;
4692 : :
4693 : : /*
4694 : : * These subcommands may require addition of toast tables. If
4695 : : * we add a toast table to a table currently being scanned, we
4696 : : * might miss data added to the new toast table by concurrent
4697 : : * insert transactions.
4698 : : */
4699 : 219 : case AT_SetStorage: /* may add toast tables, see
4700 : : * ATRewriteCatalogs() */
4701 : 219 : cmd_lockmode = AccessExclusiveLock;
4702 : 219 : break;
4703 : :
4704 : : /*
4705 : : * Removing constraints can affect SELECTs that have been
4706 : : * optimized assuming the constraint holds true. See also
4707 : : * CloneFkReferenced.
4708 : : */
4709 : 765 : case AT_DropConstraint: /* as DROP INDEX */
4710 : : case AT_DropNotNull: /* may change some SQL plans */
4711 : 765 : cmd_lockmode = AccessExclusiveLock;
4712 : 765 : break;
4713 : :
4714 : : /*
4715 : : * Subcommands that may be visible to concurrent SELECTs
4716 : : */
4717 : 1172 : case AT_DropColumn: /* change visible to SELECT */
4718 : : case AT_AddColumnToView: /* CREATE VIEW */
4719 : : case AT_DropOids: /* used to equiv to DropColumn */
4720 : : case AT_EnableAlwaysRule: /* may change SELECT rules */
4721 : : case AT_EnableReplicaRule: /* may change SELECT rules */
4722 : : case AT_EnableRule: /* may change SELECT rules */
4723 : : case AT_DisableRule: /* may change SELECT rules */
4724 : 1172 : cmd_lockmode = AccessExclusiveLock;
4725 : 1172 : break;
4726 : :
4727 : : /*
4728 : : * Changing owner may remove implicit SELECT privileges
4729 : : */
4730 : 1135 : case AT_ChangeOwner: /* change visible to SELECT */
4731 : 1135 : cmd_lockmode = AccessExclusiveLock;
4732 : 1135 : break;
4733 : :
4734 : : /*
4735 : : * Changing foreign table options may affect optimization.
4736 : : */
4737 : 144 : case AT_GenericOptions:
4738 : : case AT_AlterColumnGenericOptions:
4739 : 144 : cmd_lockmode = AccessExclusiveLock;
4740 : 144 : break;
4741 : :
4742 : : /*
4743 : : * These subcommands affect write operations only.
4744 : : */
4745 : 191 : case AT_EnableTrig:
4746 : : case AT_EnableAlwaysTrig:
4747 : : case AT_EnableReplicaTrig:
4748 : : case AT_EnableTrigAll:
4749 : : case AT_EnableTrigUser:
4750 : : case AT_DisableTrig:
4751 : : case AT_DisableTrigAll:
4752 : : case AT_DisableTrigUser:
4753 : 191 : cmd_lockmode = ShareRowExclusiveLock;
4754 : 191 : break;
4755 : :
4756 : : /*
4757 : : * These subcommands affect write operations only. XXX
4758 : : * Theoretically, these could be ShareRowExclusiveLock.
4759 : : */
4760 : 2152 : case AT_ColumnDefault:
4761 : : case AT_CookedColumnDefault:
4762 : : case AT_AlterConstraint:
4763 : : case AT_AddIndex: /* from ADD CONSTRAINT */
4764 : : case AT_AddIndexConstraint:
4765 : : case AT_ReplicaIdentity:
4766 : : case AT_SetNotNull:
4767 : : case AT_EnableRowSecurity:
4768 : : case AT_DisableRowSecurity:
4769 : : case AT_ForceRowSecurity:
4770 : : case AT_NoForceRowSecurity:
4771 : : case AT_AddIdentity:
4772 : : case AT_DropIdentity:
4773 : : case AT_SetIdentity:
4774 : : case AT_SetExpression:
4775 : : case AT_DropExpression:
4776 : : case AT_SetCompression:
4777 : 2152 : cmd_lockmode = AccessExclusiveLock;
4778 : 2152 : break;
4779 : :
4780 : 9763 : case AT_AddConstraint:
4781 : : case AT_ReAddConstraint: /* becomes AT_AddConstraint */
4782 : : case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
4783 [ + - ]: 9763 : if (IsA(cmd->def, Constraint))
4784 : : {
4785 : 9763 : Constraint *con = (Constraint *) cmd->def;
4786 : :
4787 [ + + + ]: 9763 : switch (con->contype)
4788 : : {
4789 : 7156 : case CONSTR_EXCLUSION:
4790 : : case CONSTR_PRIMARY:
4791 : : case CONSTR_UNIQUE:
4792 : :
4793 : : /*
4794 : : * Cases essentially the same as CREATE INDEX. We
4795 : : * could reduce the lock strength to ShareLock if
4796 : : * we can work out how to allow concurrent catalog
4797 : : * updates. XXX Might be set down to
4798 : : * ShareRowExclusiveLock but requires further
4799 : : * analysis.
4800 : : */
4801 : 7156 : cmd_lockmode = AccessExclusiveLock;
4802 : 7156 : break;
4803 : 1840 : case CONSTR_FOREIGN:
4804 : :
4805 : : /*
4806 : : * We add triggers to both tables when we add a
4807 : : * Foreign Key, so the lock level must be at least
4808 : : * as strong as CREATE TRIGGER.
4809 : : */
4810 : 1840 : cmd_lockmode = ShareRowExclusiveLock;
4811 : 1840 : break;
4812 : :
4813 : 767 : default:
4814 : 767 : cmd_lockmode = AccessExclusiveLock;
4815 : : }
4816 : : }
4817 : 9763 : break;
4818 : :
4819 : : /*
4820 : : * These subcommands affect inheritance behaviour. Queries
4821 : : * started before us will continue to see the old inheritance
4822 : : * behaviour, while queries started after we commit will see
4823 : : * new behaviour. No need to prevent reads or writes to the
4824 : : * subtable while we hook it up though. Changing the TupDesc
4825 : : * may be a problem, so keep highest lock.
4826 : : */
4827 : 374 : case AT_AddInherit:
4828 : : case AT_DropInherit:
4829 : 374 : cmd_lockmode = AccessExclusiveLock;
4830 : 374 : break;
4831 : :
4832 : : /*
4833 : : * These subcommands affect implicit row type conversion. They
4834 : : * have affects similar to CREATE/DROP CAST on queries. don't
4835 : : * provide for invalidating parse trees as a result of such
4836 : : * changes, so we keep these at AccessExclusiveLock.
4837 : : */
4838 : 54 : case AT_AddOf:
4839 : : case AT_DropOf:
4840 : 54 : cmd_lockmode = AccessExclusiveLock;
4841 : 54 : break;
4842 : :
4843 : : /*
4844 : : * Only used by CREATE OR REPLACE VIEW which must conflict
4845 : : * with an SELECTs currently using the view.
4846 : : */
4847 : 137 : case AT_ReplaceRelOptions:
4848 : 137 : cmd_lockmode = AccessExclusiveLock;
4849 : 137 : break;
4850 : :
4851 : : /*
4852 : : * These subcommands affect general strategies for performance
4853 : : * and maintenance, though don't change the semantic results
4854 : : * from normal data reads and writes. Delaying an ALTER TABLE
4855 : : * behind currently active writes only delays the point where
4856 : : * the new strategy begins to take effect, so there is no
4857 : : * benefit in waiting. In this case the minimum restriction
4858 : : * applies: we don't currently allow concurrent catalog
4859 : : * updates.
4860 : : */
4861 : 158 : case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
4862 : : case AT_ClusterOn: /* Uses MVCC in getIndexes() */
4863 : : case AT_DropCluster: /* Uses MVCC in getIndexes() */
4864 : : case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
4865 : : case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
4866 : 158 : cmd_lockmode = ShareUpdateExclusiveLock;
4867 : 158 : break;
4868 : :
4869 : 79 : case AT_SetLogged:
4870 : : case AT_SetUnLogged:
4871 : 79 : cmd_lockmode = AccessExclusiveLock;
4872 : 79 : break;
4873 : :
4874 : 288 : case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
4875 : 288 : cmd_lockmode = ShareUpdateExclusiveLock;
4876 : 288 : break;
4877 : :
4878 : : /*
4879 : : * Rel options are more complex than first appears. Options
4880 : : * are set here for tables, views and indexes; for historical
4881 : : * reasons these can all be used with ALTER TABLE, so we can't
4882 : : * decide between them using the basic grammar.
4883 : : */
4884 : 540 : case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
4885 : : * getTables() */
4886 : : case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
4887 : : * getTables() */
4888 : 540 : cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
4889 : 540 : break;
4890 : :
4891 : 1847 : case AT_AttachPartition:
4892 : 1847 : cmd_lockmode = ShareUpdateExclusiveLock;
4893 : 1847 : break;
4894 : :
4895 : 374 : case AT_DetachPartition:
4896 [ + + ]: 374 : if (((PartitionCmd *) cmd->def)->concurrent)
4897 : 88 : cmd_lockmode = ShareUpdateExclusiveLock;
4898 : : else
4899 : 286 : cmd_lockmode = AccessExclusiveLock;
4900 : 374 : break;
4901 : :
4902 : 11 : case AT_DetachPartitionFinalize:
4903 : 11 : cmd_lockmode = ShareUpdateExclusiveLock;
4904 : 11 : break;
4905 : :
4906 : 0 : default: /* oops */
4907 [ # # ]: 0 : elog(ERROR, "unrecognized alter table type: %d",
4908 : : (int) cmd->subtype);
4909 : : break;
4910 : : }
4911 : :
4912 : : /*
4913 : : * Take the greatest lockmode from any subcommand
4914 : : */
4915 [ + + ]: 22025 : if (cmd_lockmode > lockmode)
4916 : 18390 : lockmode = cmd_lockmode;
4917 : : }
4918 : :
4919 : 21204 : return lockmode;
4920 : : }
4921 : :
4922 : : /*
4923 : : * ATController provides top level control over the phases.
4924 : : *
4925 : : * parsetree is passed in to allow it to be passed to event triggers
4926 : : * when requested.
4927 : : */
4928 : : static void
4929 : 21016 : ATController(AlterTableStmt *parsetree,
4930 : : Relation rel, List *cmds, bool recurse, LOCKMODE lockmode,
4931 : : AlterTableUtilityContext *context)
4932 : : {
4933 : 21016 : List *wqueue = NIL;
4934 : : ListCell *lcmd;
4935 : :
4936 : : /* Phase 1: preliminary examination of commands, create work queue */
4937 [ + - + + : 42544 : foreach(lcmd, cmds)
+ + ]
4938 : : {
4939 : 21833 : AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4940 : :
4941 : 21833 : ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode, context);
4942 : : }
4943 : :
4944 : : /* Close the relation, but keep lock until commit */
4945 : 20711 : relation_close(rel, NoLock);
4946 : :
4947 : : /* Phase 2: update system catalogs */
4948 : 20711 : ATRewriteCatalogs(&wqueue, lockmode, context);
4949 : :
4950 : : /* Phase 3: scan/rewrite tables as needed, and run afterStmts */
4951 : 18713 : ATRewriteTables(parsetree, &wqueue, lockmode, context);
4952 : 18292 : }
4953 : :
4954 : : /*
4955 : : * ATPrepCmd
4956 : : *
4957 : : * Traffic cop for ALTER TABLE Phase 1 operations, including simple
4958 : : * recursion and permission checks.
4959 : : *
4960 : : * Caller must have acquired appropriate lock type on relation already.
4961 : : * This lock should be held until commit.
4962 : : */
4963 : : static void
4964 : 22472 : ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
4965 : : bool recurse, bool recursing, LOCKMODE lockmode,
4966 : : AlterTableUtilityContext *context)
4967 : : {
4968 : : AlteredTableInfo *tab;
4969 : 22472 : AlterTablePass pass = AT_PASS_UNSET;
4970 : :
4971 : : /* Find or create work queue entry for this table */
4972 : 22472 : tab = ATGetQueueEntry(wqueue, rel);
4973 : :
4974 : : /*
4975 : : * Disallow any ALTER TABLE other than ALTER TABLE DETACH FINALIZE on
4976 : : * partitions that are pending detach.
4977 : : */
4978 [ + + ]: 22472 : if (rel->rd_rel->relispartition &&
4979 [ + - + + ]: 1834 : cmd->subtype != AT_DetachPartitionFinalize &&
4980 : 917 : PartitionHasPendingDetach(RelationGetRelid(rel)))
4981 [ + - ]: 1 : ereport(ERROR,
4982 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4983 : : errmsg("cannot alter partition \"%s\" with an incomplete detach",
4984 : : RelationGetRelationName(rel)),
4985 : : errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."));
4986 : :
4987 : : /*
4988 : : * Copy the original subcommand for each table, so we can scribble on it.
4989 : : * This avoids conflicts when different child tables need to make
4990 : : * different parse transformations (for example, the same column may have
4991 : : * different column numbers in different children).
4992 : : */
4993 : 22471 : cmd = copyObject(cmd);
4994 : :
4995 : : /*
4996 : : * Do permissions and relkind checking, recursion to child tables if
4997 : : * needed, and any additional phase-1 processing needed. (But beware of
4998 : : * adding any processing that looks at table details that another
4999 : : * subcommand could change. In some cases we reject multiple subcommands
5000 : : * that could try to change the same state in contrary ways.)
5001 : : */
5002 [ + + + + : 22471 : switch (cmd->subtype)
+ + + + +
+ + + + +
+ + - + -
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ - ]
5003 : : {
5004 : 1570 : case AT_AddColumn: /* ADD COLUMN */
5005 : 1570 : ATSimplePermissions(cmd->subtype, rel,
5006 : : ATT_TABLE | ATT_PARTITIONED_TABLE |
5007 : : ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
5008 : 1570 : ATPrepAddColumn(wqueue, rel, recurse, recursing, false, cmd,
5009 : : lockmode, context);
5010 : : /* Recursion occurs during execution phase */
5011 : 1562 : pass = AT_PASS_ADD_COL;
5012 : 1562 : break;
5013 : 21 : case AT_AddColumnToView: /* add column via CREATE OR REPLACE VIEW */
5014 : 21 : ATSimplePermissions(cmd->subtype, rel, ATT_VIEW);
5015 : 21 : ATPrepAddColumn(wqueue, rel, recurse, recursing, true, cmd,
5016 : : lockmode, context);
5017 : : /* Recursion occurs during execution phase */
5018 : 21 : pass = AT_PASS_ADD_COL;
5019 : 21 : break;
5020 : 411 : case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
5021 : :
5022 : : /*
5023 : : * We allow defaults on views so that INSERT into a view can have
5024 : : * default-ish behavior. This works because the rewriter
5025 : : * substitutes default values into INSERTs before it expands
5026 : : * rules.
5027 : : */
5028 : 411 : ATSimplePermissions(cmd->subtype, rel,
5029 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5030 : : ATT_FOREIGN_TABLE);
5031 : 411 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5032 : : /* No command-specific prep needed */
5033 [ + + ]: 411 : pass = cmd->def ? AT_PASS_ADD_OTHERCONSTR : AT_PASS_DROP;
5034 : 411 : break;
5035 : 57 : case AT_CookedColumnDefault: /* add a pre-cooked default */
5036 : : /* This is currently used only in CREATE TABLE */
5037 : : /* (so the permission check really isn't necessary) */
5038 : 57 : ATSimplePermissions(cmd->subtype, rel,
5039 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5040 : : /* This command never recurses */
5041 : 57 : pass = AT_PASS_ADD_OTHERCONSTR;
5042 : 57 : break;
5043 : 107 : case AT_AddIdentity:
5044 : 107 : ATSimplePermissions(cmd->subtype, rel,
5045 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5046 : : ATT_FOREIGN_TABLE);
5047 : : /* Set up recursion for phase 2; no other prep needed */
5048 [ + + ]: 107 : if (recurse)
5049 : 103 : cmd->recurse = true;
5050 : 107 : pass = AT_PASS_ADD_OTHERCONSTR;
5051 : 107 : break;
5052 : 41 : case AT_SetIdentity:
5053 : 41 : ATSimplePermissions(cmd->subtype, rel,
5054 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5055 : : ATT_FOREIGN_TABLE);
5056 : : /* Set up recursion for phase 2; no other prep needed */
5057 [ + + ]: 41 : if (recurse)
5058 : 37 : cmd->recurse = true;
5059 : : /* This should run after AddIdentity, so do it in MISC pass */
5060 : 41 : pass = AT_PASS_MISC;
5061 : 41 : break;
5062 : 37 : case AT_DropIdentity:
5063 : 37 : ATSimplePermissions(cmd->subtype, rel,
5064 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5065 : : ATT_FOREIGN_TABLE);
5066 : : /* Set up recursion for phase 2; no other prep needed */
5067 [ + + ]: 37 : if (recurse)
5068 : 33 : cmd->recurse = true;
5069 : 37 : pass = AT_PASS_DROP;
5070 : 37 : break;
5071 : 181 : case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
5072 : 181 : ATSimplePermissions(cmd->subtype, rel,
5073 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5074 : : /* Set up recursion for phase 2; no other prep needed */
5075 [ + + ]: 177 : if (recurse)
5076 : 165 : cmd->recurse = true;
5077 : 177 : pass = AT_PASS_DROP;
5078 : 177 : break;
5079 : 276 : case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
5080 : 276 : ATSimplePermissions(cmd->subtype, rel,
5081 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5082 : : /* Set up recursion for phase 2; no other prep needed */
5083 [ + + ]: 272 : if (recurse)
5084 : 252 : cmd->recurse = true;
5085 : 272 : pass = AT_PASS_COL_ATTRS;
5086 : 272 : break;
5087 : 193 : case AT_SetExpression: /* ALTER COLUMN SET EXPRESSION */
5088 : 193 : ATSimplePermissions(cmd->subtype, rel,
5089 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5090 : 193 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5091 : 193 : pass = AT_PASS_SET_EXPRESSION;
5092 : 193 : break;
5093 : 93 : case AT_DropExpression: /* ALTER COLUMN DROP EXPRESSION */
5094 : 93 : ATSimplePermissions(cmd->subtype, rel,
5095 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5096 : 93 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5097 : 93 : ATPrepDropExpression(rel, cmd, recurse, recursing, lockmode);
5098 : 69 : pass = AT_PASS_DROP;
5099 : 69 : break;
5100 : 111 : case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
5101 : 111 : ATSimplePermissions(cmd->subtype, rel,
5102 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW |
5103 : : ATT_INDEX | ATT_PARTITIONED_INDEX | ATT_FOREIGN_TABLE);
5104 : 111 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5105 : : /* No command-specific prep needed */
5106 : 111 : pass = AT_PASS_MISC;
5107 : 111 : break;
5108 : 29 : case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
5109 : : case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
5110 : 29 : ATSimplePermissions(cmd->subtype, rel,
5111 : : ATT_TABLE | ATT_PARTITIONED_TABLE |
5112 : : ATT_MATVIEW | ATT_FOREIGN_TABLE);
5113 : : /* This command never recurses */
5114 : 21 : pass = AT_PASS_MISC;
5115 : 21 : break;
5116 : 233 : case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
5117 : 233 : ATSimplePermissions(cmd->subtype, rel,
5118 : : ATT_TABLE | ATT_PARTITIONED_TABLE |
5119 : : ATT_MATVIEW | ATT_FOREIGN_TABLE);
5120 : 233 : ATSimpleRecursion(wqueue, rel, cmd, recurse, lockmode, context);
5121 : : /* No command-specific prep needed */
5122 : 233 : pass = AT_PASS_MISC;
5123 : 233 : break;
5124 : 48 : case AT_SetCompression: /* ALTER COLUMN SET COMPRESSION */
5125 : 48 : ATSimplePermissions(cmd->subtype, rel,
5126 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5127 : : /* This command never recurses */
5128 : : /* No command-specific prep needed */
5129 : 48 : pass = AT_PASS_MISC;
5130 : 48 : break;
5131 : 1098 : case AT_DropColumn: /* DROP COLUMN */
5132 : 1098 : ATSimplePermissions(cmd->subtype, rel,
5133 : : ATT_TABLE | ATT_PARTITIONED_TABLE |
5134 : : ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
5135 : 1094 : ATPrepDropColumn(wqueue, rel, recurse, recursing, cmd,
5136 : : lockmode, context);
5137 : : /* Recursion occurs during execution phase */
5138 : 1086 : pass = AT_PASS_DROP;
5139 : 1086 : break;
5140 : 0 : case AT_AddIndex: /* ADD INDEX */
5141 : 0 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE);
5142 : : /* This command never recurses */
5143 : : /* No command-specific prep needed */
5144 : 0 : pass = AT_PASS_ADD_INDEX;
5145 : 0 : break;
5146 : 10060 : case AT_AddConstraint: /* ADD CONSTRAINT */
5147 : 10060 : ATSimplePermissions(cmd->subtype, rel,
5148 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5149 : 10060 : ATPrepAddPrimaryKey(wqueue, rel, cmd, recurse, lockmode, context);
5150 [ + + ]: 10040 : if (recurse)
5151 : : {
5152 : : /* recurses at exec time; lock descendants and set flag */
5153 : 9827 : (void) find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
5154 : 9827 : cmd->recurse = true;
5155 : : }
5156 : 10040 : pass = AT_PASS_ADD_CONSTR;
5157 : 10040 : break;
5158 : 0 : case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
5159 : 0 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE);
5160 : : /* This command never recurses */
5161 : : /* No command-specific prep needed */
5162 : 0 : pass = AT_PASS_ADD_INDEXCONSTR;
5163 : 0 : break;
5164 : 559 : case AT_DropConstraint: /* DROP CONSTRAINT */
5165 : 559 : ATSimplePermissions(cmd->subtype, rel,
5166 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5167 : 559 : ATCheckPartitionsNotInUse(rel, lockmode);
5168 : : /* Other recursion occurs during execution phase */
5169 : : /* No command-specific prep needed except saving recurse flag */
5170 [ + + ]: 555 : if (recurse)
5171 : 531 : cmd->recurse = true;
5172 : 555 : pass = AT_PASS_DROP;
5173 : 555 : break;
5174 : 963 : case AT_AlterColumnType: /* ALTER COLUMN TYPE */
5175 : 963 : ATSimplePermissions(cmd->subtype, rel,
5176 : : ATT_TABLE | ATT_PARTITIONED_TABLE |
5177 : : ATT_COMPOSITE_TYPE | ATT_FOREIGN_TABLE);
5178 : : /* See comments for ATPrepAlterColumnType */
5179 : 963 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, recurse, lockmode,
5180 : : AT_PASS_UNSET, context);
5181 : : Assert(cmd != NULL);
5182 : : /* Performs own recursion */
5183 : 959 : ATPrepAlterColumnType(wqueue, tab, rel, recurse, recursing, cmd,
5184 : : lockmode, context);
5185 : 828 : pass = AT_PASS_ALTER_TYPE;
5186 : 828 : break;
5187 : 94 : case AT_AlterColumnGenericOptions:
5188 : 94 : ATSimplePermissions(cmd->subtype, rel, ATT_FOREIGN_TABLE);
5189 : : /* This command never recurses */
5190 : : /* No command-specific prep needed */
5191 : 94 : pass = AT_PASS_MISC;
5192 : 94 : break;
5193 : 1115 : case AT_ChangeOwner: /* ALTER OWNER */
5194 : : /* This command never recurses */
5195 : : /* No command-specific prep needed */
5196 : 1115 : pass = AT_PASS_MISC;
5197 : 1115 : break;
5198 : 43 : case AT_ClusterOn: /* CLUSTER ON */
5199 : : case AT_DropCluster: /* SET WITHOUT CLUSTER */
5200 : 43 : ATSimplePermissions(cmd->subtype, rel,
5201 : : ATT_TABLE | ATT_MATVIEW);
5202 : : /* These commands never recurse */
5203 : : /* No command-specific prep needed */
5204 : 35 : pass = AT_PASS_MISC;
5205 : 35 : break;
5206 : 79 : case AT_SetLogged: /* SET LOGGED */
5207 : : case AT_SetUnLogged: /* SET UNLOGGED */
5208 : 79 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_SEQUENCE);
5209 [ - + ]: 71 : if (tab->chgPersistence)
5210 [ # # ]: 0 : ereport(ERROR,
5211 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5212 : : errmsg("cannot change persistence setting twice")));
5213 : 71 : ATPrepChangePersistence(tab, rel, cmd->subtype == AT_SetLogged);
5214 : 59 : pass = AT_PASS_MISC;
5215 : 59 : break;
5216 : 4 : case AT_DropOids: /* SET WITHOUT OIDS */
5217 : 4 : ATSimplePermissions(cmd->subtype, rel,
5218 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5219 : 4 : pass = AT_PASS_DROP;
5220 : 4 : break;
5221 : 85 : case AT_SetAccessMethod: /* SET ACCESS METHOD */
5222 : 85 : ATSimplePermissions(cmd->subtype, rel,
5223 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5224 : :
5225 : : /* check if another access method change was already requested */
5226 [ + + ]: 85 : if (tab->chgAccessMethod)
5227 [ + - ]: 12 : ereport(ERROR,
5228 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5229 : : errmsg("cannot have multiple SET ACCESS METHOD subcommands")));
5230 : :
5231 : 73 : ATPrepSetAccessMethod(tab, rel, cmd->name);
5232 : 73 : pass = AT_PASS_MISC; /* does not matter; no work in Phase 2 */
5233 : 73 : break;
5234 : 104 : case AT_SetTableSpace: /* SET TABLESPACE */
5235 : 104 : ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_PARTITIONED_TABLE |
5236 : : ATT_MATVIEW | ATT_INDEX | ATT_PARTITIONED_INDEX);
5237 : : /* This command never recurses */
5238 : 104 : ATPrepSetTableSpace(tab, rel, cmd->name, lockmode);
5239 : 104 : pass = AT_PASS_MISC; /* doesn't actually matter */
5240 : 104 : break;
5241 : 675 : case AT_SetRelOptions: /* SET (...) */
5242 : : case AT_ResetRelOptions: /* RESET (...) */
5243 : : case AT_ReplaceRelOptions: /* reset them all, then set just these */
5244 : 675 : ATSimplePermissions(cmd->subtype, rel,
5245 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_VIEW |
5246 : : ATT_MATVIEW | ATT_INDEX);
5247 : : /* This command never recurses */
5248 : : /* No command-specific prep needed */
5249 : 674 : pass = AT_PASS_MISC;
5250 : 674 : break;
5251 : 301 : case AT_AddInherit: /* INHERIT */
5252 : 301 : ATSimplePermissions(cmd->subtype, rel,
5253 : : ATT_TABLE | ATT_FOREIGN_TABLE);
5254 : : /* This command never recurses */
5255 : 297 : ATPrepChangeInherit(rel);
5256 : 285 : pass = AT_PASS_MISC;
5257 : 285 : break;
5258 : 73 : case AT_DropInherit: /* NO INHERIT */
5259 : 73 : ATSimplePermissions(cmd->subtype, rel,
5260 : : ATT_TABLE | ATT_FOREIGN_TABLE);
5261 : : /* This command never recurses */
5262 : 69 : ATPrepChangeInherit(rel);
5263 : 61 : pass = AT_PASS_MISC;
5264 : 61 : break;
5265 : 336 : case AT_AlterConstraint: /* ALTER CONSTRAINT */
5266 : 336 : ATSimplePermissions(cmd->subtype, rel,
5267 : : ATT_TABLE | ATT_PARTITIONED_TABLE);
5268 : : /* Recursion occurs during execution phase */
5269 [ + + ]: 332 : if (recurse)
5270 : 320 : cmd->recurse = true;
5271 : 332 : pass = AT_PASS_MISC;
5272 : 332 : break;
5273 : 288 : case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
5274 : 288 : ATSimplePermissions(cmd->subtype, rel,
5275 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5276 : : /* Recursion occurs during execution phase */
5277 : : /* No command-specific prep needed except saving recurse flag */
5278 [ + - ]: 288 : if (recurse)
5279 : 288 : cmd->recurse = true;
5280 : 288 : pass = AT_PASS_MISC;
5281 : 288 : break;
5282 : 317 : case AT_ReplicaIdentity: /* REPLICA IDENTITY ... */
5283 : 317 : ATSimplePermissions(cmd->subtype, rel,
5284 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_MATVIEW);
5285 : 317 : pass = AT_PASS_MISC;
5286 : : /* This command never recurses */
5287 : : /* No command-specific prep needed */
5288 : 317 : break;
5289 : 191 : case AT_EnableTrig: /* ENABLE TRIGGER variants */
5290 : : case AT_EnableAlwaysTrig:
5291 : : case AT_EnableReplicaTrig:
5292 : : case AT_EnableTrigAll:
5293 : : case AT_EnableTrigUser:
5294 : : case AT_DisableTrig: /* DISABLE TRIGGER variants */
5295 : : case AT_DisableTrigAll:
5296 : : case AT_DisableTrigUser:
5297 : 191 : ATSimplePermissions(cmd->subtype, rel,
5298 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
5299 : : /* Set up recursion for phase 2; no other prep needed */
5300 [ + + ]: 191 : if (recurse)
5301 : 174 : cmd->recurse = true;
5302 : 191 : pass = AT_PASS_MISC;
5303 : 191 : break;
5304 : 420 : case AT_EnableRule: /* ENABLE/DISABLE RULE variants */
5305 : : case AT_EnableAlwaysRule:
5306 : : case AT_EnableReplicaRule:
5307 : : case AT_DisableRule:
5308 : : case AT_AddOf: /* OF */
5309 : : case AT_DropOf: /* NOT OF */
5310 : : case AT_EnableRowSecurity:
5311 : : case AT_DisableRowSecurity:
5312 : : case AT_ForceRowSecurity:
5313 : : case AT_NoForceRowSecurity:
5314 : 420 : ATSimplePermissions(cmd->subtype, rel,
5315 : : ATT_TABLE | ATT_PARTITIONED_TABLE);
5316 : : /* These commands never recurse */
5317 : : /* No command-specific prep needed */
5318 : 420 : pass = AT_PASS_MISC;
5319 : 420 : break;
5320 : 34 : case AT_GenericOptions:
5321 : 34 : ATSimplePermissions(cmd->subtype, rel, ATT_FOREIGN_TABLE);
5322 : : /* No command-specific prep needed */
5323 : 34 : pass = AT_PASS_MISC;
5324 : 34 : break;
5325 : 1839 : case AT_AttachPartition:
5326 : 1839 : ATSimplePermissions(cmd->subtype, rel,
5327 : : ATT_PARTITIONED_TABLE | ATT_PARTITIONED_INDEX);
5328 : : /* No command-specific prep needed */
5329 : 1835 : pass = AT_PASS_MISC;
5330 : 1835 : break;
5331 : 374 : case AT_DetachPartition:
5332 : 374 : ATSimplePermissions(cmd->subtype, rel, ATT_PARTITIONED_TABLE);
5333 : : /* No command-specific prep needed */
5334 : 362 : pass = AT_PASS_MISC;
5335 : 362 : break;
5336 : 11 : case AT_DetachPartitionFinalize:
5337 : 11 : ATSimplePermissions(cmd->subtype, rel, ATT_PARTITIONED_TABLE);
5338 : : /* No command-specific prep needed */
5339 : 7 : pass = AT_PASS_MISC;
5340 : 7 : break;
5341 : 0 : default: /* oops */
5342 [ # # ]: 0 : elog(ERROR, "unrecognized alter table type: %d",
5343 : : (int) cmd->subtype);
5344 : : pass = AT_PASS_UNSET; /* keep compiler quiet */
5345 : : break;
5346 : : }
5347 : : Assert(pass > AT_PASS_UNSET);
5348 : :
5349 : : /* Add the subcommand to the appropriate list for phase 2 */
5350 : 22159 : tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd);
5351 : 22159 : }
5352 : :
5353 : : /*
5354 : : * ATRewriteCatalogs
5355 : : *
5356 : : * Traffic cop for ALTER TABLE Phase 2 operations. Subcommands are
5357 : : * dispatched in a "safe" execution order (designed to avoid unnecessary
5358 : : * conflicts).
5359 : : */
5360 : : static void
5361 : 20711 : ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode,
5362 : : AlterTableUtilityContext *context)
5363 : : {
5364 : : ListCell *ltab;
5365 : :
5366 : : /*
5367 : : * We process all the tables "in parallel", one pass at a time. This is
5368 : : * needed because we may have to propagate work from one table to another
5369 : : * (specifically, ALTER TYPE on a foreign key's PK has to dispatch the
5370 : : * re-adding of the foreign key constraint to the other table). Work can
5371 : : * only be propagated into later passes, however.
5372 : : */
5373 [ + + ]: 260078 : for (AlterTablePass pass = 0; pass < AT_NUM_PASSES; pass++)
5374 : : {
5375 : : /* Go through each table that needs to be processed */
5376 [ + - + + : 492099 : foreach(ltab, *wqueue)
+ + ]
5377 : : {
5378 : 252732 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5379 : 252732 : List *subcmds = tab->subcmds[pass];
5380 : : ListCell *lcmd;
5381 : :
5382 [ + + ]: 252732 : if (subcmds == NIL)
5383 : 217247 : continue;
5384 : :
5385 : : /*
5386 : : * Open the relation and store it in tab. This allows subroutines
5387 : : * close and reopen, if necessary. Appropriate lock was obtained
5388 : : * by phase 1, needn't get it again.
5389 : : */
5390 : 35485 : tab->rel = relation_open(tab->relid, NoLock);
5391 : :
5392 [ + - + + : 71342 : foreach(lcmd, subcmds)
+ + ]
5393 : 37855 : ATExecCmd(wqueue, tab,
5394 : 37855 : lfirst_node(AlterTableCmd, lcmd),
5395 : : lockmode, pass, context);
5396 : :
5397 : : /*
5398 : : * After the ALTER TYPE or SET EXPRESSION pass, do cleanup work
5399 : : * (this is not done in ATExecAlterColumnType since it should be
5400 : : * done only once if multiple columns of a table are altered).
5401 : : */
5402 [ + + + + ]: 33487 : if (pass == AT_PASS_ALTER_TYPE || pass == AT_PASS_SET_EXPRESSION)
5403 : 925 : ATPostAlterTypeCleanup(wqueue, tab, lockmode);
5404 : :
5405 [ + - ]: 33487 : if (tab->rel)
5406 : : {
5407 : 33487 : relation_close(tab->rel, NoLock);
5408 : 33487 : tab->rel = NULL;
5409 : : }
5410 : : }
5411 : : }
5412 : :
5413 : : /* Check to see if a toast table must be added. */
5414 [ + - + + : 40324 : foreach(ltab, *wqueue)
+ + ]
5415 : : {
5416 : 21611 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5417 : :
5418 : : /*
5419 : : * If the table is source table of ATTACH PARTITION command, we did
5420 : : * not modify anything about it that will change its toasting
5421 : : * requirement, so no need to check.
5422 : : */
5423 [ + + ]: 21611 : if (((tab->relkind == RELKIND_RELATION ||
5424 [ + + ]: 4001 : tab->relkind == RELKIND_PARTITIONED_TABLE) &&
5425 [ + + ]: 20369 : tab->partition_constraint == NULL) ||
5426 [ + + ]: 2562 : tab->relkind == RELKIND_MATVIEW)
5427 : 19078 : AlterTableCreateToastTable(tab->relid, (Datum) 0, lockmode);
5428 : : }
5429 : 18713 : }
5430 : :
5431 : : /*
5432 : : * ATExecCmd: dispatch a subcommand to appropriate execution routine
5433 : : */
5434 : : static void
5435 : 37855 : ATExecCmd(List **wqueue, AlteredTableInfo *tab,
5436 : : AlterTableCmd *cmd, LOCKMODE lockmode, AlterTablePass cur_pass,
5437 : : AlterTableUtilityContext *context)
5438 : : {
5439 : 37855 : ObjectAddress address = InvalidObjectAddress;
5440 : 37855 : Relation rel = tab->rel;
5441 : :
5442 [ + + + + : 37855 : switch (cmd->subtype)
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + - + -
+ + - + +
+ + + + +
+ + + + +
+ + + - ]
5443 : : {
5444 : 1579 : case AT_AddColumn: /* ADD COLUMN */
5445 : : case AT_AddColumnToView: /* add column via CREATE OR REPLACE VIEW */
5446 : 1579 : address = ATExecAddColumn(wqueue, tab, rel, &cmd,
5447 : 1579 : cmd->recurse, false,
5448 : : lockmode, cur_pass, context);
5449 : 1411 : break;
5450 : 387 : case AT_ColumnDefault: /* ALTER COLUMN DEFAULT */
5451 : 387 : address = ATExecColumnDefault(rel, cmd->name, cmd->def, lockmode);
5452 : 339 : break;
5453 : 57 : case AT_CookedColumnDefault: /* add a pre-cooked default */
5454 : 57 : address = ATExecCookedColumnDefault(rel, cmd->num, cmd->def);
5455 : 53 : break;
5456 : 107 : case AT_AddIdentity:
5457 : 107 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5458 : : cur_pass, context);
5459 : : Assert(cmd != NULL);
5460 : 99 : address = ATExecAddIdentity(rel, cmd->name, cmd->def, lockmode, cmd->recurse, false);
5461 : 63 : break;
5462 : 41 : case AT_SetIdentity:
5463 : 41 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5464 : : cur_pass, context);
5465 : : Assert(cmd != NULL);
5466 : 41 : address = ATExecSetIdentity(rel, cmd->name, cmd->def, lockmode, cmd->recurse, false);
5467 : 25 : break;
5468 : 37 : case AT_DropIdentity:
5469 : 37 : address = ATExecDropIdentity(rel, cmd->name, cmd->missing_ok, lockmode, cmd->recurse, false);
5470 : 25 : break;
5471 : 177 : case AT_DropNotNull: /* ALTER COLUMN DROP NOT NULL */
5472 : 177 : address = ATExecDropNotNull(rel, cmd->name, cmd->recurse, lockmode);
5473 : 109 : break;
5474 : 272 : case AT_SetNotNull: /* ALTER COLUMN SET NOT NULL */
5475 : 272 : address = ATExecSetNotNull(wqueue, rel, NULL, cmd->name,
5476 : 272 : cmd->recurse, false, lockmode);
5477 : 252 : break;
5478 : 193 : case AT_SetExpression:
5479 : 193 : address = ATExecSetExpression(tab, rel, cmd->name, cmd->def, lockmode);
5480 : 181 : break;
5481 : 61 : case AT_DropExpression:
5482 : 61 : address = ATExecDropExpression(rel, cmd->name, cmd->missing_ok, lockmode);
5483 : 45 : break;
5484 : 111 : case AT_SetStatistics: /* ALTER COLUMN SET STATISTICS */
5485 : 111 : address = ATExecSetStatistics(rel, cmd->name, cmd->num, cmd->def, lockmode);
5486 : 79 : break;
5487 : 17 : case AT_SetOptions: /* ALTER COLUMN SET ( options ) */
5488 : 17 : address = ATExecSetOptions(rel, cmd->name, cmd->def, false, lockmode);
5489 : 17 : break;
5490 : 4 : case AT_ResetOptions: /* ALTER COLUMN RESET ( options ) */
5491 : 4 : address = ATExecSetOptions(rel, cmd->name, cmd->def, true, lockmode);
5492 : 4 : break;
5493 : 233 : case AT_SetStorage: /* ALTER COLUMN SET STORAGE */
5494 : 233 : address = ATExecSetStorage(rel, cmd->name, cmd->def, lockmode);
5495 : 225 : break;
5496 : 48 : case AT_SetCompression: /* ALTER COLUMN SET COMPRESSION */
5497 : 48 : address = ATExecSetCompression(rel, cmd->name, cmd->def,
5498 : : lockmode);
5499 : 44 : break;
5500 : 1086 : case AT_DropColumn: /* DROP COLUMN */
5501 : 1086 : address = ATExecDropColumn(wqueue, rel, cmd->name,
5502 : 1086 : cmd->behavior, cmd->recurse, false,
5503 : 1086 : cmd->missing_ok, lockmode,
5504 : : NULL);
5505 : 966 : break;
5506 : 778 : case AT_AddIndex: /* ADD INDEX */
5507 : 778 : address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, false,
5508 : : lockmode);
5509 : 665 : break;
5510 : 330 : case AT_ReAddIndex: /* ADD INDEX */
5511 : 330 : address = ATExecAddIndex(tab, rel, (IndexStmt *) cmd->def, true,
5512 : : lockmode);
5513 : 330 : break;
5514 : 57 : case AT_ReAddStatistics: /* ADD STATISTICS */
5515 : 57 : address = ATExecAddStatistics(tab, rel, (CreateStatsStmt *) cmd->def,
5516 : : true, lockmode);
5517 : 57 : break;
5518 : 17962 : case AT_AddConstraint: /* ADD CONSTRAINT */
5519 : : /* Transform the command only during initial examination */
5520 [ + + ]: 17962 : if (cur_pass == AT_PASS_ADD_CONSTR)
5521 : 10020 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd,
5522 : 10040 : cmd->recurse, lockmode,
5523 : : cur_pass, context);
5524 : : /* Depending on constraint type, might be no more work to do now */
5525 [ + + ]: 17942 : if (cmd != NULL)
5526 : : address =
5527 : 7922 : ATExecAddConstraint(wqueue, tab, rel,
5528 : 7922 : (Constraint *) cmd->def,
5529 : 7922 : cmd->recurse, false, lockmode);
5530 : 17481 : break;
5531 : 269 : case AT_ReAddConstraint: /* Re-add pre-existing check constraint */
5532 : : address =
5533 : 269 : ATExecAddConstraint(wqueue, tab, rel, (Constraint *) cmd->def,
5534 : : true, true, lockmode);
5535 : 261 : break;
5536 : 13 : case AT_ReAddDomainConstraint: /* Re-add pre-existing domain check
5537 : : * constraint */
5538 : : address =
5539 : 13 : AlterDomainAddConstraint(((AlterDomainStmt *) cmd->def)->typeName,
5540 : 13 : ((AlterDomainStmt *) cmd->def)->def,
5541 : : NULL, true);
5542 : 9 : break;
5543 : 52 : case AT_ReAddComment: /* Re-add existing comment */
5544 : 52 : address = CommentObject((CommentStmt *) cmd->def);
5545 : 52 : break;
5546 : 6323 : case AT_AddIndexConstraint: /* ADD CONSTRAINT USING INDEX */
5547 : 6323 : address = ATExecAddIndexConstraint(tab, rel, (IndexStmt *) cmd->def,
5548 : : lockmode);
5549 : 6315 : break;
5550 : 332 : case AT_AlterConstraint: /* ALTER CONSTRAINT */
5551 : 332 : address = ATExecAlterConstraint(wqueue, rel,
5552 : 332 : castNode(ATAlterConstraint, cmd->def),
5553 : 332 : cmd->recurse, lockmode);
5554 : 256 : break;
5555 : 288 : case AT_ValidateConstraint: /* VALIDATE CONSTRAINT */
5556 : 288 : address = ATExecValidateConstraint(wqueue, rel, cmd->name, cmd->recurse,
5557 : : false, lockmode);
5558 : 284 : break;
5559 : 555 : case AT_DropConstraint: /* DROP CONSTRAINT */
5560 : 555 : ATExecDropConstraint(rel, cmd->name, cmd->behavior,
5561 : 555 : cmd->recurse,
5562 : 555 : cmd->missing_ok, lockmode);
5563 : 415 : break;
5564 : 804 : case AT_AlterColumnType: /* ALTER COLUMN TYPE */
5565 : : /* parse transformation was done earlier */
5566 : 804 : address = ATExecAlterColumnType(tab, rel, cmd, lockmode);
5567 : 776 : break;
5568 : 94 : case AT_AlterColumnGenericOptions: /* ALTER COLUMN OPTIONS */
5569 : : address =
5570 : 94 : ATExecAlterColumnGenericOptions(rel, cmd->name,
5571 : 94 : (List *) cmd->def, lockmode);
5572 : 90 : break;
5573 : 1115 : case AT_ChangeOwner: /* ALTER OWNER */
5574 : 1112 : ATExecChangeOwner(RelationGetRelid(rel),
5575 : 1115 : get_rolespec_oid(cmd->newowner, false),
5576 : : false, lockmode);
5577 : 1104 : break;
5578 : 39 : case AT_ClusterOn: /* CLUSTER ON */
5579 : 39 : address = ATExecClusterOn(rel, cmd->name, lockmode);
5580 : 39 : break;
5581 : 8 : case AT_DropCluster: /* SET WITHOUT CLUSTER */
5582 : 8 : ATExecDropCluster(rel, lockmode);
5583 : 8 : break;
5584 : 59 : case AT_SetLogged: /* SET LOGGED */
5585 : : case AT_SetUnLogged: /* SET UNLOGGED */
5586 : 59 : break;
5587 : 4 : case AT_DropOids: /* SET WITHOUT OIDS */
5588 : : /* nothing to do here, oid columns don't exist anymore */
5589 : 4 : break;
5590 : 61 : case AT_SetAccessMethod: /* SET ACCESS METHOD */
5591 : :
5592 : : /*
5593 : : * Only do this for partitioned tables, for which this is just a
5594 : : * catalog change. Tables with storage are handled by Phase 3.
5595 : : */
5596 [ + + ]: 61 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
5597 [ + + ]: 33 : tab->chgAccessMethod)
5598 : 29 : ATExecSetAccessMethodNoStorage(rel, tab->newAccessMethod);
5599 : 61 : break;
5600 : 104 : case AT_SetTableSpace: /* SET TABLESPACE */
5601 : :
5602 : : /*
5603 : : * Only do this for partitioned tables and indexes, for which this
5604 : : * is just a catalog change. Other relation types which have
5605 : : * storage are handled by Phase 3.
5606 : : */
5607 [ + + ]: 104 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
5608 [ + + ]: 96 : rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
5609 : 24 : ATExecSetTableSpaceNoStorage(rel, tab->newTableSpace);
5610 : :
5611 : 100 : break;
5612 : 674 : case AT_SetRelOptions: /* SET (...) */
5613 : : case AT_ResetRelOptions: /* RESET (...) */
5614 : : case AT_ReplaceRelOptions: /* replace entire option list */
5615 : 674 : ATExecSetRelOptions(rel, (List *) cmd->def, cmd->subtype, lockmode);
5616 : 640 : break;
5617 : 65 : case AT_EnableTrig: /* ENABLE TRIGGER name */
5618 : 65 : ATExecEnableDisableTrigger(rel, cmd->name,
5619 : : TRIGGER_FIRES_ON_ORIGIN, false,
5620 : 65 : cmd->recurse,
5621 : : lockmode);
5622 : 65 : break;
5623 : 27 : case AT_EnableAlwaysTrig: /* ENABLE ALWAYS TRIGGER name */
5624 : 27 : ATExecEnableDisableTrigger(rel, cmd->name,
5625 : : TRIGGER_FIRES_ALWAYS, false,
5626 : 27 : cmd->recurse,
5627 : : lockmode);
5628 : 27 : break;
5629 : 8 : case AT_EnableReplicaTrig: /* ENABLE REPLICA TRIGGER name */
5630 : 8 : ATExecEnableDisableTrigger(rel, cmd->name,
5631 : : TRIGGER_FIRES_ON_REPLICA, false,
5632 : 8 : cmd->recurse,
5633 : : lockmode);
5634 : 8 : break;
5635 : 75 : case AT_DisableTrig: /* DISABLE TRIGGER name */
5636 : 75 : ATExecEnableDisableTrigger(rel, cmd->name,
5637 : : TRIGGER_DISABLED, false,
5638 : 75 : cmd->recurse,
5639 : : lockmode);
5640 : 75 : break;
5641 : 0 : case AT_EnableTrigAll: /* ENABLE TRIGGER ALL */
5642 : 0 : ATExecEnableDisableTrigger(rel, NULL,
5643 : : TRIGGER_FIRES_ON_ORIGIN, false,
5644 : 0 : cmd->recurse,
5645 : : lockmode);
5646 : 0 : break;
5647 : 8 : case AT_DisableTrigAll: /* DISABLE TRIGGER ALL */
5648 : 8 : ATExecEnableDisableTrigger(rel, NULL,
5649 : : TRIGGER_DISABLED, false,
5650 : 8 : cmd->recurse,
5651 : : lockmode);
5652 : 8 : break;
5653 : 0 : case AT_EnableTrigUser: /* ENABLE TRIGGER USER */
5654 : 0 : ATExecEnableDisableTrigger(rel, NULL,
5655 : : TRIGGER_FIRES_ON_ORIGIN, true,
5656 : 0 : cmd->recurse,
5657 : : lockmode);
5658 : 0 : break;
5659 : 8 : case AT_DisableTrigUser: /* DISABLE TRIGGER USER */
5660 : 8 : ATExecEnableDisableTrigger(rel, NULL,
5661 : : TRIGGER_DISABLED, true,
5662 : 8 : cmd->recurse,
5663 : : lockmode);
5664 : 8 : break;
5665 : :
5666 : 5 : case AT_EnableRule: /* ENABLE RULE name */
5667 : 5 : ATExecEnableDisableRule(rel, cmd->name,
5668 : : RULE_FIRES_ON_ORIGIN, lockmode);
5669 : 5 : break;
5670 : 0 : case AT_EnableAlwaysRule: /* ENABLE ALWAYS RULE name */
5671 : 0 : ATExecEnableDisableRule(rel, cmd->name,
5672 : : RULE_FIRES_ALWAYS, lockmode);
5673 : 0 : break;
5674 : 4 : case AT_EnableReplicaRule: /* ENABLE REPLICA RULE name */
5675 : 4 : ATExecEnableDisableRule(rel, cmd->name,
5676 : : RULE_FIRES_ON_REPLICA, lockmode);
5677 : 4 : break;
5678 : 20 : case AT_DisableRule: /* DISABLE RULE name */
5679 : 20 : ATExecEnableDisableRule(rel, cmd->name,
5680 : : RULE_DISABLED, lockmode);
5681 : 20 : break;
5682 : :
5683 : 285 : case AT_AddInherit:
5684 : 285 : address = ATExecAddInherit(rel, (RangeVar *) cmd->def, lockmode);
5685 : 205 : break;
5686 : 61 : case AT_DropInherit:
5687 : 61 : address = ATExecDropInherit(rel, (RangeVar *) cmd->def, lockmode);
5688 : 57 : break;
5689 : 50 : case AT_AddOf:
5690 : 50 : address = ATExecAddOf(rel, (TypeName *) cmd->def, lockmode);
5691 : 22 : break;
5692 : 4 : case AT_DropOf:
5693 : 4 : ATExecDropOf(rel, lockmode);
5694 : 4 : break;
5695 : 329 : case AT_ReplicaIdentity:
5696 : 329 : ATExecReplicaIdentity(rel, (ReplicaIdentityStmt *) cmd->def, lockmode);
5697 : 293 : break;
5698 : 246 : case AT_EnableRowSecurity:
5699 : 246 : ATExecSetRowSecurity(rel, true);
5700 : 246 : break;
5701 : 6 : case AT_DisableRowSecurity:
5702 : 6 : ATExecSetRowSecurity(rel, false);
5703 : 6 : break;
5704 : 65 : case AT_ForceRowSecurity:
5705 : 65 : ATExecForceNoForceRowSecurity(rel, true);
5706 : 65 : break;
5707 : 20 : case AT_NoForceRowSecurity:
5708 : 20 : ATExecForceNoForceRowSecurity(rel, false);
5709 : 20 : break;
5710 : 34 : case AT_GenericOptions:
5711 : 34 : ATExecGenericOptions(rel, (List *) cmd->def);
5712 : 33 : break;
5713 : 1835 : case AT_AttachPartition:
5714 : 1835 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5715 : : cur_pass, context);
5716 : : Assert(cmd != NULL);
5717 [ + + ]: 1819 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
5718 : 1533 : address = ATExecAttachPartition(wqueue, rel, (PartitionCmd *) cmd->def,
5719 : : context);
5720 : : else
5721 : 286 : address = ATExecAttachPartitionIdx(wqueue, rel,
5722 : 286 : ((PartitionCmd *) cmd->def)->name);
5723 : 1551 : break;
5724 : 362 : case AT_DetachPartition:
5725 : 362 : cmd = ATParseTransformCmd(wqueue, tab, rel, cmd, false, lockmode,
5726 : : cur_pass, context);
5727 : : Assert(cmd != NULL);
5728 : : /* ATPrepCmd ensures it must be a table */
5729 : : Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
5730 : 362 : address = ATExecDetachPartition(wqueue, tab, rel,
5731 : 362 : ((PartitionCmd *) cmd->def)->name,
5732 : 362 : ((PartitionCmd *) cmd->def)->concurrent);
5733 : 284 : break;
5734 : 7 : case AT_DetachPartitionFinalize:
5735 : 7 : address = ATExecDetachPartitionFinalize(rel, ((PartitionCmd *) cmd->def)->name);
5736 : 7 : break;
5737 : 0 : default: /* oops */
5738 [ # # ]: 0 : elog(ERROR, "unrecognized alter table type: %d",
5739 : : (int) cmd->subtype);
5740 : : break;
5741 : : }
5742 : :
5743 : : /*
5744 : : * Report the subcommand to interested event triggers.
5745 : : */
5746 [ + + ]: 35857 : if (cmd)
5747 : 25837 : EventTriggerCollectAlterTableSubcmd((Node *) cmd, address);
5748 : :
5749 : : /*
5750 : : * Bump the command counter to ensure the next subcommand in the sequence
5751 : : * can see the changes so far
5752 : : */
5753 : 35857 : CommandCounterIncrement();
5754 : 35857 : }
5755 : :
5756 : : /*
5757 : : * ATParseTransformCmd: perform parse transformation for one subcommand
5758 : : *
5759 : : * Returns the transformed subcommand tree, if there is one, else NULL.
5760 : : *
5761 : : * The parser may hand back additional AlterTableCmd(s) and/or other
5762 : : * utility statements, either before or after the original subcommand.
5763 : : * Other AlterTableCmds are scheduled into the appropriate slot of the
5764 : : * AlteredTableInfo (they had better be for later passes than the current one).
5765 : : * Utility statements that are supposed to happen before the AlterTableCmd
5766 : : * are executed immediately. Those that are supposed to happen afterwards
5767 : : * are added to the tab->afterStmts list to be done at the very end.
5768 : : */
5769 : : static AlterTableCmd *
5770 : 14834 : ATParseTransformCmd(List **wqueue, AlteredTableInfo *tab, Relation rel,
5771 : : AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
5772 : : AlterTablePass cur_pass, AlterTableUtilityContext *context)
5773 : : {
5774 : 14834 : AlterTableCmd *newcmd = NULL;
5775 : 14834 : AlterTableStmt *atstmt = makeNode(AlterTableStmt);
5776 : : List *beforeStmts;
5777 : : List *afterStmts;
5778 : : ListCell *lc;
5779 : :
5780 : : /* Gin up an AlterTableStmt with just this subcommand and this table */
5781 : 14834 : atstmt->relation =
5782 : 14834 : makeRangeVar(get_namespace_name(RelationGetNamespace(rel)),
5783 : 14834 : pstrdup(RelationGetRelationName(rel)),
5784 : : -1);
5785 : 14834 : atstmt->relation->inh = recurse;
5786 : 14834 : atstmt->cmds = list_make1(cmd);
5787 : 14834 : atstmt->objtype = OBJECT_TABLE; /* needn't be picky here */
5788 : 14834 : atstmt->missing_ok = false;
5789 : :
5790 : : /* Transform the AlterTableStmt */
5791 : 14834 : atstmt = transformAlterTableStmt(RelationGetRelid(rel),
5792 : : atstmt,
5793 : : context->queryString,
5794 : : &beforeStmts,
5795 : : &afterStmts);
5796 : :
5797 : : /* Execute any statements that should happen before these subcommand(s) */
5798 [ + + + + : 15097 : foreach(lc, beforeStmts)
+ + ]
5799 : : {
5800 : 315 : Node *stmt = (Node *) lfirst(lc);
5801 : :
5802 : 315 : ProcessUtilityForAlterTable(stmt, context);
5803 : 307 : CommandCounterIncrement();
5804 : : }
5805 : :
5806 : : /* Examine the transformed subcommands and schedule them appropriately */
5807 [ + - + + : 34591 : foreach(lc, atstmt->cmds)
+ + ]
5808 : : {
5809 : 19809 : AlterTableCmd *cmd2 = lfirst_node(AlterTableCmd, lc);
5810 : : AlterTablePass pass;
5811 : :
5812 : : /*
5813 : : * This switch need only cover the subcommand types that can be added
5814 : : * by parse_utilcmd.c; otherwise, we'll use the default strategy of
5815 : : * executing the subcommand immediately, as a substitute for the
5816 : : * original subcommand. (Note, however, that this does cause
5817 : : * AT_AddConstraint subcommands to be rescheduled into later passes,
5818 : : * which is important for index and foreign key constraints.)
5819 : : *
5820 : : * We assume we needn't do any phase-1 checks for added subcommands.
5821 : : */
5822 [ + + + - : 19809 : switch (cmd2->subtype)
+ ]
5823 : : {
5824 : 794 : case AT_AddIndex:
5825 : 794 : pass = AT_PASS_ADD_INDEX;
5826 : 794 : break;
5827 : 6323 : case AT_AddIndexConstraint:
5828 : 6323 : pass = AT_PASS_ADD_INDEXCONSTR;
5829 : 6323 : break;
5830 : 7930 : case AT_AddConstraint:
5831 : : /* Recursion occurs during execution phase */
5832 [ + + ]: 7930 : if (recurse)
5833 : 7903 : cmd2->recurse = true;
5834 [ + - + ]: 7930 : switch (castNode(Constraint, cmd2->def)->contype)
5835 : : {
5836 : 5450 : case CONSTR_NOTNULL:
5837 : 5450 : pass = AT_PASS_COL_ATTRS;
5838 : 5450 : break;
5839 : 0 : case CONSTR_PRIMARY:
5840 : : case CONSTR_UNIQUE:
5841 : : case CONSTR_EXCLUSION:
5842 : 0 : pass = AT_PASS_ADD_INDEXCONSTR;
5843 : 0 : break;
5844 : 2480 : default:
5845 : 2480 : pass = AT_PASS_ADD_OTHERCONSTR;
5846 : 2480 : break;
5847 : : }
5848 : 7930 : break;
5849 : 0 : case AT_AlterColumnGenericOptions:
5850 : : /* This command never recurses */
5851 : : /* No command-specific prep needed */
5852 : 0 : pass = AT_PASS_MISC;
5853 : 0 : break;
5854 : 4762 : default:
5855 : 4762 : pass = cur_pass;
5856 : 4762 : break;
5857 : : }
5858 : :
5859 [ - + ]: 19809 : if (pass < cur_pass)
5860 : : {
5861 : : /* Cannot schedule into a pass we already finished */
5862 [ # # ]: 0 : elog(ERROR, "ALTER TABLE scheduling failure: too late for pass %d",
5863 : : pass);
5864 : : }
5865 [ + + ]: 19809 : else if (pass > cur_pass)
5866 : : {
5867 : : /* OK, queue it up for later */
5868 : 15047 : tab->subcmds[pass] = lappend(tab->subcmds[pass], cmd2);
5869 : : }
5870 : : else
5871 : : {
5872 : : /*
5873 : : * We should see at most one subcommand for the current pass,
5874 : : * which is the transformed version of the original subcommand.
5875 : : */
5876 [ + - + - ]: 4762 : if (newcmd == NULL && cmd->subtype == cmd2->subtype)
5877 : : {
5878 : : /* Found the transformed version of our subcommand */
5879 : 4762 : newcmd = cmd2;
5880 : : }
5881 : : else
5882 [ # # ]: 0 : elog(ERROR, "ALTER TABLE scheduling failure: bogus item for pass %d",
5883 : : pass);
5884 : : }
5885 : : }
5886 : :
5887 : : /* Queue up any after-statements to happen at the end */
5888 : 14782 : tab->afterStmts = list_concat(tab->afterStmts, afterStmts);
5889 : :
5890 : 14782 : return newcmd;
5891 : : }
5892 : :
5893 : : /*
5894 : : * ATRewriteTables: ALTER TABLE phase 3
5895 : : */
5896 : : static void
5897 : 18713 : ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode,
5898 : : AlterTableUtilityContext *context)
5899 : : {
5900 : : ListCell *ltab;
5901 : :
5902 : : /* Go through each table that needs to be checked or rewritten */
5903 [ + - + + : 39910 : foreach(ltab, *wqueue)
+ + ]
5904 : : {
5905 : 21527 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
5906 : :
5907 : : /* Relations without storage may be ignored here */
5908 [ + + + + : 21527 : if (!RELKIND_HAS_STORAGE(tab->relkind))
+ + + - +
+ ]
5909 : 3823 : continue;
5910 : :
5911 : : /*
5912 : : * If we change column data types, the operation has to be propagated
5913 : : * to tables that use this table's rowtype as a column type.
5914 : : * tab->newvals will also be non-NULL in the case where we're adding a
5915 : : * column with a default. We choose to forbid that case as well,
5916 : : * since composite types might eventually support defaults.
5917 : : *
5918 : : * (Eventually we'll probably need to check for composite type
5919 : : * dependencies even when we're just scanning the table without a
5920 : : * rewrite, but at the moment a composite type does not enforce any
5921 : : * constraints, so it's not necessary/appropriate to enforce them just
5922 : : * during ALTER.)
5923 : : */
5924 [ + + + + : 17704 : if (tab->newvals != NIL || (tab->rewrite > 0 && tab->relkind != RELKIND_SEQUENCE))
+ + ]
5925 : : {
5926 : : Relation rel;
5927 : :
5928 : 1306 : rel = table_open(tab->relid, NoLock);
5929 : 1306 : find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
5930 : 1270 : table_close(rel, NoLock);
5931 : : }
5932 : :
5933 : : /*
5934 : : * We only need to rewrite the table if at least one column needs to
5935 : : * be recomputed, or we are changing its persistence or access method.
5936 : : *
5937 : : * There are two reasons for requiring a rewrite when changing
5938 : : * persistence: on one hand, we need to ensure that the buffers
5939 : : * belonging to each of the two relations are marked with or without
5940 : : * BM_PERMANENT properly. On the other hand, since rewriting creates
5941 : : * and assigns a new relfilenumber, we automatically create or drop an
5942 : : * init fork for the relation as appropriate.
5943 : : */
5944 [ + + + + ]: 17668 : if (tab->rewrite > 0 && tab->relkind != RELKIND_SEQUENCE)
5945 : 724 : {
5946 : : /* Build a temporary relation and copy data */
5947 : : Relation OldHeap;
5948 : : Oid OIDNewHeap;
5949 : : Oid NewAccessMethod;
5950 : : Oid NewTableSpace;
5951 : : char persistence;
5952 : :
5953 : 785 : OldHeap = table_open(tab->relid, NoLock);
5954 : :
5955 : : /*
5956 : : * We don't support rewriting of system catalogs; there are too
5957 : : * many corner cases and too little benefit. In particular this
5958 : : * is certainly not going to work for mapped catalogs.
5959 : : */
5960 [ - + ]: 785 : if (IsSystemRelation(OldHeap))
5961 [ # # ]: 0 : ereport(ERROR,
5962 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5963 : : errmsg("cannot rewrite system relation \"%s\"",
5964 : : RelationGetRelationName(OldHeap))));
5965 : :
5966 [ + + - + : 785 : if (RelationIsUsedAsCatalogTable(OldHeap))
- - + + ]
5967 [ + - ]: 1 : ereport(ERROR,
5968 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5969 : : errmsg("cannot rewrite table \"%s\" used as a catalog table",
5970 : : RelationGetRelationName(OldHeap))));
5971 : :
5972 : : /*
5973 : : * Don't allow rewrite on temp tables of other backends ... their
5974 : : * local buffer manager is not going to cope. (This is redundant
5975 : : * with the check in CheckAlterTableIsSafe, but for safety we'll
5976 : : * check here too.)
5977 : : */
5978 [ + + - + ]: 784 : if (RELATION_IS_OTHER_TEMP(OldHeap))
5979 [ # # ]: 0 : ereport(ERROR,
5980 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5981 : : errmsg("cannot rewrite temporary tables of other sessions")));
5982 : :
5983 : : /*
5984 : : * Select destination tablespace (same as original unless user
5985 : : * requested a change)
5986 : : */
5987 [ - + ]: 784 : if (tab->newTableSpace)
5988 : 0 : NewTableSpace = tab->newTableSpace;
5989 : : else
5990 : 784 : NewTableSpace = OldHeap->rd_rel->reltablespace;
5991 : :
5992 : : /*
5993 : : * Select destination access method (same as original unless user
5994 : : * requested a change)
5995 : : */
5996 [ + + ]: 784 : if (tab->chgAccessMethod)
5997 : 24 : NewAccessMethod = tab->newAccessMethod;
5998 : : else
5999 : 760 : NewAccessMethod = OldHeap->rd_rel->relam;
6000 : :
6001 : : /*
6002 : : * Select persistence of transient table (same as original unless
6003 : : * user requested a change)
6004 : : */
6005 [ + + ]: 784 : persistence = tab->chgPersistence ?
6006 : 749 : tab->newrelpersistence : OldHeap->rd_rel->relpersistence;
6007 : :
6008 : 784 : table_close(OldHeap, NoLock);
6009 : :
6010 : : /*
6011 : : * Fire off an Event Trigger now, before actually rewriting the
6012 : : * table.
6013 : : *
6014 : : * We don't support Event Trigger for nested commands anywhere,
6015 : : * here included, and parsetree is given NULL when coming from
6016 : : * AlterTableInternal.
6017 : : *
6018 : : * And fire it only once.
6019 : : */
6020 [ + - ]: 784 : if (parsetree)
6021 : 784 : EventTriggerTableRewrite((Node *) parsetree,
6022 : : tab->relid,
6023 : : tab->rewrite);
6024 : :
6025 : : /*
6026 : : * Create transient table that will receive the modified data.
6027 : : *
6028 : : * Ensure it is marked correctly as logged or unlogged. We have
6029 : : * to do this here so that buffers for the new relfilenumber will
6030 : : * have the right persistence set, and at the same time ensure
6031 : : * that the original filenumbers's buffers will get read in with
6032 : : * the correct setting (i.e. the original one). Otherwise a
6033 : : * rollback after the rewrite would possibly result with buffers
6034 : : * for the original filenumbers having the wrong persistence
6035 : : * setting.
6036 : : *
6037 : : * NB: This relies on swap_relation_files() also swapping the
6038 : : * persistence. That wouldn't work for pg_class, but that can't be
6039 : : * unlogged anyway.
6040 : : */
6041 : 780 : OIDNewHeap = make_new_heap(tab->relid, NewTableSpace, NewAccessMethod,
6042 : : persistence, lockmode);
6043 : :
6044 : : /*
6045 : : * Copy the heap data into the new table with the desired
6046 : : * modifications, and test the current data within the table
6047 : : * against new constraints generated by ALTER TABLE commands.
6048 : : */
6049 : 780 : ATRewriteTable(tab, OIDNewHeap);
6050 : :
6051 : : /*
6052 : : * Swap the physical files of the old and new heaps, then rebuild
6053 : : * indexes and discard the old heap. We can use RecentXmin for
6054 : : * the table's new relfrozenxid because we rewrote all the tuples
6055 : : * in ATRewriteTable, so no older Xid remains in the table. Also,
6056 : : * we never try to swap toast tables by content, since we have no
6057 : : * interest in letting this code work on system catalogs.
6058 : : */
6059 : 728 : finish_heap_swap(tab->relid, OIDNewHeap,
6060 : : false, false, true,
6061 : 728 : !OidIsValid(tab->newTableSpace),
6062 : : true, /* reindex */
6063 : : RecentXmin,
6064 : : ReadNextMultiXactId(),
6065 : : persistence);
6066 : :
6067 [ - + ]: 724 : InvokeObjectPostAlterHook(RelationRelationId, tab->relid, 0);
6068 : : }
6069 [ + + + - ]: 16883 : else if (tab->rewrite > 0 && tab->relkind == RELKIND_SEQUENCE)
6070 : : {
6071 [ + - ]: 16 : if (tab->chgPersistence)
6072 : 16 : SequenceChangePersistence(tab->relid, tab->newrelpersistence);
6073 : : }
6074 : : else
6075 : : {
6076 : : /*
6077 : : * If required, test the current data within the table against new
6078 : : * constraints generated by ALTER TABLE commands, but don't
6079 : : * rebuild data.
6080 : : */
6081 [ + + + + ]: 16867 : if (tab->constraints != NIL || tab->verify_new_notnull ||
6082 [ + + ]: 14727 : tab->partition_constraint != NULL)
6083 : 3362 : ATRewriteTable(tab, InvalidOid);
6084 : :
6085 : : /*
6086 : : * If we had SET TABLESPACE but no reason to reconstruct tuples,
6087 : : * just do a block-by-block copy.
6088 : : */
6089 [ + + ]: 16634 : if (tab->newTableSpace)
6090 : 80 : ATExecSetTableSpace(tab->relid, tab->newTableSpace, lockmode);
6091 : : }
6092 : :
6093 : : /*
6094 : : * Also change persistence of owned sequences, so that it matches the
6095 : : * table persistence.
6096 : : */
6097 [ + + ]: 17374 : if (tab->chgPersistence)
6098 : : {
6099 : 51 : List *seqlist = getOwnedSequences(tab->relid);
6100 : : ListCell *lc;
6101 : :
6102 [ + + + + : 83 : foreach(lc, seqlist)
+ + ]
6103 : : {
6104 : 32 : Oid seq_relid = lfirst_oid(lc);
6105 : :
6106 : 32 : SequenceChangePersistence(seq_relid, tab->newrelpersistence);
6107 : : }
6108 : : }
6109 : : }
6110 : :
6111 : : /*
6112 : : * Foreign key constraints are checked in a final pass, since (a) it's
6113 : : * generally best to examine each one separately, and (b) it's at least
6114 : : * theoretically possible that we have changed both relations of the
6115 : : * foreign key, and we'd better have finished both rewrites before we try
6116 : : * to read the tables.
6117 : : */
6118 [ + - + + : 39311 : foreach(ltab, *wqueue)
+ + ]
6119 : : {
6120 : 21019 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
6121 : 21019 : Relation rel = NULL;
6122 : : ListCell *lcon;
6123 : :
6124 : : /* Relations without storage may be ignored here too */
6125 [ + + + + : 21019 : if (!RELKIND_HAS_STORAGE(tab->relkind))
+ + + - +
+ ]
6126 : 3718 : continue;
6127 : :
6128 [ + + + + : 18619 : foreach(lcon, tab->constraints)
+ + ]
6129 : : {
6130 : 1409 : NewConstraint *con = lfirst(lcon);
6131 : :
6132 [ + + ]: 1409 : if (con->contype == CONSTR_FOREIGN)
6133 : : {
6134 : 847 : Constraint *fkconstraint = (Constraint *) con->qual;
6135 : : Relation refrel;
6136 : :
6137 [ + + ]: 847 : if (rel == NULL)
6138 : : {
6139 : : /* Long since locked, no need for another */
6140 : 839 : rel = table_open(tab->relid, NoLock);
6141 : : }
6142 : :
6143 : 847 : refrel = table_open(con->refrelid, RowShareLock);
6144 : :
6145 : 847 : validateForeignKeyConstraint(fkconstraint->conname, rel, refrel,
6146 : : con->refindid,
6147 : : con->conid,
6148 : 847 : con->conwithperiod);
6149 : :
6150 : : /*
6151 : : * No need to mark the constraint row as validated, we did
6152 : : * that when we inserted the row earlier.
6153 : : */
6154 : :
6155 : 756 : table_close(refrel, NoLock);
6156 : : }
6157 : : }
6158 : :
6159 [ + + ]: 17210 : if (rel)
6160 : 748 : table_close(rel, NoLock);
6161 : : }
6162 : :
6163 : : /* Finally, run any afterStmts that were queued up */
6164 [ + - + + : 39193 : foreach(ltab, *wqueue)
+ + ]
6165 : : {
6166 : 20901 : AlteredTableInfo *tab = (AlteredTableInfo *) lfirst(ltab);
6167 : : ListCell *lc;
6168 : :
6169 [ + + + + : 20957 : foreach(lc, tab->afterStmts)
+ + ]
6170 : : {
6171 : 56 : Node *stmt = (Node *) lfirst(lc);
6172 : :
6173 : 56 : ProcessUtilityForAlterTable(stmt, context);
6174 : 56 : CommandCounterIncrement();
6175 : : }
6176 : : }
6177 : 18292 : }
6178 : :
6179 : : /*
6180 : : * ATRewriteTable: scan or rewrite one table
6181 : : *
6182 : : * A rewrite is requested by passing a valid OIDNewHeap; in that case, caller
6183 : : * must already hold AccessExclusiveLock on it.
6184 : : */
6185 : : static void
6186 : 4142 : ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap)
6187 : : {
6188 : : Relation oldrel;
6189 : : Relation newrel;
6190 : : TupleDesc oldTupDesc;
6191 : : TupleDesc newTupDesc;
6192 : 4142 : bool needscan = false;
6193 : : List *notnull_attrs;
6194 : : List *notnull_virtual_attrs;
6195 : : int i;
6196 : : ListCell *l;
6197 : : EState *estate;
6198 : : CommandId mycid;
6199 : : BulkInsertState bistate;
6200 : : uint32 ti_options;
6201 : 4142 : ExprState *partqualstate = NULL;
6202 : :
6203 : : /*
6204 : : * Open the relation(s). We have surely already locked the existing
6205 : : * table.
6206 : : */
6207 : 4142 : oldrel = table_open(tab->relid, NoLock);
6208 : 4142 : oldTupDesc = tab->oldDesc;
6209 : 4142 : newTupDesc = RelationGetDescr(oldrel); /* includes all mods */
6210 : :
6211 [ + + ]: 4142 : if (OidIsValid(OIDNewHeap))
6212 : : {
6213 : : Assert(CheckRelationOidLockedByMe(OIDNewHeap, AccessExclusiveLock,
6214 : : false));
6215 : 780 : newrel = table_open(OIDNewHeap, NoLock);
6216 : : }
6217 : : else
6218 : 3362 : newrel = NULL;
6219 : :
6220 : : /*
6221 : : * Prepare a BulkInsertState and options for table_tuple_insert. The FSM
6222 : : * is empty, so don't bother using it.
6223 : : */
6224 [ + + ]: 4142 : if (newrel)
6225 : : {
6226 : 780 : mycid = GetCurrentCommandId(true);
6227 : 780 : bistate = GetBulkInsertState();
6228 : 780 : ti_options = TABLE_INSERT_SKIP_FSM;
6229 : : }
6230 : : else
6231 : : {
6232 : : /* keep compiler quiet about using these uninitialized */
6233 : 3362 : mycid = 0;
6234 : 3362 : bistate = NULL;
6235 : 3362 : ti_options = 0;
6236 : : }
6237 : :
6238 : : /*
6239 : : * Generate the constraint and default execution states
6240 : : */
6241 : :
6242 : 4142 : estate = CreateExecutorState();
6243 : :
6244 : : /* Build the needed expression execution states */
6245 [ + + + + : 5715 : foreach(l, tab->constraints)
+ + ]
6246 : : {
6247 : 1573 : NewConstraint *con = lfirst(l);
6248 : :
6249 [ + + - ]: 1573 : switch (con->contype)
6250 : : {
6251 : 722 : case CONSTR_CHECK:
6252 : 722 : needscan = true;
6253 : 722 : con->qualstate = ExecPrepareExpr((Expr *) expand_generated_columns_in_expr(con->qual, oldrel, 1), estate);
6254 : 722 : break;
6255 : 851 : case CONSTR_FOREIGN:
6256 : : /* Nothing to do here */
6257 : 851 : break;
6258 : 0 : default:
6259 [ # # ]: 0 : elog(ERROR, "unrecognized constraint type: %d",
6260 : : (int) con->contype);
6261 : : }
6262 : : }
6263 : :
6264 : : /* Build expression execution states for partition check quals */
6265 [ + + ]: 4142 : if (tab->partition_constraint)
6266 : : {
6267 : 1316 : needscan = true;
6268 : 1316 : partqualstate = ExecPrepareExpr(tab->partition_constraint, estate);
6269 : : }
6270 : :
6271 [ + + + + : 4983 : foreach(l, tab->newvals)
+ + ]
6272 : : {
6273 : 841 : NewColumnValue *ex = lfirst(l);
6274 : :
6275 : : /* expr already planned */
6276 : 841 : ex->exprstate = ExecInitExpr(ex->expr, NULL);
6277 : : }
6278 : :
6279 : 4142 : notnull_attrs = notnull_virtual_attrs = NIL;
6280 [ + + + + ]: 4142 : if (newrel || tab->verify_new_notnull)
6281 : : {
6282 : : /*
6283 : : * If we are rebuilding the tuples OR if we added any new but not
6284 : : * verified not-null constraints, check all *valid* not-null
6285 : : * constraints. This is a bit of overkill but it minimizes risk of
6286 : : * bugs.
6287 : : *
6288 : : * notnull_attrs does *not* collect attribute numbers for valid
6289 : : * not-null constraints over virtual generated columns; instead, they
6290 : : * are collected in notnull_virtual_attrs for verification elsewhere.
6291 : : */
6292 [ + + ]: 5360 : for (i = 0; i < newTupDesc->natts; i++)
6293 : : {
6294 : 3892 : CompactAttribute *attr = TupleDescCompactAttr(newTupDesc, i);
6295 : :
6296 [ + + ]: 3892 : if (attr->attnullability == ATTNULLABLE_VALID &&
6297 [ + - ]: 1467 : !attr->attisdropped)
6298 : : {
6299 : 1467 : Form_pg_attribute wholeatt = TupleDescAttr(newTupDesc, i);
6300 : :
6301 [ + + ]: 1467 : if (wholeatt->attgenerated != ATTRIBUTE_GENERATED_VIRTUAL)
6302 : 1403 : notnull_attrs = lappend_int(notnull_attrs, wholeatt->attnum);
6303 : : else
6304 : 64 : notnull_virtual_attrs = lappend_int(notnull_virtual_attrs,
6305 : 64 : wholeatt->attnum);
6306 : : }
6307 : : }
6308 [ + + + + ]: 1468 : if (notnull_attrs || notnull_virtual_attrs)
6309 : 1070 : needscan = true;
6310 : : }
6311 : :
6312 [ + + + + ]: 4142 : if (newrel || needscan)
6313 : : {
6314 : : ExprContext *econtext;
6315 : : TupleTableSlot *oldslot;
6316 : : TupleTableSlot *newslot;
6317 : : TableScanDesc scan;
6318 : : MemoryContext oldCxt;
6319 : 3421 : List *dropped_attrs = NIL;
6320 : : ListCell *lc;
6321 : : Snapshot snapshot;
6322 : 3421 : ResultRelInfo *rInfo = NULL;
6323 : :
6324 : : /*
6325 : : * When adding or changing a virtual generated column with a not-null
6326 : : * constraint, we need to evaluate whether the generation expression
6327 : : * is null. For that, we borrow ExecRelGenVirtualNotNull(). Here, we
6328 : : * prepare a dummy ResultRelInfo.
6329 : : */
6330 [ + + ]: 3421 : if (notnull_virtual_attrs != NIL)
6331 : : {
6332 : : MemoryContext oldcontext;
6333 : :
6334 : : Assert(newTupDesc->constr->has_generated_virtual);
6335 : : Assert(newTupDesc->constr->has_not_null);
6336 : 44 : oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
6337 : 44 : rInfo = makeNode(ResultRelInfo);
6338 : 44 : InitResultRelInfo(rInfo,
6339 : : oldrel,
6340 : : 0, /* dummy rangetable index */
6341 : : NULL,
6342 : : estate->es_instrument);
6343 : 44 : MemoryContextSwitchTo(oldcontext);
6344 : : }
6345 : :
6346 [ + + ]: 3421 : if (newrel)
6347 [ - + ]: 780 : ereport(DEBUG1,
6348 : : (errmsg_internal("rewriting table \"%s\"",
6349 : : RelationGetRelationName(oldrel))));
6350 : : else
6351 [ + + ]: 2641 : ereport(DEBUG1,
6352 : : (errmsg_internal("verifying table \"%s\"",
6353 : : RelationGetRelationName(oldrel))));
6354 : :
6355 [ + + ]: 3421 : if (newrel)
6356 : : {
6357 : : /*
6358 : : * All predicate locks on the tuples or pages are about to be made
6359 : : * invalid, because we move tuples around. Promote them to
6360 : : * relation locks.
6361 : : */
6362 : 780 : TransferPredicateLocksToHeapRelation(oldrel);
6363 : : }
6364 : :
6365 [ - + ]: 3421 : econtext = GetPerTupleExprContext(estate);
6366 : :
6367 : : /*
6368 : : * Create necessary tuple slots. When rewriting, two slots are needed,
6369 : : * otherwise one suffices. In the case where one slot suffices, we
6370 : : * need to use the new tuple descriptor, otherwise some constraints
6371 : : * can't be evaluated. Note that even when the tuple layout is the
6372 : : * same and no rewrite is required, the tupDescs might not be
6373 : : * (consider ADD COLUMN without a default).
6374 : : */
6375 [ + + ]: 3421 : if (tab->rewrite)
6376 : : {
6377 : : Assert(newrel != NULL);
6378 : 780 : oldslot = MakeSingleTupleTableSlot(oldTupDesc,
6379 : : table_slot_callbacks(oldrel));
6380 : 780 : newslot = MakeSingleTupleTableSlot(newTupDesc,
6381 : : table_slot_callbacks(newrel));
6382 : :
6383 : : /*
6384 : : * Set all columns in the new slot to NULL initially, to ensure
6385 : : * columns added as part of the rewrite are initialized to NULL.
6386 : : * That is necessary as tab->newvals will not contain an
6387 : : * expression for columns with a NULL default, e.g. when adding a
6388 : : * column without a default together with a column with a default
6389 : : * requiring an actual rewrite.
6390 : : */
6391 : 780 : ExecStoreAllNullTuple(newslot);
6392 : : }
6393 : : else
6394 : : {
6395 : 2641 : oldslot = MakeSingleTupleTableSlot(newTupDesc,
6396 : : table_slot_callbacks(oldrel));
6397 : 2641 : newslot = NULL;
6398 : : }
6399 : :
6400 : : /*
6401 : : * Any attributes that are dropped according to the new tuple
6402 : : * descriptor can be set to NULL. We precompute the list of dropped
6403 : : * attributes to avoid needing to do so in the per-tuple loop.
6404 : : */
6405 [ + + ]: 11929 : for (i = 0; i < newTupDesc->natts; i++)
6406 : : {
6407 [ + + ]: 8508 : if (TupleDescAttr(newTupDesc, i)->attisdropped)
6408 : 516 : dropped_attrs = lappend_int(dropped_attrs, i);
6409 : : }
6410 : :
6411 : : /*
6412 : : * Scan through the rows, generating a new row if needed and then
6413 : : * checking all the constraints.
6414 : : */
6415 : 3421 : snapshot = RegisterSnapshot(GetLatestSnapshot());
6416 : 3421 : scan = table_beginscan(oldrel, snapshot, 0, NULL,
6417 : : SO_NONE);
6418 : :
6419 : : /*
6420 : : * Switch to per-tuple memory context and reset it for each tuple
6421 : : * produced, so we don't leak memory.
6422 : : */
6423 [ + - ]: 3421 : oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
6424 : :
6425 [ + + ]: 490769 : while (table_scan_getnextslot(scan, ForwardScanDirection, oldslot))
6426 : : {
6427 : : TupleTableSlot *insertslot;
6428 : :
6429 [ + + ]: 484212 : if (tab->rewrite > 0)
6430 : : {
6431 : : /* Extract data from old tuple */
6432 : 67479 : slot_getallattrs(oldslot);
6433 : 67479 : ExecClearTuple(newslot);
6434 : :
6435 : : /* copy attributes */
6436 : 67479 : memcpy(newslot->tts_values, oldslot->tts_values,
6437 : 67479 : sizeof(Datum) * oldslot->tts_nvalid);
6438 : 67479 : memcpy(newslot->tts_isnull, oldslot->tts_isnull,
6439 : 67479 : sizeof(bool) * oldslot->tts_nvalid);
6440 : :
6441 : : /* Set dropped attributes to null in new tuple */
6442 [ + + + + : 67564 : foreach(lc, dropped_attrs)
+ + ]
6443 : 85 : newslot->tts_isnull[lfirst_int(lc)] = true;
6444 : :
6445 : : /*
6446 : : * Constraints and GENERATED expressions might reference the
6447 : : * tableoid column, so fill tts_tableOid with the desired
6448 : : * value. (We must do this each time, because it gets
6449 : : * overwritten with newrel's OID during storing.)
6450 : : */
6451 : 67479 : newslot->tts_tableOid = RelationGetRelid(oldrel);
6452 : :
6453 : : /*
6454 : : * Process supplied expressions to replace selected columns.
6455 : : *
6456 : : * First, evaluate expressions whose inputs come from the old
6457 : : * tuple.
6458 : : */
6459 : 67479 : econtext->ecxt_scantuple = oldslot;
6460 : :
6461 [ + + + + : 137950 : foreach(l, tab->newvals)
+ + ]
6462 : : {
6463 : 70479 : NewColumnValue *ex = lfirst(l);
6464 : :
6465 [ + + ]: 70479 : if (ex->is_generated)
6466 : 284 : continue;
6467 : :
6468 : 70195 : newslot->tts_values[ex->attnum - 1]
6469 : 70187 : = ExecEvalExpr(ex->exprstate,
6470 : : econtext,
6471 : 70195 : &newslot->tts_isnull[ex->attnum - 1]);
6472 : : }
6473 : :
6474 : 67471 : ExecStoreVirtualTuple(newslot);
6475 : :
6476 : : /*
6477 : : * Now, evaluate any expressions whose inputs come from the
6478 : : * new tuple. We assume these columns won't reference each
6479 : : * other, so that there's no ordering dependency.
6480 : : */
6481 : 67471 : econtext->ecxt_scantuple = newslot;
6482 : :
6483 [ + + + + : 137942 : foreach(l, tab->newvals)
+ + ]
6484 : : {
6485 : 70471 : NewColumnValue *ex = lfirst(l);
6486 : :
6487 [ + + ]: 70471 : if (!ex->is_generated)
6488 : 70187 : continue;
6489 : :
6490 : 284 : newslot->tts_values[ex->attnum - 1]
6491 : 284 : = ExecEvalExpr(ex->exprstate,
6492 : : econtext,
6493 : 284 : &newslot->tts_isnull[ex->attnum - 1]);
6494 : : }
6495 : :
6496 : 67471 : insertslot = newslot;
6497 : : }
6498 : : else
6499 : : {
6500 : : /*
6501 : : * If there's no rewrite, old and new table are guaranteed to
6502 : : * have the same AM, so we can just use the old slot to verify
6503 : : * new constraints etc.
6504 : : */
6505 : 416733 : insertslot = oldslot;
6506 : : }
6507 : :
6508 : : /* Now check any constraints on the possibly-changed tuple */
6509 : 484204 : econtext->ecxt_scantuple = insertslot;
6510 : :
6511 [ + + + + : 2579274 : foreach_int(attn, notnull_attrs)
+ + ]
6512 : : {
6513 [ + + ]: 1611042 : if (slot_attisnull(insertslot, attn))
6514 : : {
6515 : 88 : Form_pg_attribute attr = TupleDescAttr(newTupDesc, attn - 1);
6516 : :
6517 [ + - ]: 88 : ereport(ERROR,
6518 : : (errcode(ERRCODE_NOT_NULL_VIOLATION),
6519 : : errmsg("column \"%s\" of relation \"%s\" contains null values",
6520 : : NameStr(attr->attname),
6521 : : RelationGetRelationName(oldrel)),
6522 : : errtablecol(oldrel, attn)));
6523 : : }
6524 : : }
6525 : :
6526 [ + + ]: 484116 : if (notnull_virtual_attrs != NIL)
6527 : : {
6528 : : AttrNumber attnum;
6529 : :
6530 : 60 : attnum = ExecRelGenVirtualNotNull(rInfo, insertslot,
6531 : : estate,
6532 : : notnull_virtual_attrs);
6533 [ + + ]: 60 : if (attnum != InvalidAttrNumber)
6534 : : {
6535 : 20 : Form_pg_attribute attr = TupleDescAttr(newTupDesc, attnum - 1);
6536 : :
6537 [ + - ]: 20 : ereport(ERROR,
6538 : : errcode(ERRCODE_NOT_NULL_VIOLATION),
6539 : : errmsg("column \"%s\" of relation \"%s\" contains null values",
6540 : : NameStr(attr->attname),
6541 : : RelationGetRelationName(oldrel)),
6542 : : errtablecol(oldrel, attnum));
6543 : : }
6544 : : }
6545 : :
6546 [ + + + + : 489321 : foreach(l, tab->constraints)
+ + ]
6547 : : {
6548 : 5345 : NewConstraint *con = lfirst(l);
6549 : :
6550 [ + + - ]: 5345 : switch (con->contype)
6551 : : {
6552 : 5279 : case CONSTR_CHECK:
6553 [ + + ]: 5279 : if (!ExecCheck(con->qualstate, econtext))
6554 [ + - ]: 120 : ereport(ERROR,
6555 : : (errcode(ERRCODE_CHECK_VIOLATION),
6556 : : errmsg("check constraint \"%s\" of relation \"%s\" is violated by some row",
6557 : : con->name,
6558 : : RelationGetRelationName(oldrel)),
6559 : : errtableconstraint(oldrel, con->name)));
6560 : 5159 : break;
6561 : 66 : case CONSTR_NOTNULL:
6562 : : case CONSTR_FOREIGN:
6563 : : /* Nothing to do here */
6564 : 66 : break;
6565 : 0 : default:
6566 [ # # ]: 0 : elog(ERROR, "unrecognized constraint type: %d",
6567 : : (int) con->contype);
6568 : : }
6569 : : }
6570 : :
6571 [ + + + + ]: 483976 : if (partqualstate && !ExecCheck(partqualstate, econtext))
6572 : : {
6573 [ + + ]: 49 : if (tab->validate_default)
6574 [ + - ]: 17 : ereport(ERROR,
6575 : : (errcode(ERRCODE_CHECK_VIOLATION),
6576 : : errmsg("updated partition constraint for default partition \"%s\" would be violated by some row",
6577 : : RelationGetRelationName(oldrel)),
6578 : : errtable(oldrel)));
6579 : : else
6580 [ + - ]: 32 : ereport(ERROR,
6581 : : (errcode(ERRCODE_CHECK_VIOLATION),
6582 : : errmsg("partition constraint of relation \"%s\" is violated by some row",
6583 : : RelationGetRelationName(oldrel)),
6584 : : errtable(oldrel)));
6585 : : }
6586 : :
6587 : : /* Write the tuple out to the new relation */
6588 [ + + ]: 483927 : if (newrel)
6589 : 67427 : table_tuple_insert(newrel, insertslot, mycid,
6590 : : ti_options, bistate);
6591 : :
6592 : 483927 : ResetExprContext(econtext);
6593 : :
6594 [ - + ]: 483927 : CHECK_FOR_INTERRUPTS();
6595 : : }
6596 : :
6597 : 3136 : MemoryContextSwitchTo(oldCxt);
6598 : 3136 : table_endscan(scan);
6599 : 3136 : UnregisterSnapshot(snapshot);
6600 : :
6601 : 3136 : ExecDropSingleTupleTableSlot(oldslot);
6602 [ + + ]: 3136 : if (newslot)
6603 : 728 : ExecDropSingleTupleTableSlot(newslot);
6604 : : }
6605 : :
6606 : 3857 : FreeExecutorState(estate);
6607 : :
6608 : 3857 : table_close(oldrel, NoLock);
6609 [ + + ]: 3857 : if (newrel)
6610 : : {
6611 : 728 : FreeBulkInsertState(bistate);
6612 : :
6613 : 728 : table_finish_bulk_insert(newrel, ti_options);
6614 : :
6615 : 728 : table_close(newrel, NoLock);
6616 : : }
6617 : 3857 : }
6618 : :
6619 : : /*
6620 : : * ATGetQueueEntry: find or create an entry in the ALTER TABLE work queue
6621 : : */
6622 : : static AlteredTableInfo *
6623 : 27493 : ATGetQueueEntry(List **wqueue, Relation rel)
6624 : : {
6625 : 27493 : Oid relid = RelationGetRelid(rel);
6626 : : AlteredTableInfo *tab;
6627 : : ListCell *ltab;
6628 : :
6629 [ + + + + : 34214 : foreach(ltab, *wqueue)
+ + ]
6630 : : {
6631 : 10200 : tab = (AlteredTableInfo *) lfirst(ltab);
6632 [ + + ]: 10200 : if (tab->relid == relid)
6633 : 3479 : return tab;
6634 : : }
6635 : :
6636 : : /*
6637 : : * Not there, so add it. Note that we make a copy of the relation's
6638 : : * existing descriptor before anything interesting can happen to it.
6639 : : */
6640 : 24014 : tab = palloc0_object(AlteredTableInfo);
6641 : 24014 : tab->relid = relid;
6642 : 24014 : tab->rel = NULL; /* set later */
6643 : 24014 : tab->relkind = rel->rd_rel->relkind;
6644 : 24014 : tab->oldDesc = CreateTupleDescCopyConstr(RelationGetDescr(rel));
6645 : 24014 : tab->newAccessMethod = InvalidOid;
6646 : 24014 : tab->chgAccessMethod = false;
6647 : 24014 : tab->newTableSpace = InvalidOid;
6648 : 24014 : tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
6649 : 24014 : tab->chgPersistence = false;
6650 : :
6651 : 24014 : *wqueue = lappend(*wqueue, tab);
6652 : :
6653 : 24014 : return tab;
6654 : : }
6655 : :
6656 : : static const char *
6657 : 69 : alter_table_type_to_string(AlterTableType cmdtype)
6658 : : {
6659 [ - - + + : 69 : switch (cmdtype)
- - - + -
- - + - -
+ - - - -
- - + + -
+ + - - +
- - - - -
- - - - -
- - - - +
+ - - - -
- - - - +
+ + - - -
- - ]
6660 : : {
6661 : 0 : case AT_AddColumn:
6662 : : case AT_AddColumnToView:
6663 : 0 : return "ADD COLUMN";
6664 : 0 : case AT_ColumnDefault:
6665 : : case AT_CookedColumnDefault:
6666 : 0 : return "ALTER COLUMN ... SET DEFAULT";
6667 : 4 : case AT_DropNotNull:
6668 : 4 : return "ALTER COLUMN ... DROP NOT NULL";
6669 : 4 : case AT_SetNotNull:
6670 : 4 : return "ALTER COLUMN ... SET NOT NULL";
6671 : 0 : case AT_SetExpression:
6672 : 0 : return "ALTER COLUMN ... SET EXPRESSION";
6673 : 0 : case AT_DropExpression:
6674 : 0 : return "ALTER COLUMN ... DROP EXPRESSION";
6675 : 0 : case AT_SetStatistics:
6676 : 0 : return "ALTER COLUMN ... SET STATISTICS";
6677 : 8 : case AT_SetOptions:
6678 : 8 : return "ALTER COLUMN ... SET";
6679 : 0 : case AT_ResetOptions:
6680 : 0 : return "ALTER COLUMN ... RESET";
6681 : 0 : case AT_SetStorage:
6682 : 0 : return "ALTER COLUMN ... SET STORAGE";
6683 : 0 : case AT_SetCompression:
6684 : 0 : return "ALTER COLUMN ... SET COMPRESSION";
6685 : 4 : case AT_DropColumn:
6686 : 4 : return "DROP COLUMN";
6687 : 0 : case AT_AddIndex:
6688 : : case AT_ReAddIndex:
6689 : 0 : return NULL; /* not real grammar */
6690 : 0 : case AT_AddConstraint:
6691 : : case AT_ReAddConstraint:
6692 : : case AT_ReAddDomainConstraint:
6693 : : case AT_AddIndexConstraint:
6694 : 0 : return "ADD CONSTRAINT";
6695 : 4 : case AT_AlterConstraint:
6696 : 4 : return "ALTER CONSTRAINT";
6697 : 0 : case AT_ValidateConstraint:
6698 : 0 : return "VALIDATE CONSTRAINT";
6699 : 0 : case AT_DropConstraint:
6700 : 0 : return "DROP CONSTRAINT";
6701 : 0 : case AT_ReAddComment:
6702 : 0 : return NULL; /* not real grammar */
6703 : 0 : case AT_AlterColumnType:
6704 : 0 : return "ALTER COLUMN ... SET DATA TYPE";
6705 : 0 : case AT_AlterColumnGenericOptions:
6706 : 0 : return "ALTER COLUMN ... OPTIONS";
6707 : 0 : case AT_ChangeOwner:
6708 : 0 : return "OWNER TO";
6709 : 4 : case AT_ClusterOn:
6710 : 4 : return "CLUSTER ON";
6711 : 4 : case AT_DropCluster:
6712 : 4 : return "SET WITHOUT CLUSTER";
6713 : 0 : case AT_SetAccessMethod:
6714 : 0 : return "SET ACCESS METHOD";
6715 : 4 : case AT_SetLogged:
6716 : 4 : return "SET LOGGED";
6717 : 4 : case AT_SetUnLogged:
6718 : 4 : return "SET UNLOGGED";
6719 : 0 : case AT_DropOids:
6720 : 0 : return "SET WITHOUT OIDS";
6721 : 0 : case AT_SetTableSpace:
6722 : 0 : return "SET TABLESPACE";
6723 : 1 : case AT_SetRelOptions:
6724 : 1 : return "SET";
6725 : 0 : case AT_ResetRelOptions:
6726 : 0 : return "RESET";
6727 : 0 : case AT_ReplaceRelOptions:
6728 : 0 : return NULL; /* not real grammar */
6729 : 0 : case AT_EnableTrig:
6730 : 0 : return "ENABLE TRIGGER";
6731 : 0 : case AT_EnableAlwaysTrig:
6732 : 0 : return "ENABLE ALWAYS TRIGGER";
6733 : 0 : case AT_EnableReplicaTrig:
6734 : 0 : return "ENABLE REPLICA TRIGGER";
6735 : 0 : case AT_DisableTrig:
6736 : 0 : return "DISABLE TRIGGER";
6737 : 0 : case AT_EnableTrigAll:
6738 : 0 : return "ENABLE TRIGGER ALL";
6739 : 0 : case AT_DisableTrigAll:
6740 : 0 : return "DISABLE TRIGGER ALL";
6741 : 0 : case AT_EnableTrigUser:
6742 : 0 : return "ENABLE TRIGGER USER";
6743 : 0 : case AT_DisableTrigUser:
6744 : 0 : return "DISABLE TRIGGER USER";
6745 : 0 : case AT_EnableRule:
6746 : 0 : return "ENABLE RULE";
6747 : 0 : case AT_EnableAlwaysRule:
6748 : 0 : return "ENABLE ALWAYS RULE";
6749 : 0 : case AT_EnableReplicaRule:
6750 : 0 : return "ENABLE REPLICA RULE";
6751 : 0 : case AT_DisableRule:
6752 : 0 : return "DISABLE RULE";
6753 : 4 : case AT_AddInherit:
6754 : 4 : return "INHERIT";
6755 : 4 : case AT_DropInherit:
6756 : 4 : return "NO INHERIT";
6757 : 0 : case AT_AddOf:
6758 : 0 : return "OF";
6759 : 0 : case AT_DropOf:
6760 : 0 : return "NOT OF";
6761 : 0 : case AT_ReplicaIdentity:
6762 : 0 : return "REPLICA IDENTITY";
6763 : 0 : case AT_EnableRowSecurity:
6764 : 0 : return "ENABLE ROW SECURITY";
6765 : 0 : case AT_DisableRowSecurity:
6766 : 0 : return "DISABLE ROW SECURITY";
6767 : 0 : case AT_ForceRowSecurity:
6768 : 0 : return "FORCE ROW SECURITY";
6769 : 0 : case AT_NoForceRowSecurity:
6770 : 0 : return "NO FORCE ROW SECURITY";
6771 : 0 : case AT_GenericOptions:
6772 : 0 : return "OPTIONS";
6773 : 4 : case AT_AttachPartition:
6774 : 4 : return "ATTACH PARTITION";
6775 : 12 : case AT_DetachPartition:
6776 : 12 : return "DETACH PARTITION";
6777 : 4 : case AT_DetachPartitionFinalize:
6778 : 4 : return "DETACH PARTITION ... FINALIZE";
6779 : 0 : case AT_AddIdentity:
6780 : 0 : return "ALTER COLUMN ... ADD IDENTITY";
6781 : 0 : case AT_SetIdentity:
6782 : 0 : return "ALTER COLUMN ... SET";
6783 : 0 : case AT_DropIdentity:
6784 : 0 : return "ALTER COLUMN ... DROP IDENTITY";
6785 : 0 : case AT_ReAddStatistics:
6786 : 0 : return NULL; /* not real grammar */
6787 : : }
6788 : :
6789 : 0 : return NULL;
6790 : : }
6791 : :
6792 : : /*
6793 : : * ATSimplePermissions
6794 : : *
6795 : : * - Ensure that it is a relation (or possibly a view)
6796 : : * - Ensure this user is the owner
6797 : : * - Ensure that it is not a system table
6798 : : */
6799 : : static void
6800 : 25019 : ATSimplePermissions(AlterTableType cmdtype, Relation rel, int allowed_targets)
6801 : : {
6802 : : int actual_target;
6803 : :
6804 [ + + + + : 25019 : switch (rel->rd_rel->relkind)
+ + + + +
+ ]
6805 : : {
6806 : 19762 : case RELKIND_RELATION:
6807 : 19762 : actual_target = ATT_TABLE;
6808 : 19762 : break;
6809 : 3732 : case RELKIND_PARTITIONED_TABLE:
6810 : 3732 : actual_target = ATT_PARTITIONED_TABLE;
6811 : 3732 : break;
6812 : 280 : case RELKIND_VIEW:
6813 : 280 : actual_target = ATT_VIEW;
6814 : 280 : break;
6815 : 29 : case RELKIND_MATVIEW:
6816 : 29 : actual_target = ATT_MATVIEW;
6817 : 29 : break;
6818 : 140 : case RELKIND_INDEX:
6819 : 140 : actual_target = ATT_INDEX;
6820 : 140 : break;
6821 : 314 : case RELKIND_PARTITIONED_INDEX:
6822 : 314 : actual_target = ATT_PARTITIONED_INDEX;
6823 : 314 : break;
6824 : 149 : case RELKIND_COMPOSITE_TYPE:
6825 : 149 : actual_target = ATT_COMPOSITE_TYPE;
6826 : 149 : break;
6827 : 596 : case RELKIND_FOREIGN_TABLE:
6828 : 596 : actual_target = ATT_FOREIGN_TABLE;
6829 : 596 : break;
6830 : 16 : case RELKIND_SEQUENCE:
6831 : 16 : actual_target = ATT_SEQUENCE;
6832 : 16 : break;
6833 : 1 : default:
6834 : 1 : actual_target = 0;
6835 : 1 : break;
6836 : : }
6837 : :
6838 : : /* Wrong target type? */
6839 [ + + ]: 25019 : if ((actual_target & allowed_targets) == 0)
6840 : : {
6841 : 69 : const char *action_str = alter_table_type_to_string(cmdtype);
6842 : :
6843 [ + - ]: 69 : if (action_str)
6844 [ + - ]: 69 : ereport(ERROR,
6845 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6846 : : /* translator: %s is a group of some SQL keywords */
6847 : : errmsg("ALTER action %s cannot be performed on relation \"%s\"",
6848 : : action_str, RelationGetRelationName(rel)),
6849 : : errdetail_relkind_not_supported(rel->rd_rel->relkind)));
6850 : : else
6851 : : /* internal error? */
6852 [ # # ]: 0 : elog(ERROR, "invalid ALTER action attempted on relation \"%s\"",
6853 : : RelationGetRelationName(rel));
6854 : : }
6855 : :
6856 : : /* Permissions checks */
6857 [ + + ]: 24950 : if (!object_ownercheck(RelationRelationId, RelationGetRelid(rel), GetUserId()))
6858 : 8 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(rel->rd_rel->relkind),
6859 : 8 : RelationGetRelationName(rel));
6860 : :
6861 : : /*
6862 : : * Conflict log tables are used internally for logical replication
6863 : : * conflict logging and should not be altered directly, as it could
6864 : : * disrupt conflict logging. Direct ALTER commands are already rejected
6865 : : * during relation lookup in RangeVarCallbackForAlterRelation(), and
6866 : : * AlterTableMoveAll() skips these tables, so a conflict log table does
6867 : : * not normally reach here; this check guards any internal caller that
6868 : : * arrives via AlterTableInternal().
6869 : : */
6870 [ - + ]: 24942 : if (IsConflictLogTableClass(rel->rd_rel))
6871 [ # # ]: 0 : ereport(ERROR,
6872 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6873 : : errmsg("cannot alter conflict log table \"%s\"",
6874 : : RelationGetRelationName(rel)),
6875 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
6876 : :
6877 [ + + - + ]: 24942 : if (!allowSystemTableMods && IsSystemRelation(rel))
6878 [ # # ]: 0 : ereport(ERROR,
6879 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6880 : : errmsg("permission denied: \"%s\" is a system catalog",
6881 : : RelationGetRelationName(rel))));
6882 : 24942 : }
6883 : :
6884 : : /*
6885 : : * ATSimpleRecursion
6886 : : *
6887 : : * Simple table recursion sufficient for most ALTER TABLE operations.
6888 : : * All direct and indirect children are processed in an unspecified order.
6889 : : * Note that if a child inherits from the original table via multiple
6890 : : * inheritance paths, it will be visited just once.
6891 : : */
6892 : : static void
6893 : 1041 : ATSimpleRecursion(List **wqueue, Relation rel,
6894 : : AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode,
6895 : : AlterTableUtilityContext *context)
6896 : : {
6897 : : /*
6898 : : * Propagate to children, if desired and if there are (or might be) any
6899 : : * children.
6900 : : */
6901 [ + + + + ]: 1041 : if (recurse && rel->rd_rel->relhassubclass)
6902 : : {
6903 : 71 : Oid relid = RelationGetRelid(rel);
6904 : : ListCell *child;
6905 : : List *children;
6906 : :
6907 : 71 : children = find_all_inheritors(relid, lockmode, NULL);
6908 : :
6909 : : /*
6910 : : * find_all_inheritors does the recursive search of the inheritance
6911 : : * hierarchy, so all we have to do is process all of the relids in the
6912 : : * list that it returns.
6913 : : */
6914 [ + - + + : 300 : foreach(child, children)
+ + ]
6915 : : {
6916 : 229 : Oid childrelid = lfirst_oid(child);
6917 : : Relation childrel;
6918 : :
6919 [ + + ]: 229 : if (childrelid == relid)
6920 : 71 : continue;
6921 : : /* find_all_inheritors already got lock */
6922 : 158 : childrel = relation_open(childrelid, NoLock);
6923 : 158 : CheckAlterTableIsSafe(childrel);
6924 : 158 : ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode, context);
6925 : 158 : relation_close(childrel, NoLock);
6926 : : }
6927 : : }
6928 : 1041 : }
6929 : :
6930 : : /*
6931 : : * Obtain list of partitions of the given table, locking them all at the given
6932 : : * lockmode and ensuring that they all pass CheckAlterTableIsSafe.
6933 : : *
6934 : : * This function is a no-op if the given relation is not a partitioned table;
6935 : : * in particular, nothing is done if it's a legacy inheritance parent.
6936 : : */
6937 : : static void
6938 : 559 : ATCheckPartitionsNotInUse(Relation rel, LOCKMODE lockmode)
6939 : : {
6940 [ + + ]: 559 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
6941 : : {
6942 : : List *inh;
6943 : : ListCell *cell;
6944 : :
6945 : 121 : inh = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
6946 : : /* first element is the parent rel; must ignore it */
6947 [ + - + + : 398 : for_each_from(cell, inh, 1)
+ + ]
6948 : : {
6949 : : Relation childrel;
6950 : :
6951 : : /* find_all_inheritors already got lock */
6952 : 281 : childrel = table_open(lfirst_oid(cell), NoLock);
6953 : 281 : CheckAlterTableIsSafe(childrel);
6954 : 277 : table_close(childrel, NoLock);
6955 : : }
6956 : 117 : list_free(inh);
6957 : : }
6958 : 555 : }
6959 : :
6960 : : /*
6961 : : * ATTypedTableRecursion
6962 : : *
6963 : : * Propagate ALTER TYPE operations to the typed tables of that type.
6964 : : * Also check the RESTRICT/CASCADE behavior. Given CASCADE, also permit
6965 : : * recursion to inheritance children of the typed tables.
6966 : : */
6967 : : static void
6968 : 133 : ATTypedTableRecursion(List **wqueue, Relation rel, AlterTableCmd *cmd,
6969 : : LOCKMODE lockmode, AlterTableUtilityContext *context)
6970 : : {
6971 : : ListCell *child;
6972 : : List *children;
6973 : :
6974 : : Assert(rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
6975 : :
6976 : 133 : children = find_typed_table_dependencies(rel->rd_rel->reltype,
6977 : 133 : RelationGetRelationName(rel),
6978 : : cmd->behavior);
6979 : :
6980 [ + + + + : 141 : foreach(child, children)
+ + ]
6981 : : {
6982 : 20 : Oid childrelid = lfirst_oid(child);
6983 : : Relation childrel;
6984 : :
6985 : 20 : childrel = relation_open(childrelid, lockmode);
6986 : 20 : CheckAlterTableIsSafe(childrel);
6987 : 20 : ATPrepCmd(wqueue, childrel, cmd, true, true, lockmode, context);
6988 : 20 : relation_close(childrel, NoLock);
6989 : : }
6990 : 121 : }
6991 : :
6992 : :
6993 : : /*
6994 : : * find_composite_type_dependencies
6995 : : *
6996 : : * Check to see if the type "typeOid" is being used as a column in some table
6997 : : * (possibly nested several levels deep in composite types, arrays, etc!).
6998 : : * Eventually, we'd like to propagate the check or rewrite operation
6999 : : * into such tables, but for now, just error out if we find any.
7000 : : *
7001 : : * Caller should provide either the associated relation of a rowtype,
7002 : : * or a type name (not both) for use in the error message, if any.
7003 : : *
7004 : : * Note that "typeOid" is not necessarily a composite type; it could also be
7005 : : * another container type such as an array or range, or a domain over one of
7006 : : * these things. The name of this function is therefore somewhat historical,
7007 : : * but it's not worth changing.
7008 : : *
7009 : : * We assume that functions and views depending on the type are not reasons
7010 : : * to reject the ALTER. (How safe is this really?)
7011 : : */
7012 : : void
7013 : 3350 : find_composite_type_dependencies(Oid typeOid, Relation origRelation,
7014 : : const char *origTypeName)
7015 : : {
7016 : : Relation depRel;
7017 : : ScanKeyData key[2];
7018 : : SysScanDesc depScan;
7019 : : HeapTuple depTup;
7020 : :
7021 : : Assert(OidIsValid(typeOid));
7022 : :
7023 : : /* since this function recurses, it could be driven to stack overflow */
7024 : 3350 : check_stack_depth();
7025 : :
7026 : : /*
7027 : : * We scan pg_depend to find those things that depend on the given type.
7028 : : * (We assume we can ignore refobjsubid for a type.)
7029 : : */
7030 : 3350 : depRel = table_open(DependRelationId, AccessShareLock);
7031 : :
7032 : 3350 : ScanKeyInit(&key[0],
7033 : : Anum_pg_depend_refclassid,
7034 : : BTEqualStrategyNumber, F_OIDEQ,
7035 : : ObjectIdGetDatum(TypeRelationId));
7036 : 3350 : ScanKeyInit(&key[1],
7037 : : Anum_pg_depend_refobjid,
7038 : : BTEqualStrategyNumber, F_OIDEQ,
7039 : : ObjectIdGetDatum(typeOid));
7040 : :
7041 : 3350 : depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
7042 : : NULL, 2, key);
7043 : :
7044 [ + + ]: 5154 : while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
7045 : : {
7046 : 1908 : Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
7047 : : Relation rel;
7048 : : TupleDesc tupleDesc;
7049 : : Form_pg_attribute att;
7050 : :
7051 : : /* Check for directly dependent types */
7052 [ + + ]: 1908 : if (pg_depend->classid == TypeRelationId)
7053 : : {
7054 : : /*
7055 : : * This must be an array, domain, or range containing the given
7056 : : * type, so recursively check for uses of this type. Note that
7057 : : * any error message will mention the original type not the
7058 : : * container; this is intentional.
7059 : : */
7060 : 1630 : find_composite_type_dependencies(pg_depend->objid,
7061 : : origRelation, origTypeName);
7062 : 1614 : continue;
7063 : : }
7064 : :
7065 : : /* Else, ignore dependees that aren't relations */
7066 [ + + ]: 278 : if (pg_depend->classid != RelationRelationId)
7067 : 85 : continue;
7068 : :
7069 : 193 : rel = relation_open(pg_depend->objid, AccessShareLock);
7070 : 193 : tupleDesc = RelationGetDescr(rel);
7071 : :
7072 : : /*
7073 : : * If objsubid identifies a specific column, refer to that in error
7074 : : * messages. Otherwise, search to see if there's a user column of the
7075 : : * type. (We assume system columns are never of interesting types.)
7076 : : * The search is needed because an index containing an expression
7077 : : * column of the target type will just be recorded as a whole-relation
7078 : : * dependency. If we do not find a column of the type, the dependency
7079 : : * must indicate that the type is transiently referenced in an index
7080 : : * expression but not stored on disk, which we assume is OK, just as
7081 : : * we do for references in views. (It could also be that the target
7082 : : * type is embedded in some container type that is stored in an index
7083 : : * column, but the previous recursion should catch such cases.)
7084 : : */
7085 [ + + + - ]: 193 : if (pg_depend->objsubid > 0 && pg_depend->objsubid <= tupleDesc->natts)
7086 : 84 : att = TupleDescAttr(tupleDesc, pg_depend->objsubid - 1);
7087 : : else
7088 : : {
7089 : 109 : att = NULL;
7090 [ + + ]: 286 : for (int attno = 1; attno <= tupleDesc->natts; attno++)
7091 : : {
7092 : 181 : att = TupleDescAttr(tupleDesc, attno - 1);
7093 [ + + + - ]: 181 : if (att->atttypid == typeOid && !att->attisdropped)
7094 : 4 : break;
7095 : 177 : att = NULL;
7096 : : }
7097 [ + + ]: 109 : if (att == NULL)
7098 : : {
7099 : : /* No such column, so assume OK */
7100 : 105 : relation_close(rel, AccessShareLock);
7101 : 105 : continue;
7102 : : }
7103 : : }
7104 : :
7105 : : /*
7106 : : * We definitely should reject if the relation has storage. If it's
7107 : : * partitioned, then perhaps we don't have to reject: if there are
7108 : : * partitions then we'll fail when we find one, else there is no
7109 : : * stored data to worry about. However, it's possible that the type
7110 : : * change would affect conclusions about whether the type is sortable
7111 : : * or hashable and thus (if it's a partitioning column) break the
7112 : : * partitioning rule. For now, reject for partitioned rels too.
7113 : : */
7114 [ + + - + : 88 : if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind) ||
- - - - -
- ]
7115 [ # # # # ]: 0 : RELKIND_HAS_PARTITIONS(rel->rd_rel->relkind))
7116 : : {
7117 [ + + ]: 88 : if (origTypeName)
7118 [ + - ]: 20 : ereport(ERROR,
7119 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7120 : : errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
7121 : : origTypeName,
7122 : : RelationGetRelationName(rel),
7123 : : NameStr(att->attname))));
7124 [ + + ]: 68 : else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
7125 [ + - ]: 12 : ereport(ERROR,
7126 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7127 : : errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
7128 : : RelationGetRelationName(origRelation),
7129 : : RelationGetRelationName(rel),
7130 : : NameStr(att->attname))));
7131 [ + + ]: 56 : else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
7132 [ + - ]: 4 : ereport(ERROR,
7133 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7134 : : errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
7135 : : RelationGetRelationName(origRelation),
7136 : : RelationGetRelationName(rel),
7137 : : NameStr(att->attname))));
7138 : : else
7139 [ + - ]: 52 : ereport(ERROR,
7140 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7141 : : errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
7142 : : RelationGetRelationName(origRelation),
7143 : : RelationGetRelationName(rel),
7144 : : NameStr(att->attname))));
7145 : : }
7146 [ # # ]: 0 : else if (OidIsValid(rel->rd_rel->reltype))
7147 : : {
7148 : : /*
7149 : : * A view or composite type itself isn't a problem, but we must
7150 : : * recursively check for indirect dependencies via its rowtype.
7151 : : */
7152 : 0 : find_composite_type_dependencies(rel->rd_rel->reltype,
7153 : : origRelation, origTypeName);
7154 : : }
7155 : :
7156 : 0 : relation_close(rel, AccessShareLock);
7157 : : }
7158 : :
7159 : 3246 : systable_endscan(depScan);
7160 : :
7161 : 3246 : relation_close(depRel, AccessShareLock);
7162 : 3246 : }
7163 : :
7164 : :
7165 : : /*
7166 : : * find_typed_table_dependencies
7167 : : *
7168 : : * Check to see if a composite type is being used as the type of a
7169 : : * typed table. Abort if any are found and behavior is RESTRICT.
7170 : : * Else return the list of tables.
7171 : : */
7172 : : static List *
7173 : 149 : find_typed_table_dependencies(Oid typeOid, const char *typeName, DropBehavior behavior)
7174 : : {
7175 : : Relation classRel;
7176 : : ScanKeyData key[1];
7177 : : TableScanDesc scan;
7178 : : HeapTuple tuple;
7179 : 149 : List *result = NIL;
7180 : :
7181 : 149 : classRel = table_open(RelationRelationId, AccessShareLock);
7182 : :
7183 : 149 : ScanKeyInit(&key[0],
7184 : : Anum_pg_class_reloftype,
7185 : : BTEqualStrategyNumber, F_OIDEQ,
7186 : : ObjectIdGetDatum(typeOid));
7187 : :
7188 : 149 : scan = table_beginscan_catalog(classRel, 1, key);
7189 : :
7190 [ + + ]: 173 : while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
7191 : : {
7192 : 40 : Form_pg_class classform = (Form_pg_class) GETSTRUCT(tuple);
7193 : :
7194 [ + + ]: 40 : if (behavior == DROP_RESTRICT)
7195 [ + - ]: 16 : ereport(ERROR,
7196 : : (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
7197 : : errmsg("cannot alter type \"%s\" because it is the type of a typed table",
7198 : : typeName),
7199 : : errhint("Use ALTER ... CASCADE to alter the typed tables too.")));
7200 : : else
7201 : 24 : result = lappend_oid(result, classform->oid);
7202 : : }
7203 : :
7204 : 133 : table_endscan(scan);
7205 : 133 : table_close(classRel, AccessShareLock);
7206 : :
7207 : 133 : return result;
7208 : : }
7209 : :
7210 : :
7211 : : /*
7212 : : * check_of_type
7213 : : *
7214 : : * Check whether a type is suitable for CREATE TABLE OF/ALTER TABLE OF. If it
7215 : : * isn't suitable, throw an error. Currently, we require that the type
7216 : : * originated with CREATE TYPE AS. We could support any row type, but doing so
7217 : : * would require handling a number of extra corner cases in the DDL commands.
7218 : : * (Also, allowing domain-over-composite would open up a can of worms about
7219 : : * whether and how the domain's constraints should apply to derived tables.)
7220 : : */
7221 : : void
7222 : 127 : check_of_type(HeapTuple typetuple)
7223 : : {
7224 : 127 : Form_pg_type typ = (Form_pg_type) GETSTRUCT(typetuple);
7225 : 127 : bool typeOk = false;
7226 : :
7227 [ + + ]: 127 : if (typ->typtype == TYPTYPE_COMPOSITE)
7228 : : {
7229 : : Relation typeRelation;
7230 : :
7231 : : Assert(OidIsValid(typ->typrelid));
7232 : 123 : typeRelation = relation_open(typ->typrelid, AccessShareLock);
7233 : 123 : typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
7234 : :
7235 : : /*
7236 : : * Close the parent rel, but keep our AccessShareLock on it until xact
7237 : : * commit. That will prevent someone else from deleting or ALTERing
7238 : : * the type before the typed table creation/conversion commits.
7239 : : */
7240 : 123 : relation_close(typeRelation, NoLock);
7241 : :
7242 [ + + ]: 123 : if (!typeOk)
7243 [ + - ]: 4 : ereport(ERROR,
7244 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7245 : : errmsg("type %s is the row type of another table",
7246 : : format_type_be(typ->oid)),
7247 : : errdetail("A typed table must use a stand-alone composite type created with CREATE TYPE.")));
7248 : : }
7249 : : else
7250 [ + - ]: 4 : ereport(ERROR,
7251 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7252 : : errmsg("type %s is not a composite type",
7253 : : format_type_be(typ->oid))));
7254 : 119 : }
7255 : :
7256 : :
7257 : : /*
7258 : : * ALTER TABLE ADD COLUMN
7259 : : *
7260 : : * Adds an additional attribute to a relation making the assumption that
7261 : : * CHECK, NOT NULL, and FOREIGN KEY constraints will be removed from the
7262 : : * AT_AddColumn AlterTableCmd by parse_utilcmd.c and added as independent
7263 : : * AlterTableCmd's.
7264 : : *
7265 : : * ADD COLUMN cannot use the normal ALTER TABLE recursion mechanism, because we
7266 : : * have to decide at runtime whether to recurse or not depending on whether we
7267 : : * actually add a column or merely merge with an existing column. (We can't
7268 : : * check this in a static pre-pass because it won't handle multiple inheritance
7269 : : * situations correctly.)
7270 : : */
7271 : : static void
7272 : 1591 : ATPrepAddColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
7273 : : bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode,
7274 : : AlterTableUtilityContext *context)
7275 : : {
7276 [ + + + + ]: 1591 : if (rel->rd_rel->reloftype && !recursing)
7277 [ + - ]: 4 : ereport(ERROR,
7278 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7279 : : errmsg("cannot add column to typed table")));
7280 : :
7281 [ + + ]: 1587 : if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
7282 : 42 : ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
7283 : :
7284 [ + + + + ]: 1583 : if (recurse && !is_view)
7285 : 1508 : cmd->recurse = true;
7286 : 1583 : }
7287 : :
7288 : : /*
7289 : : * Add a column to a table. The return value is the address of the
7290 : : * new column in the parent relation.
7291 : : *
7292 : : * cmd is pass-by-ref so that we can replace it with the parse-transformed
7293 : : * copy (but that happens only after we check for IF NOT EXISTS).
7294 : : */
7295 : : static ObjectAddress
7296 : 2093 : ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel,
7297 : : AlterTableCmd **cmd, bool recurse, bool recursing,
7298 : : LOCKMODE lockmode, AlterTablePass cur_pass,
7299 : : AlterTableUtilityContext *context)
7300 : : {
7301 : 2093 : Oid myrelid = RelationGetRelid(rel);
7302 : 2093 : ColumnDef *colDef = castNode(ColumnDef, (*cmd)->def);
7303 : 2093 : bool if_not_exists = (*cmd)->missing_ok;
7304 : : Relation pgclass,
7305 : : attrdesc;
7306 : : HeapTuple reltup;
7307 : : Form_pg_class relform;
7308 : : Form_pg_attribute attribute;
7309 : : int newattnum;
7310 : : char relkind;
7311 : : Expr *defval;
7312 : : List *children;
7313 : : ListCell *child;
7314 : : AlterTableCmd *childcmd;
7315 : : ObjectAddress address;
7316 : : TupleDesc tupdesc;
7317 : :
7318 : : /* since this function recurses, it could be driven to stack overflow */
7319 : 2093 : check_stack_depth();
7320 : :
7321 : : /* At top level, permission check was done in ATPrepCmd, else do it */
7322 [ + + ]: 2093 : if (recursing)
7323 : 514 : ATSimplePermissions((*cmd)->subtype, rel,
7324 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
7325 : :
7326 [ + + + + ]: 2093 : if (rel->rd_rel->relispartition && !recursing)
7327 [ + - ]: 8 : ereport(ERROR,
7328 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7329 : : errmsg("cannot add column to a partition")));
7330 : :
7331 : 2085 : attrdesc = table_open(AttributeRelationId, RowExclusiveLock);
7332 : :
7333 : : /*
7334 : : * Are we adding the column to a recursion child? If so, check whether to
7335 : : * merge with an existing definition for the column. If we do merge, we
7336 : : * must not recurse. Children will already have the column, and recursing
7337 : : * into them would mess up attinhcount.
7338 : : */
7339 [ + + ]: 2085 : if (colDef->inhcount > 0)
7340 : : {
7341 : : HeapTuple tuple;
7342 : :
7343 : : /* Does child already have a column by this name? */
7344 : 514 : tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
7345 [ + + ]: 514 : if (HeapTupleIsValid(tuple))
7346 : : {
7347 : 40 : Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
7348 : : Oid ctypeId;
7349 : : int32 ctypmod;
7350 : : Oid ccollid;
7351 : :
7352 : : /* Child column must match on type, typmod, and collation */
7353 : 40 : typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
7354 [ + - ]: 40 : if (ctypeId != childatt->atttypid ||
7355 [ - + ]: 40 : ctypmod != childatt->atttypmod)
7356 [ # # ]: 0 : ereport(ERROR,
7357 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
7358 : : errmsg("child table \"%s\" has different type for column \"%s\"",
7359 : : RelationGetRelationName(rel), colDef->colname)));
7360 : 40 : ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
7361 [ - + ]: 40 : if (ccollid != childatt->attcollation)
7362 [ # # ]: 0 : ereport(ERROR,
7363 : : (errcode(ERRCODE_COLLATION_MISMATCH),
7364 : : errmsg("child table \"%s\" has different collation for column \"%s\"",
7365 : : RelationGetRelationName(rel), colDef->colname),
7366 : : errdetail("\"%s\" versus \"%s\"",
7367 : : get_collation_name(ccollid),
7368 : : get_collation_name(childatt->attcollation))));
7369 : :
7370 : : /* Bump the existing child att's inhcount */
7371 [ - + ]: 40 : if (pg_add_s16_overflow(childatt->attinhcount, 1,
7372 : : &childatt->attinhcount))
7373 [ # # ]: 0 : ereport(ERROR,
7374 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
7375 : : errmsg("too many inheritance parents"));
7376 : 40 : CatalogTupleUpdate(attrdesc, &tuple->t_self, tuple);
7377 : :
7378 : 40 : heap_freetuple(tuple);
7379 : :
7380 : : /* Inform the user about the merge */
7381 [ + - ]: 40 : ereport(NOTICE,
7382 : : (errmsg("merging definition of column \"%s\" for child \"%s\"",
7383 : : colDef->colname, RelationGetRelationName(rel))));
7384 : :
7385 : 40 : table_close(attrdesc, RowExclusiveLock);
7386 : :
7387 : : /* Make the child column change visible */
7388 : 40 : CommandCounterIncrement();
7389 : :
7390 : 40 : return InvalidObjectAddress;
7391 : : }
7392 : : }
7393 : :
7394 : : /* skip if the name already exists and if_not_exists is true */
7395 [ + + ]: 2045 : if (!check_for_column_name_collision(rel, colDef->colname, if_not_exists))
7396 : : {
7397 : 44 : table_close(attrdesc, RowExclusiveLock);
7398 : 44 : return InvalidObjectAddress;
7399 : : }
7400 : :
7401 : : /*
7402 : : * Okay, we need to add the column, so go ahead and do parse
7403 : : * transformation. This can result in queueing up, or even immediately
7404 : : * executing, subsidiary operations (such as creation of unique indexes);
7405 : : * so we mustn't do it until we have made the if_not_exists check.
7406 : : *
7407 : : * When recursing, the command was already transformed and we needn't do
7408 : : * so again. Also, if context isn't given we can't transform. (That
7409 : : * currently happens only for AT_AddColumnToView; we expect that view.c
7410 : : * passed us a ColumnDef that doesn't need work.)
7411 : : */
7412 [ + + + + ]: 1981 : if (context != NULL && !recursing)
7413 : : {
7414 : 1486 : *cmd = ATParseTransformCmd(wqueue, tab, rel, *cmd, recurse, lockmode,
7415 : : cur_pass, context);
7416 : : Assert(*cmd != NULL);
7417 : 1482 : colDef = castNode(ColumnDef, (*cmd)->def);
7418 : : }
7419 : :
7420 : : /*
7421 : : * Regular inheritance children are independent enough not to inherit the
7422 : : * identity column from parent hence cannot recursively add identity
7423 : : * column if the table has inheritance children.
7424 : : *
7425 : : * Partitions, on the other hand, are integral part of a partitioned table
7426 : : * and inherit identity column. Hence propagate identity column down the
7427 : : * partition hierarchy.
7428 : : */
7429 [ + + + - ]: 1977 : if (colDef->identity &&
7430 : 36 : recurse &&
7431 [ + + + + ]: 68 : rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE &&
7432 : 32 : find_inheritance_children(myrelid, NoLock) != NIL)
7433 [ + - ]: 4 : ereport(ERROR,
7434 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7435 : : errmsg("cannot recursively add identity column to table that has child tables")));
7436 : :
7437 : 1973 : pgclass = table_open(RelationRelationId, RowExclusiveLock);
7438 : :
7439 : 1973 : reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
7440 [ - + ]: 1973 : if (!HeapTupleIsValid(reltup))
7441 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", myrelid);
7442 : 1973 : relform = (Form_pg_class) GETSTRUCT(reltup);
7443 : 1973 : relkind = relform->relkind;
7444 : :
7445 : : /* Determine the new attribute's number */
7446 : 1973 : newattnum = relform->relnatts + 1;
7447 [ - + ]: 1973 : if (newattnum > MaxHeapAttributeNumber)
7448 [ # # ]: 0 : ereport(ERROR,
7449 : : (errcode(ERRCODE_TOO_MANY_COLUMNS),
7450 : : errmsg("tables can have at most %d columns",
7451 : : MaxHeapAttributeNumber)));
7452 : :
7453 : : /*
7454 : : * Construct new attribute's pg_attribute entry.
7455 : : */
7456 : 1973 : tupdesc = BuildDescForRelation(list_make1(colDef));
7457 : :
7458 : 1965 : attribute = TupleDescAttr(tupdesc, 0);
7459 : :
7460 : : /* Fix up attribute number */
7461 : 1965 : attribute->attnum = newattnum;
7462 : :
7463 : : /* make sure datatype is legal for a column */
7464 : 3930 : CheckAttributeType(NameStr(attribute->attname), attribute->atttypid, attribute->attcollation,
7465 : 1965 : list_make1_oid(rel->rd_rel->reltype),
7466 [ + + ]: 1965 : (attribute->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL ? CHKATYPE_IS_VIRTUAL : 0));
7467 : :
7468 : 1937 : InsertPgAttributeTuples(attrdesc, tupdesc, myrelid, NULL, NULL);
7469 : :
7470 : 1937 : table_close(attrdesc, RowExclusiveLock);
7471 : :
7472 : : /*
7473 : : * Update pg_class tuple as appropriate
7474 : : */
7475 : 1937 : relform->relnatts = newattnum;
7476 : :
7477 : 1937 : CatalogTupleUpdate(pgclass, &reltup->t_self, reltup);
7478 : :
7479 : 1937 : heap_freetuple(reltup);
7480 : :
7481 : : /* Post creation hook for new attribute */
7482 [ - + ]: 1937 : InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
7483 : :
7484 : 1937 : table_close(pgclass, RowExclusiveLock);
7485 : :
7486 : : /* Make the attribute's catalog entry visible */
7487 : 1937 : CommandCounterIncrement();
7488 : :
7489 : : /*
7490 : : * Store the DEFAULT, if any, in the catalogs
7491 : : */
7492 [ + + ]: 1937 : if (colDef->raw_default)
7493 : : {
7494 : : RawColumnDefault *rawEnt;
7495 : :
7496 : 759 : rawEnt = palloc_object(RawColumnDefault);
7497 : 759 : rawEnt->attnum = attribute->attnum;
7498 : 759 : rawEnt->raw_default = copyObject(colDef->raw_default);
7499 : 759 : rawEnt->generated = colDef->generated;
7500 : :
7501 : : /*
7502 : : * This function is intended for CREATE TABLE, so it processes a
7503 : : * _list_ of defaults, but we just do one.
7504 : : */
7505 : 759 : AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
7506 : : false, true, false, NULL);
7507 : :
7508 : : /* Make the additional catalog changes visible */
7509 : 671 : CommandCounterIncrement();
7510 : : }
7511 : :
7512 : : /*
7513 : : * Tell Phase 3 to fill in the default expression, if there is one.
7514 : : *
7515 : : * If there is no default, Phase 3 doesn't have to do anything, because
7516 : : * that effectively means that the default is NULL. The heap tuple access
7517 : : * routines always check for attnum > # of attributes in tuple, and return
7518 : : * NULL if so, so without any modification of the tuple data we will get
7519 : : * the effect of NULL values in the new column.
7520 : : *
7521 : : * An exception occurs when the new column is of a domain type: the domain
7522 : : * might have a not-null constraint, or a check constraint that indirectly
7523 : : * rejects nulls. If there are any domain constraints then we construct
7524 : : * an explicit NULL default value that will be passed through
7525 : : * CoerceToDomain processing. (This is a tad inefficient, since it causes
7526 : : * rewriting the table which we really wouldn't have to do; but we do it
7527 : : * to preserve the historical behavior that such a failure will be raised
7528 : : * only if the table currently contains some rows.)
7529 : : *
7530 : : * Note: we use build_column_default, and not just the cooked default
7531 : : * returned by AddRelationNewConstraints, so that the right thing happens
7532 : : * when a datatype's default applies.
7533 : : *
7534 : : * Note: it might seem that this should happen at the end of Phase 2, so
7535 : : * that the effects of subsequent subcommands can be taken into account.
7536 : : * It's intentional that we do it now, though. The new column should be
7537 : : * filled according to what is said in the ADD COLUMN subcommand, so that
7538 : : * the effects are the same as if this subcommand had been run by itself
7539 : : * and the later subcommands had been issued in new ALTER TABLE commands.
7540 : : *
7541 : : * We can skip this entirely for relations without storage, since Phase 3
7542 : : * is certainly not going to touch them.
7543 : : */
7544 [ + + + - : 1849 : if (RELKIND_HAS_STORAGE(relkind))
+ - + - -
+ ]
7545 : : {
7546 : : bool has_domain_constraints;
7547 : 1579 : bool has_missing = false;
7548 : :
7549 : : /*
7550 : : * For an identity column, we can't use build_column_default(),
7551 : : * because the sequence ownership isn't set yet. So do it manually.
7552 : : */
7553 [ + + ]: 1579 : if (colDef->identity)
7554 : : {
7555 : 28 : NextValueExpr *nve = makeNode(NextValueExpr);
7556 : :
7557 : 28 : nve->seqid = RangeVarGetRelid(colDef->identitySequence, NoLock, false);
7558 : 28 : nve->typeId = attribute->atttypid;
7559 : :
7560 : 28 : defval = (Expr *) nve;
7561 : : }
7562 : : else
7563 : 1551 : defval = (Expr *) build_column_default(rel, attribute->attnum);
7564 : :
7565 : : /* Build CoerceToDomain(NULL) expression if needed */
7566 : 1579 : has_domain_constraints = DomainHasConstraints(attribute->atttypid, NULL);
7567 [ + + + + ]: 1579 : if (!defval && has_domain_constraints)
7568 : : {
7569 : : Oid baseTypeId;
7570 : : int32 baseTypeMod;
7571 : : Oid baseTypeColl;
7572 : :
7573 : 4 : baseTypeMod = attribute->atttypmod;
7574 : 4 : baseTypeId = getBaseTypeAndTypmod(attribute->atttypid, &baseTypeMod);
7575 : 4 : baseTypeColl = get_typcollation(baseTypeId);
7576 : 4 : defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
7577 : 4 : defval = (Expr *) coerce_to_target_type(NULL,
7578 : : (Node *) defval,
7579 : : baseTypeId,
7580 : : attribute->atttypid,
7581 : : attribute->atttypmod,
7582 : : COERCION_ASSIGNMENT,
7583 : : COERCE_IMPLICIT_CAST,
7584 : : -1);
7585 [ - + ]: 4 : if (defval == NULL) /* should not happen */
7586 [ # # ]: 0 : elog(ERROR, "failed to coerce base type to domain");
7587 : : }
7588 : :
7589 [ + + ]: 1579 : if (defval)
7590 : : {
7591 : : NewColumnValue *newval;
7592 : :
7593 : : /* Prepare defval for execution, either here or in Phase 3 */
7594 : 608 : defval = expression_planner(defval);
7595 : :
7596 : : /* Add the new default to the newvals list */
7597 : 608 : newval = palloc0_object(NewColumnValue);
7598 : 608 : newval->attnum = attribute->attnum;
7599 : 608 : newval->expr = defval;
7600 : 608 : newval->is_generated = (colDef->generated != '\0');
7601 : :
7602 : 608 : tab->newvals = lappend(tab->newvals, newval);
7603 : :
7604 : : /*
7605 : : * Attempt to skip a complete table rewrite by storing the
7606 : : * specified DEFAULT value outside of the heap. This is only
7607 : : * allowed for plain relations and non-generated columns, and the
7608 : : * default expression can't be volatile (stable is OK). Note that
7609 : : * contain_volatile_functions deems CoerceToDomain immutable, but
7610 : : * here we consider that coercion to a domain with constraints is
7611 : : * volatile; else it might fail even when the table is empty.
7612 : : */
7613 [ + - ]: 608 : if (rel->rd_rel->relkind == RELKIND_RELATION &&
7614 [ + + ]: 608 : !colDef->generated &&
7615 [ + + ]: 479 : !has_domain_constraints &&
7616 [ + + ]: 471 : !contain_volatile_functions((Node *) defval))
7617 : 361 : {
7618 : : EState *estate;
7619 : : ExprState *exprState;
7620 : : Datum missingval;
7621 : : bool missingIsNull;
7622 : :
7623 : : /* Evaluate the default expression */
7624 : 361 : estate = CreateExecutorState();
7625 : 361 : exprState = ExecPrepareExpr(defval, estate);
7626 : 361 : missingval = ExecEvalExpr(exprState,
7627 [ - + ]: 361 : GetPerTupleExprContext(estate),
7628 : : &missingIsNull);
7629 : : /* If it turns out NULL, nothing to do; else store it */
7630 [ + - ]: 361 : if (!missingIsNull)
7631 : : {
7632 : 361 : StoreAttrMissingVal(rel, attribute->attnum, missingval);
7633 : : /* Make the additional catalog change visible */
7634 : 361 : CommandCounterIncrement();
7635 : 361 : has_missing = true;
7636 : : }
7637 : 361 : FreeExecutorState(estate);
7638 : : }
7639 : : else
7640 : : {
7641 : : /*
7642 : : * Failed to use missing mode. We have to do a table rewrite
7643 : : * to install the value --- unless it's a virtual generated
7644 : : * column.
7645 : : */
7646 [ + + ]: 247 : if (colDef->generated != ATTRIBUTE_GENERATED_VIRTUAL)
7647 : 174 : tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
7648 : : }
7649 : : }
7650 : :
7651 [ + + ]: 1579 : if (!has_missing)
7652 : : {
7653 : : /*
7654 : : * If the new column is NOT NULL, and there is no missing value,
7655 : : * tell Phase 3 it needs to check for NULLs.
7656 : : */
7657 : 1218 : tab->verify_new_notnull |= colDef->is_not_null;
7658 : : }
7659 : : }
7660 : :
7661 : : /*
7662 : : * Add needed dependency entries for the new column.
7663 : : */
7664 : 1849 : add_column_datatype_dependency(myrelid, newattnum, attribute->atttypid);
7665 : 1849 : add_column_collation_dependency(myrelid, newattnum, attribute->attcollation);
7666 : :
7667 : : /*
7668 : : * Propagate to children as appropriate. Unlike most other ALTER
7669 : : * routines, we have to do this one level of recursion at a time; we can't
7670 : : * use find_all_inheritors to do it in one pass.
7671 : : */
7672 : : children =
7673 : 1849 : find_inheritance_children(RelationGetRelid(rel), lockmode);
7674 : :
7675 : : /*
7676 : : * If we are told not to recurse, there had better not be any child
7677 : : * tables; else the addition would put them out of step.
7678 : : */
7679 [ + + + + ]: 1849 : if (children && !recurse)
7680 [ + - ]: 8 : ereport(ERROR,
7681 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7682 : : errmsg("column must be added to child tables too")));
7683 : :
7684 : : /* Children should see column as singly inherited */
7685 [ + + ]: 1841 : if (!recursing)
7686 : : {
7687 : 1367 : childcmd = copyObject(*cmd);
7688 : 1367 : colDef = castNode(ColumnDef, childcmd->def);
7689 : 1367 : colDef->inhcount = 1;
7690 : 1367 : colDef->is_local = false;
7691 : : }
7692 : : else
7693 : 474 : childcmd = *cmd; /* no need to copy again */
7694 : :
7695 [ + + + + : 2355 : foreach(child, children)
+ + ]
7696 : : {
7697 : 514 : Oid childrelid = lfirst_oid(child);
7698 : : Relation childrel;
7699 : : AlteredTableInfo *childtab;
7700 : :
7701 : : /* find_inheritance_children already got lock */
7702 : 514 : childrel = table_open(childrelid, NoLock);
7703 : 514 : CheckAlterTableIsSafe(childrel);
7704 : :
7705 : : /* Find or create work queue entry for this table */
7706 : 514 : childtab = ATGetQueueEntry(wqueue, childrel);
7707 : :
7708 : : /* Recurse to child; return value is ignored */
7709 : 514 : ATExecAddColumn(wqueue, childtab, childrel,
7710 : : &childcmd, recurse, true,
7711 : : lockmode, cur_pass, context);
7712 : :
7713 : 514 : table_close(childrel, NoLock);
7714 : : }
7715 : :
7716 : 1841 : ObjectAddressSubSet(address, RelationRelationId, myrelid, newattnum);
7717 : 1841 : return address;
7718 : : }
7719 : :
7720 : : /*
7721 : : * If a new or renamed column will collide with the name of an existing
7722 : : * column and if_not_exists is false then error out, else do nothing.
7723 : : */
7724 : : static bool
7725 : 2343 : check_for_column_name_collision(Relation rel, const char *colname,
7726 : : bool if_not_exists)
7727 : : {
7728 : : HeapTuple attTuple;
7729 : : int attnum;
7730 : :
7731 : : /*
7732 : : * this test is deliberately not attisdropped-aware, since if one tries to
7733 : : * add a column matching a dropped column name, it's gonna fail anyway.
7734 : : */
7735 : 2343 : attTuple = SearchSysCache2(ATTNAME,
7736 : : ObjectIdGetDatum(RelationGetRelid(rel)),
7737 : : PointerGetDatum(colname));
7738 [ + + ]: 2343 : if (!HeapTupleIsValid(attTuple))
7739 : 2271 : return true;
7740 : :
7741 : 72 : attnum = ((Form_pg_attribute) GETSTRUCT(attTuple))->attnum;
7742 : 72 : ReleaseSysCache(attTuple);
7743 : :
7744 : : /*
7745 : : * We throw a different error message for conflicts with system column
7746 : : * names, since they are normally not shown and the user might otherwise
7747 : : * be confused about the reason for the conflict.
7748 : : */
7749 [ + + ]: 72 : if (attnum <= 0)
7750 [ + - ]: 8 : ereport(ERROR,
7751 : : (errcode(ERRCODE_DUPLICATE_COLUMN),
7752 : : errmsg("column name \"%s\" conflicts with a system column name",
7753 : : colname)));
7754 : : else
7755 : : {
7756 [ + + ]: 64 : if (if_not_exists)
7757 : : {
7758 [ + - ]: 44 : ereport(NOTICE,
7759 : : (errcode(ERRCODE_DUPLICATE_COLUMN),
7760 : : errmsg("column \"%s\" of relation \"%s\" already exists, skipping",
7761 : : colname, RelationGetRelationName(rel))));
7762 : 44 : return false;
7763 : : }
7764 : :
7765 [ + - ]: 20 : ereport(ERROR,
7766 : : (errcode(ERRCODE_DUPLICATE_COLUMN),
7767 : : errmsg("column \"%s\" of relation \"%s\" already exists",
7768 : : colname, RelationGetRelationName(rel))));
7769 : : }
7770 : :
7771 : : return true;
7772 : : }
7773 : :
7774 : : /*
7775 : : * Install a column's dependency on its datatype.
7776 : : */
7777 : : static void
7778 : 2625 : add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
7779 : : {
7780 : : ObjectAddress myself,
7781 : : referenced;
7782 : :
7783 : 2625 : myself.classId = RelationRelationId;
7784 : 2625 : myself.objectId = relid;
7785 : 2625 : myself.objectSubId = attnum;
7786 : 2625 : referenced.classId = TypeRelationId;
7787 : 2625 : referenced.objectId = typid;
7788 : 2625 : referenced.objectSubId = 0;
7789 : 2625 : recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
7790 : 2625 : }
7791 : :
7792 : : /*
7793 : : * Install a column's dependency on its collation.
7794 : : */
7795 : : static void
7796 : 2625 : add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
7797 : : {
7798 : : ObjectAddress myself,
7799 : : referenced;
7800 : :
7801 : : /* We know the default collation is pinned, so don't bother recording it */
7802 [ + + + + ]: 2625 : if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
7803 : : {
7804 : 12 : myself.classId = RelationRelationId;
7805 : 12 : myself.objectId = relid;
7806 : 12 : myself.objectSubId = attnum;
7807 : 12 : referenced.classId = CollationRelationId;
7808 : 12 : referenced.objectId = collid;
7809 : 12 : referenced.objectSubId = 0;
7810 : 12 : recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
7811 : : }
7812 : 2625 : }
7813 : :
7814 : : /*
7815 : : * ALTER TABLE ALTER COLUMN DROP NOT NULL
7816 : : *
7817 : : * Return the address of the modified column. If the column was already
7818 : : * nullable, InvalidObjectAddress is returned.
7819 : : */
7820 : : static ObjectAddress
7821 : 177 : ATExecDropNotNull(Relation rel, const char *colName, bool recurse,
7822 : : LOCKMODE lockmode)
7823 : : {
7824 : : HeapTuple tuple;
7825 : : HeapTuple conTup;
7826 : : Form_pg_attribute attTup;
7827 : : AttrNumber attnum;
7828 : : Relation attr_rel;
7829 : : ObjectAddress address;
7830 : :
7831 : : /*
7832 : : * lookup the attribute
7833 : : */
7834 : 177 : attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
7835 : :
7836 : 177 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
7837 [ + + ]: 177 : if (!HeapTupleIsValid(tuple))
7838 [ + - ]: 12 : ereport(ERROR,
7839 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
7840 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
7841 : : colName, RelationGetRelationName(rel))));
7842 : 165 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
7843 : 165 : attnum = attTup->attnum;
7844 : 165 : ObjectAddressSubSet(address, RelationRelationId,
7845 : : RelationGetRelid(rel), attnum);
7846 : :
7847 : : /* If the column is already nullable there's nothing to do. */
7848 [ - + ]: 165 : if (!attTup->attnotnull)
7849 : : {
7850 : 0 : table_close(attr_rel, RowExclusiveLock);
7851 : 0 : return InvalidObjectAddress;
7852 : : }
7853 : :
7854 : : /* Prevent them from altering a system attribute */
7855 [ - + ]: 165 : if (attnum <= 0)
7856 [ # # ]: 0 : ereport(ERROR,
7857 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7858 : : errmsg("cannot alter system column \"%s\"",
7859 : : colName)));
7860 : :
7861 [ + + ]: 165 : if (attTup->attidentity)
7862 [ + - ]: 12 : ereport(ERROR,
7863 : : (errcode(ERRCODE_SYNTAX_ERROR),
7864 : : errmsg("column \"%s\" of relation \"%s\" is an identity column",
7865 : : colName, RelationGetRelationName(rel))));
7866 : :
7867 : : /*
7868 : : * If rel is partition, shouldn't drop NOT NULL if parent has the same.
7869 : : */
7870 [ + + ]: 153 : if (rel->rd_rel->relispartition)
7871 : : {
7872 : 8 : Oid parentId = get_partition_parent(RelationGetRelid(rel), false);
7873 : 8 : Relation parent = table_open(parentId, AccessShareLock);
7874 : 8 : TupleDesc tupDesc = RelationGetDescr(parent);
7875 : : AttrNumber parent_attnum;
7876 : :
7877 : 8 : parent_attnum = get_attnum(parentId, colName);
7878 [ + - ]: 8 : if (TupleDescAttr(tupDesc, parent_attnum - 1)->attnotnull)
7879 [ + - ]: 8 : ereport(ERROR,
7880 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7881 : : errmsg("column \"%s\" is marked NOT NULL in parent table",
7882 : : colName)));
7883 : 0 : table_close(parent, AccessShareLock);
7884 : : }
7885 : :
7886 : : /*
7887 : : * Find the constraint that makes this column NOT NULL, and drop it.
7888 : : * dropconstraint_internal() resets attnotnull.
7889 : : */
7890 : 145 : conTup = findNotNullConstraintAttnum(RelationGetRelid(rel), attnum);
7891 [ - + ]: 145 : if (conTup == NULL)
7892 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
7893 : : colName, RelationGetRelationName(rel));
7894 : :
7895 : : /* The normal case: we have a pg_constraint row, remove it */
7896 : 145 : dropconstraint_internal(rel, conTup, DROP_RESTRICT, recurse, false,
7897 : : false, lockmode);
7898 : 109 : heap_freetuple(conTup);
7899 : :
7900 [ - + ]: 109 : InvokeObjectPostAlterHook(RelationRelationId,
7901 : : RelationGetRelid(rel), attnum);
7902 : :
7903 : 109 : table_close(attr_rel, RowExclusiveLock);
7904 : :
7905 : 109 : return address;
7906 : : }
7907 : :
7908 : : /*
7909 : : * set_attnotnull
7910 : : * Helper to update/validate the pg_attribute status of a not-null
7911 : : * constraint
7912 : : *
7913 : : * pg_attribute.attnotnull is set true, if it isn't already.
7914 : : * If queue_validation is true, also set up wqueue to validate the constraint.
7915 : : * wqueue may be given as NULL when validation is not needed (e.g., on table
7916 : : * creation).
7917 : : */
7918 : : static void
7919 : 15794 : set_attnotnull(List **wqueue, Relation rel, AttrNumber attnum,
7920 : : bool queue_validation)
7921 : : {
7922 : : Form_pg_attribute attr;
7923 : :
7924 : : Assert(!queue_validation || wqueue);
7925 : :
7926 : 15794 : CheckAlterTableIsSafe(rel);
7927 : :
7928 : : /*
7929 : : * Exit quickly by testing attnotnull from the tupledesc's copy of the
7930 : : * attribute.
7931 : : */
7932 : 15794 : attr = TupleDescAttr(RelationGetDescr(rel), attnum - 1);
7933 [ - + ]: 15794 : if (attr->attisdropped)
7934 : 0 : return;
7935 : :
7936 [ + + ]: 15794 : if (!attr->attnotnull)
7937 : : {
7938 : : Relation attr_rel;
7939 : : HeapTuple tuple;
7940 : :
7941 : 966 : attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
7942 : :
7943 : 966 : tuple = SearchSysCacheCopyAttNum(RelationGetRelid(rel), attnum);
7944 [ - + ]: 966 : if (!HeapTupleIsValid(tuple))
7945 [ # # ]: 0 : elog(ERROR, "cache lookup failed for attribute %d of relation %u",
7946 : : attnum, RelationGetRelid(rel));
7947 : :
7948 : 966 : attr = (Form_pg_attribute) GETSTRUCT(tuple);
7949 : :
7950 : 966 : attr->attnotnull = true;
7951 : 966 : CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
7952 : :
7953 : : /*
7954 : : * If the nullness isn't already proven by validated constraints, have
7955 : : * ALTER TABLE phase 3 test for it.
7956 : : */
7957 [ + + + - ]: 966 : if (queue_validation && wqueue &&
7958 [ + + ]: 815 : !NotNullImpliedByRelConstraints(rel, attr))
7959 : : {
7960 : : AlteredTableInfo *tab;
7961 : :
7962 : 783 : tab = ATGetQueueEntry(wqueue, rel);
7963 : 783 : tab->verify_new_notnull = true;
7964 : : }
7965 : :
7966 : 966 : CommandCounterIncrement();
7967 : :
7968 : 966 : table_close(attr_rel, RowExclusiveLock);
7969 : 966 : heap_freetuple(tuple);
7970 : : }
7971 : : else
7972 : : {
7973 : 14828 : CacheInvalidateRelcache(rel);
7974 : : }
7975 : : }
7976 : :
7977 : : /*
7978 : : * ALTER TABLE ALTER COLUMN SET NOT NULL
7979 : : *
7980 : : * Add a not-null constraint to a single table and its children. Returns
7981 : : * the address of the constraint added to the parent relation, if one gets
7982 : : * added, or InvalidObjectAddress otherwise.
7983 : : *
7984 : : * We must recurse to child tables during execution, rather than using
7985 : : * ALTER TABLE's normal prep-time recursion.
7986 : : */
7987 : : static ObjectAddress
7988 : 469 : ATExecSetNotNull(List **wqueue, Relation rel, char *conName, char *colName,
7989 : : bool recurse, bool recursing, LOCKMODE lockmode)
7990 : : {
7991 : : HeapTuple tuple;
7992 : : AttrNumber attnum;
7993 : : ObjectAddress address;
7994 : : Constraint *constraint;
7995 : : CookedConstraint *ccon;
7996 : : List *cooked;
7997 : 469 : bool is_no_inherit = false;
7998 : :
7999 : : /* Guard against stack overflow due to overly deep inheritance tree. */
8000 : 469 : check_stack_depth();
8001 : :
8002 : : /* At top level, permission check was done in ATPrepCmd, else do it */
8003 [ + + ]: 469 : if (recursing)
8004 : : {
8005 : 197 : ATSimplePermissions(AT_AddConstraint, rel,
8006 : : ATT_PARTITIONED_TABLE | ATT_TABLE | ATT_FOREIGN_TABLE);
8007 : : Assert(conName != NULL);
8008 : : }
8009 : :
8010 : 469 : attnum = get_attnum(RelationGetRelid(rel), colName);
8011 [ + + ]: 469 : if (attnum == InvalidAttrNumber)
8012 [ + - ]: 12 : ereport(ERROR,
8013 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8014 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8015 : : colName, RelationGetRelationName(rel))));
8016 : :
8017 : : /* Prevent them from altering a system attribute */
8018 [ - + ]: 457 : if (attnum <= 0)
8019 [ # # ]: 0 : ereport(ERROR,
8020 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8021 : : errmsg("cannot alter system column \"%s\"",
8022 : : colName)));
8023 : :
8024 : : /* See if there's already a constraint */
8025 : 457 : tuple = findNotNullConstraintAttnum(RelationGetRelid(rel), attnum);
8026 [ + + ]: 457 : if (HeapTupleIsValid(tuple))
8027 : : {
8028 : 105 : Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(tuple);
8029 : 105 : bool changed = false;
8030 : :
8031 : : /*
8032 : : * Don't let a NO INHERIT constraint be changed into inherit.
8033 : : */
8034 [ + + + - ]: 105 : if (conForm->connoinherit && recurse)
8035 [ + - ]: 8 : ereport(ERROR,
8036 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8037 : : errmsg("cannot change NO INHERIT status of NOT NULL constraint \"%s\" on relation \"%s\"",
8038 : : NameStr(conForm->conname),
8039 : : RelationGetRelationName(rel)));
8040 : :
8041 : : /*
8042 : : * If we find an appropriate constraint, we're almost done, but just
8043 : : * need to change some properties on it: if we're recursing, increment
8044 : : * coninhcount; if not, set conislocal if not already set.
8045 : : */
8046 [ + + ]: 97 : if (recursing)
8047 : : {
8048 [ - + ]: 68 : if (pg_add_s16_overflow(conForm->coninhcount, 1,
8049 : : &conForm->coninhcount))
8050 [ # # ]: 0 : ereport(ERROR,
8051 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
8052 : : errmsg("too many inheritance parents"));
8053 : 68 : changed = true;
8054 : : }
8055 [ - + ]: 29 : else if (!conForm->conislocal)
8056 : : {
8057 : 0 : conForm->conislocal = true;
8058 : 0 : changed = true;
8059 : : }
8060 [ + + ]: 29 : else if (!conForm->convalidated)
8061 : : {
8062 : : /*
8063 : : * Flip attnotnull and convalidated, and also validate the
8064 : : * constraint.
8065 : : */
8066 : 16 : return ATExecValidateConstraint(wqueue, rel, NameStr(conForm->conname),
8067 : : recurse, recursing, lockmode);
8068 : : }
8069 : :
8070 [ + + ]: 81 : if (changed)
8071 : : {
8072 : : Relation constr_rel;
8073 : :
8074 : 68 : constr_rel = table_open(ConstraintRelationId, RowExclusiveLock);
8075 : :
8076 : 68 : CatalogTupleUpdate(constr_rel, &tuple->t_self, tuple);
8077 : 68 : ObjectAddressSet(address, ConstraintRelationId, conForm->oid);
8078 : 68 : table_close(constr_rel, RowExclusiveLock);
8079 : : }
8080 : :
8081 [ + + ]: 81 : if (changed)
8082 : 68 : return address;
8083 : : else
8084 : 13 : return InvalidObjectAddress;
8085 : : }
8086 : :
8087 : : /*
8088 : : * If we're asked not to recurse, and children exist, raise an error for
8089 : : * partitioned tables. For inheritance, we act as if NO INHERIT had been
8090 : : * specified.
8091 : : */
8092 [ + + + + ]: 372 : if (!recurse &&
8093 : 20 : find_inheritance_children(RelationGetRelid(rel),
8094 : : NoLock) != NIL)
8095 : : {
8096 [ + + ]: 12 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
8097 [ + - ]: 4 : ereport(ERROR,
8098 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8099 : : errmsg("constraint must be added to child tables too"),
8100 : : errhint("Do not specify the ONLY keyword."));
8101 : : else
8102 : 8 : is_no_inherit = true;
8103 : : }
8104 : :
8105 : : /*
8106 : : * No constraint exists; we must add one. First determine a name to use,
8107 : : * if we haven't already.
8108 : : */
8109 [ + + ]: 348 : if (!recursing)
8110 : : {
8111 : : Assert(conName == NULL);
8112 : 223 : conName = ChooseConstraintName(RelationGetRelationName(rel),
8113 : : colName, "not_null",
8114 : 223 : RelationGetNamespace(rel),
8115 : : NIL);
8116 : : }
8117 : :
8118 : 348 : constraint = makeNotNullConstraint(makeString(colName));
8119 : 348 : constraint->is_no_inherit = is_no_inherit;
8120 : 348 : constraint->conname = conName;
8121 : :
8122 : : /* and do it */
8123 : 348 : cooked = AddRelationNewConstraints(rel, NIL, list_make1(constraint),
8124 : 348 : false, !recursing, false, NULL);
8125 : 348 : ccon = linitial(cooked);
8126 : 348 : ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
8127 : :
8128 : : /* Mark pg_attribute.attnotnull for the column and queue validation */
8129 : 348 : set_attnotnull(wqueue, rel, attnum, true);
8130 : :
8131 [ - + ]: 348 : InvokeObjectPostAlterHook(RelationRelationId,
8132 : : RelationGetRelid(rel), attnum);
8133 : :
8134 : : /*
8135 : : * Recurse to propagate the constraint to children that don't have one.
8136 : : */
8137 [ + + ]: 348 : if (recurse)
8138 : : {
8139 : : List *children;
8140 : :
8141 : 332 : children = find_inheritance_children(RelationGetRelid(rel),
8142 : : lockmode);
8143 : :
8144 [ + + + + : 817 : foreach_oid(childoid, children)
+ + ]
8145 : : {
8146 : 161 : Relation childrel = table_open(childoid, NoLock);
8147 : :
8148 : 161 : CommandCounterIncrement();
8149 : :
8150 : 161 : ATExecSetNotNull(wqueue, childrel, conName, colName,
8151 : : recurse, true, lockmode);
8152 : 157 : table_close(childrel, NoLock);
8153 : : }
8154 : : }
8155 : :
8156 : 344 : return address;
8157 : : }
8158 : :
8159 : : /*
8160 : : * NotNullImpliedByRelConstraints
8161 : : * Does rel's existing constraints imply NOT NULL for the given attribute?
8162 : : */
8163 : : static bool
8164 : 815 : NotNullImpliedByRelConstraints(Relation rel, Form_pg_attribute attr)
8165 : : {
8166 : 815 : NullTest *nnulltest = makeNode(NullTest);
8167 : :
8168 : 1630 : nnulltest->arg = (Expr *) makeVar(1,
8169 : 815 : attr->attnum,
8170 : : attr->atttypid,
8171 : : attr->atttypmod,
8172 : : attr->attcollation,
8173 : : 0);
8174 : 815 : nnulltest->nulltesttype = IS_NOT_NULL;
8175 : :
8176 : : /*
8177 : : * argisrow = false is correct even for a composite column, because
8178 : : * attnotnull does not represent a SQL-spec IS NOT NULL test in such a
8179 : : * case, just IS DISTINCT FROM NULL.
8180 : : */
8181 : 815 : nnulltest->argisrow = false;
8182 : 815 : nnulltest->location = -1;
8183 : :
8184 [ + + ]: 815 : if (ConstraintImpliedByRelConstraint(rel, list_make1(nnulltest), NIL))
8185 : : {
8186 [ + + ]: 32 : ereport(DEBUG1,
8187 : : (errmsg_internal("existing constraints on column \"%s.%s\" are sufficient to prove that it does not contain nulls",
8188 : : RelationGetRelationName(rel), NameStr(attr->attname))));
8189 : 32 : return true;
8190 : : }
8191 : :
8192 : 783 : return false;
8193 : : }
8194 : :
8195 : : /*
8196 : : * ALTER TABLE ALTER COLUMN SET/DROP DEFAULT
8197 : : *
8198 : : * Return the address of the affected column.
8199 : : */
8200 : : static ObjectAddress
8201 : 387 : ATExecColumnDefault(Relation rel, const char *colName,
8202 : : Node *newDefault, LOCKMODE lockmode)
8203 : : {
8204 : 387 : TupleDesc tupdesc = RelationGetDescr(rel);
8205 : : AttrNumber attnum;
8206 : : ObjectAddress address;
8207 : :
8208 : : /*
8209 : : * get the number of the attribute
8210 : : */
8211 : 387 : attnum = get_attnum(RelationGetRelid(rel), colName);
8212 [ + + ]: 387 : if (attnum == InvalidAttrNumber)
8213 [ + - ]: 20 : ereport(ERROR,
8214 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8215 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8216 : : colName, RelationGetRelationName(rel))));
8217 : :
8218 : : /* Prevent them from altering a system attribute */
8219 [ - + ]: 367 : if (attnum <= 0)
8220 [ # # ]: 0 : ereport(ERROR,
8221 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8222 : : errmsg("cannot alter system column \"%s\"",
8223 : : colName)));
8224 : :
8225 [ + + ]: 367 : if (TupleDescAttr(tupdesc, attnum - 1)->attidentity)
8226 [ + - - + ]: 12 : ereport(ERROR,
8227 : : (errcode(ERRCODE_SYNTAX_ERROR),
8228 : : errmsg("column \"%s\" of relation \"%s\" is an identity column",
8229 : : colName, RelationGetRelationName(rel)),
8230 : : /* translator: %s is an SQL ALTER command */
8231 : : newDefault ? 0 : errhint("Use %s instead.",
8232 : : "ALTER TABLE ... ALTER COLUMN ... DROP IDENTITY")));
8233 : :
8234 [ + + ]: 355 : if (TupleDescAttr(tupdesc, attnum - 1)->attgenerated)
8235 [ + - - + : 8 : ereport(ERROR,
+ + ]
8236 : : (errcode(ERRCODE_SYNTAX_ERROR),
8237 : : errmsg("column \"%s\" of relation \"%s\" is a generated column",
8238 : : colName, RelationGetRelationName(rel)),
8239 : : newDefault ?
8240 : : /* translator: %s is an SQL ALTER command */
8241 : : errhint("Use %s instead.", "ALTER TABLE ... ALTER COLUMN ... SET EXPRESSION") :
8242 : : (TupleDescAttr(tupdesc, attnum - 1)->attgenerated == ATTRIBUTE_GENERATED_STORED ?
8243 : : errhint("Use %s instead.", "ALTER TABLE ... ALTER COLUMN ... DROP EXPRESSION") : 0)));
8244 : :
8245 : : /*
8246 : : * Remove any old default for the column. We use RESTRICT here for
8247 : : * safety, but at present we do not expect anything to depend on the
8248 : : * default.
8249 : : *
8250 : : * We treat removing the existing default as an internal operation when it
8251 : : * is preparatory to adding a new default, but as a user-initiated
8252 : : * operation when the user asked for a drop.
8253 : : */
8254 : 347 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
8255 : : newDefault != NULL);
8256 : :
8257 [ + + ]: 347 : if (newDefault)
8258 : : {
8259 : : /* SET DEFAULT */
8260 : : RawColumnDefault *rawEnt;
8261 : :
8262 : 231 : rawEnt = palloc_object(RawColumnDefault);
8263 : 231 : rawEnt->attnum = attnum;
8264 : 231 : rawEnt->raw_default = newDefault;
8265 : 231 : rawEnt->generated = '\0';
8266 : :
8267 : : /*
8268 : : * This function is intended for CREATE TABLE, so it processes a
8269 : : * _list_ of defaults, but we just do one.
8270 : : */
8271 : 231 : AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
8272 : : false, true, false, NULL);
8273 : : }
8274 : :
8275 : 339 : ObjectAddressSubSet(address, RelationRelationId,
8276 : : RelationGetRelid(rel), attnum);
8277 : 339 : return address;
8278 : : }
8279 : :
8280 : : /*
8281 : : * Add a pre-cooked default expression.
8282 : : *
8283 : : * Return the address of the affected column.
8284 : : */
8285 : : static ObjectAddress
8286 : 57 : ATExecCookedColumnDefault(Relation rel, AttrNumber attnum,
8287 : : Node *newDefault)
8288 : : {
8289 : : ObjectAddress address;
8290 : :
8291 : : /*
8292 : : * This is used for a cooked default copied by CREATE TABLE ... LIKE,
8293 : : * which adds new type dependencies. Such a default doesn't go through
8294 : : * AddRelationNewConstraints(), and StoreAttrDefault() leaves the
8295 : : * privilege checks to its caller, so we must check for USAGE on the types
8296 : : * here.
8297 : : */
8298 : 57 : CheckUsageOnTypesInSingleRelExpr(newDefault, RelationGetRelid(rel), GetUserId());
8299 : :
8300 : : /*
8301 : : * Remove any old default for the column. We use RESTRICT here for
8302 : : * safety, but at present we do not expect anything to depend on the
8303 : : * default. (In ordinary cases, there could not be a default in place
8304 : : * anyway, but it's possible when combining LIKE with inheritance.)
8305 : : */
8306 : 53 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, false,
8307 : : true);
8308 : :
8309 : 53 : (void) StoreAttrDefault(rel, attnum, newDefault, true);
8310 : :
8311 : 53 : ObjectAddressSubSet(address, RelationRelationId,
8312 : : RelationGetRelid(rel), attnum);
8313 : 53 : return address;
8314 : : }
8315 : :
8316 : : /*
8317 : : * ALTER TABLE ALTER COLUMN ADD IDENTITY
8318 : : *
8319 : : * Return the address of the affected column.
8320 : : */
8321 : : static ObjectAddress
8322 : 103 : ATExecAddIdentity(Relation rel, const char *colName,
8323 : : Node *def, LOCKMODE lockmode, bool recurse, bool recursing)
8324 : : {
8325 : : Relation attrelation;
8326 : : HeapTuple tuple;
8327 : : Form_pg_attribute attTup;
8328 : : AttrNumber attnum;
8329 : : ObjectAddress address;
8330 : 103 : ColumnDef *cdef = castNode(ColumnDef, def);
8331 : : bool ispartitioned;
8332 : :
8333 : 103 : ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
8334 [ + + + + ]: 103 : if (ispartitioned && !recurse)
8335 [ + - ]: 4 : ereport(ERROR,
8336 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8337 : : errmsg("cannot add identity to a column of only the partitioned table"),
8338 : : errhint("Do not specify the ONLY keyword.")));
8339 : :
8340 [ + + + + ]: 99 : if (rel->rd_rel->relispartition && !recursing)
8341 [ + - ]: 8 : ereport(ERROR,
8342 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8343 : : errmsg("cannot add identity to a column of a partition"));
8344 : :
8345 : 91 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8346 : :
8347 : 91 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8348 [ - + ]: 91 : if (!HeapTupleIsValid(tuple))
8349 [ # # ]: 0 : ereport(ERROR,
8350 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8351 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8352 : : colName, RelationGetRelationName(rel))));
8353 : 91 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8354 : 91 : attnum = attTup->attnum;
8355 : :
8356 : : /* Can't alter a system attribute */
8357 [ - + ]: 91 : if (attnum <= 0)
8358 [ # # ]: 0 : ereport(ERROR,
8359 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8360 : : errmsg("cannot alter system column \"%s\"",
8361 : : colName)));
8362 : :
8363 : : /*
8364 : : * Creating a column as identity implies NOT NULL, so adding the identity
8365 : : * to an existing column that is not NOT NULL would create a state that
8366 : : * cannot be reproduced without contortions.
8367 : : */
8368 [ + + ]: 91 : if (!attTup->attnotnull)
8369 [ + - ]: 4 : ereport(ERROR,
8370 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8371 : : errmsg("column \"%s\" of relation \"%s\" must be declared NOT NULL before identity can be added",
8372 : : colName, RelationGetRelationName(rel))));
8373 : :
8374 : : /*
8375 : : * On the other hand, if a not-null constraint exists, then verify that
8376 : : * it's compatible.
8377 : : */
8378 [ + - ]: 87 : if (attTup->attnotnull)
8379 : : {
8380 : : HeapTuple contup;
8381 : : Form_pg_constraint conForm;
8382 : :
8383 : 87 : contup = findNotNullConstraintAttnum(RelationGetRelid(rel),
8384 : : attnum);
8385 [ - + ]: 87 : if (!HeapTupleIsValid(contup))
8386 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
8387 : : colName, RelationGetRelationName(rel));
8388 : :
8389 : 87 : conForm = (Form_pg_constraint) GETSTRUCT(contup);
8390 [ + + ]: 87 : if (!conForm->convalidated)
8391 [ + - ]: 4 : ereport(ERROR,
8392 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8393 : : errmsg("incompatible NOT VALID constraint \"%s\" on relation \"%s\"",
8394 : : NameStr(conForm->conname), RelationGetRelationName(rel)),
8395 : : errhint("You might need to validate it using %s.",
8396 : : "ALTER TABLE ... VALIDATE CONSTRAINT"));
8397 : : }
8398 : :
8399 [ + + ]: 83 : if (attTup->attidentity)
8400 [ + - ]: 12 : ereport(ERROR,
8401 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8402 : : errmsg("column \"%s\" of relation \"%s\" is already an identity column",
8403 : : colName, RelationGetRelationName(rel))));
8404 : :
8405 [ + + ]: 71 : if (attTup->atthasdef)
8406 [ + - ]: 4 : ereport(ERROR,
8407 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8408 : : errmsg("column \"%s\" of relation \"%s\" already has a default value",
8409 : : colName, RelationGetRelationName(rel))));
8410 : :
8411 : 67 : attTup->attidentity = cdef->identity;
8412 : 67 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8413 : :
8414 [ - + ]: 67 : InvokeObjectPostAlterHook(RelationRelationId,
8415 : : RelationGetRelid(rel),
8416 : : attTup->attnum);
8417 : 67 : ObjectAddressSubSet(address, RelationRelationId,
8418 : : RelationGetRelid(rel), attnum);
8419 : 67 : heap_freetuple(tuple);
8420 : :
8421 : 67 : table_close(attrelation, RowExclusiveLock);
8422 : :
8423 : : /*
8424 : : * Recurse to propagate the identity column to partitions. Identity is
8425 : : * not inherited in regular inheritance children.
8426 : : */
8427 [ + - + + ]: 67 : if (recurse && ispartitioned)
8428 : : {
8429 : : List *children;
8430 : : ListCell *lc;
8431 : :
8432 : 6 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
8433 : :
8434 [ + + + + : 10 : foreach(lc, children)
+ + ]
8435 : : {
8436 : : Relation childrel;
8437 : :
8438 : 4 : childrel = table_open(lfirst_oid(lc), NoLock);
8439 : 4 : ATExecAddIdentity(childrel, colName, def, lockmode, recurse, true);
8440 : 4 : table_close(childrel, NoLock);
8441 : : }
8442 : : }
8443 : :
8444 : 67 : return address;
8445 : : }
8446 : :
8447 : : /*
8448 : : * ALTER TABLE ALTER COLUMN SET { GENERATED or sequence options }
8449 : : *
8450 : : * Return the address of the affected column.
8451 : : */
8452 : : static ObjectAddress
8453 : 49 : ATExecSetIdentity(Relation rel, const char *colName, Node *def,
8454 : : LOCKMODE lockmode, bool recurse, bool recursing)
8455 : : {
8456 : : ListCell *option;
8457 : 49 : DefElem *generatedEl = NULL;
8458 : : HeapTuple tuple;
8459 : : Form_pg_attribute attTup;
8460 : : AttrNumber attnum;
8461 : : Relation attrelation;
8462 : : ObjectAddress address;
8463 : : bool ispartitioned;
8464 : :
8465 : 49 : ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
8466 [ + + + + ]: 49 : if (ispartitioned && !recurse)
8467 [ + - ]: 4 : ereport(ERROR,
8468 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8469 : : errmsg("cannot change identity column of only the partitioned table"),
8470 : : errhint("Do not specify the ONLY keyword.")));
8471 : :
8472 [ + + + + ]: 45 : if (rel->rd_rel->relispartition && !recursing)
8473 [ + - ]: 8 : ereport(ERROR,
8474 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8475 : : errmsg("cannot change identity column of a partition"));
8476 : :
8477 [ + + + + : 66 : foreach(option, castNode(List, def))
+ + ]
8478 : : {
8479 : 29 : DefElem *defel = lfirst_node(DefElem, option);
8480 : :
8481 [ + - ]: 29 : if (strcmp(defel->defname, "generated") == 0)
8482 : : {
8483 [ - + ]: 29 : if (generatedEl)
8484 [ # # ]: 0 : ereport(ERROR,
8485 : : (errcode(ERRCODE_SYNTAX_ERROR),
8486 : : errmsg("conflicting or redundant options")));
8487 : 29 : generatedEl = defel;
8488 : : }
8489 : : else
8490 [ # # ]: 0 : elog(ERROR, "option \"%s\" not recognized",
8491 : : defel->defname);
8492 : : }
8493 : :
8494 : : /*
8495 : : * Even if there is nothing to change here, we run all the checks. There
8496 : : * will be a subsequent ALTER SEQUENCE that relies on everything being
8497 : : * there.
8498 : : */
8499 : :
8500 : 37 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8501 : 37 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8502 [ - + ]: 37 : if (!HeapTupleIsValid(tuple))
8503 [ # # ]: 0 : ereport(ERROR,
8504 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8505 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8506 : : colName, RelationGetRelationName(rel))));
8507 : :
8508 : 37 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8509 : 37 : attnum = attTup->attnum;
8510 : :
8511 [ - + ]: 37 : if (attnum <= 0)
8512 [ # # ]: 0 : ereport(ERROR,
8513 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8514 : : errmsg("cannot alter system column \"%s\"",
8515 : : colName)));
8516 : :
8517 [ + + ]: 37 : if (!attTup->attidentity)
8518 [ + - ]: 4 : ereport(ERROR,
8519 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8520 : : errmsg("column \"%s\" of relation \"%s\" is not an identity column",
8521 : : colName, RelationGetRelationName(rel))));
8522 : :
8523 [ + + ]: 33 : if (generatedEl)
8524 : : {
8525 : 29 : attTup->attidentity = defGetInt32(generatedEl);
8526 : 29 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8527 : :
8528 [ - + ]: 29 : InvokeObjectPostAlterHook(RelationRelationId,
8529 : : RelationGetRelid(rel),
8530 : : attTup->attnum);
8531 : 29 : ObjectAddressSubSet(address, RelationRelationId,
8532 : : RelationGetRelid(rel), attnum);
8533 : : }
8534 : : else
8535 : 4 : address = InvalidObjectAddress;
8536 : :
8537 : 33 : heap_freetuple(tuple);
8538 : 33 : table_close(attrelation, RowExclusiveLock);
8539 : :
8540 : : /*
8541 : : * Recurse to propagate the identity change to partitions. Identity is not
8542 : : * inherited in regular inheritance children.
8543 : : */
8544 [ + + + - : 33 : if (generatedEl && recurse && ispartitioned)
+ + ]
8545 : : {
8546 : : List *children;
8547 : : ListCell *lc;
8548 : :
8549 : 4 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
8550 : :
8551 [ + - + + : 12 : foreach(lc, children)
+ + ]
8552 : : {
8553 : : Relation childrel;
8554 : :
8555 : 8 : childrel = table_open(lfirst_oid(lc), NoLock);
8556 : 8 : ATExecSetIdentity(childrel, colName, def, lockmode, recurse, true);
8557 : 8 : table_close(childrel, NoLock);
8558 : : }
8559 : : }
8560 : :
8561 : 33 : return address;
8562 : : }
8563 : :
8564 : : /*
8565 : : * ALTER TABLE ALTER COLUMN DROP IDENTITY
8566 : : *
8567 : : * Return the address of the affected column.
8568 : : */
8569 : : static ObjectAddress
8570 : 45 : ATExecDropIdentity(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode,
8571 : : bool recurse, bool recursing)
8572 : : {
8573 : : HeapTuple tuple;
8574 : : Form_pg_attribute attTup;
8575 : : AttrNumber attnum;
8576 : : Relation attrelation;
8577 : : ObjectAddress address;
8578 : : Oid seqid;
8579 : : ObjectAddress seqaddress;
8580 : : bool ispartitioned;
8581 : :
8582 : 45 : ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
8583 [ + + + + ]: 45 : if (ispartitioned && !recurse)
8584 [ + - ]: 4 : ereport(ERROR,
8585 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8586 : : errmsg("cannot drop identity from a column of only the partitioned table"),
8587 : : errhint("Do not specify the ONLY keyword.")));
8588 : :
8589 [ + + + + ]: 41 : if (rel->rd_rel->relispartition && !recursing)
8590 [ + - ]: 4 : ereport(ERROR,
8591 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8592 : : errmsg("cannot drop identity from a column of a partition"));
8593 : :
8594 : 37 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8595 : 37 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8596 [ - + ]: 37 : if (!HeapTupleIsValid(tuple))
8597 [ # # ]: 0 : ereport(ERROR,
8598 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8599 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8600 : : colName, RelationGetRelationName(rel))));
8601 : :
8602 : 37 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8603 : 37 : attnum = attTup->attnum;
8604 : :
8605 [ - + ]: 37 : if (attnum <= 0)
8606 [ # # ]: 0 : ereport(ERROR,
8607 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8608 : : errmsg("cannot alter system column \"%s\"",
8609 : : colName)));
8610 : :
8611 [ + + ]: 37 : if (!attTup->attidentity)
8612 : : {
8613 [ + + ]: 8 : if (!missing_ok)
8614 [ + - ]: 4 : ereport(ERROR,
8615 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8616 : : errmsg("column \"%s\" of relation \"%s\" is not an identity column",
8617 : : colName, RelationGetRelationName(rel))));
8618 : : else
8619 : : {
8620 [ + - ]: 4 : ereport(NOTICE,
8621 : : (errmsg("column \"%s\" of relation \"%s\" is not an identity column, skipping",
8622 : : colName, RelationGetRelationName(rel))));
8623 : 4 : heap_freetuple(tuple);
8624 : 4 : table_close(attrelation, RowExclusiveLock);
8625 : 4 : return InvalidObjectAddress;
8626 : : }
8627 : : }
8628 : :
8629 : 29 : attTup->attidentity = '\0';
8630 : 29 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8631 : :
8632 [ - + ]: 29 : InvokeObjectPostAlterHook(RelationRelationId,
8633 : : RelationGetRelid(rel),
8634 : : attTup->attnum);
8635 : 29 : ObjectAddressSubSet(address, RelationRelationId,
8636 : : RelationGetRelid(rel), attnum);
8637 : 29 : heap_freetuple(tuple);
8638 : :
8639 : 29 : table_close(attrelation, RowExclusiveLock);
8640 : :
8641 : : /*
8642 : : * Recurse to drop the identity from column in partitions. Identity is
8643 : : * not inherited in regular inheritance children so ignore them.
8644 : : */
8645 [ + - + + ]: 29 : if (recurse && ispartitioned)
8646 : : {
8647 : : List *children;
8648 : : ListCell *lc;
8649 : :
8650 : 4 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
8651 : :
8652 [ + - + + : 8 : foreach(lc, children)
+ + ]
8653 : : {
8654 : : Relation childrel;
8655 : :
8656 : 4 : childrel = table_open(lfirst_oid(lc), NoLock);
8657 : 4 : ATExecDropIdentity(childrel, colName, false, lockmode, recurse, true);
8658 : 4 : table_close(childrel, NoLock);
8659 : : }
8660 : : }
8661 : :
8662 [ + + ]: 29 : if (!recursing)
8663 : : {
8664 : : /* drop the internal sequence */
8665 : 21 : seqid = getIdentitySequence(rel, attnum, false);
8666 : 21 : deleteDependencyRecordsForClass(RelationRelationId, seqid,
8667 : : RelationRelationId, DEPENDENCY_INTERNAL);
8668 : 21 : CommandCounterIncrement();
8669 : 21 : seqaddress.classId = RelationRelationId;
8670 : 21 : seqaddress.objectId = seqid;
8671 : 21 : seqaddress.objectSubId = 0;
8672 : 21 : performDeletion(&seqaddress, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
8673 : : }
8674 : :
8675 : 29 : return address;
8676 : : }
8677 : :
8678 : : /*
8679 : : * ALTER TABLE ALTER COLUMN SET EXPRESSION
8680 : : *
8681 : : * Return the address of the affected column.
8682 : : */
8683 : : static ObjectAddress
8684 : 193 : ATExecSetExpression(AlteredTableInfo *tab, Relation rel, const char *colName,
8685 : : Node *newExpr, LOCKMODE lockmode)
8686 : : {
8687 : : HeapTuple tuple;
8688 : : Form_pg_attribute attTup;
8689 : : AttrNumber attnum;
8690 : : char attgenerated;
8691 : : bool rewrite;
8692 : : Oid attrdefoid;
8693 : : ObjectAddress address;
8694 : : Expr *defval;
8695 : : NewColumnValue *newval;
8696 : : RawColumnDefault *rawEnt;
8697 : :
8698 : 193 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
8699 [ - + ]: 193 : if (!HeapTupleIsValid(tuple))
8700 [ # # ]: 0 : ereport(ERROR,
8701 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8702 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8703 : : colName, RelationGetRelationName(rel))));
8704 : :
8705 : 193 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8706 : :
8707 : 193 : attnum = attTup->attnum;
8708 [ - + ]: 193 : if (attnum <= 0)
8709 [ # # ]: 0 : ereport(ERROR,
8710 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8711 : : errmsg("cannot alter system column \"%s\"",
8712 : : colName)));
8713 : :
8714 : 193 : attgenerated = attTup->attgenerated;
8715 [ + + ]: 193 : if (!attgenerated)
8716 [ + - ]: 8 : ereport(ERROR,
8717 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8718 : : errmsg("column \"%s\" of relation \"%s\" is not a generated column",
8719 : : colName, RelationGetRelationName(rel))));
8720 : :
8721 [ + + + + ]: 185 : if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL && attTup->attnotnull)
8722 : 16 : tab->verify_new_notnull = true;
8723 : :
8724 : : /*
8725 : : * We need to prevent this because a change of expression could affect a
8726 : : * row filter and inject expressions that are not permitted in a row
8727 : : * filter. XXX We could try to have a more precise check to catch only
8728 : : * publications with row filters, or even re-verify the row filter
8729 : : * expressions.
8730 : : */
8731 [ + + + + ]: 273 : if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL &&
8732 : 88 : GetRelationIncludedPublications(RelationGetRelid(rel)) != NIL)
8733 [ + - ]: 4 : ereport(ERROR,
8734 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8735 : : errmsg("ALTER TABLE / SET EXPRESSION is not supported for virtual generated columns in tables that are part of a publication"),
8736 : : errdetail("Column \"%s\" of relation \"%s\" is a virtual generated column.",
8737 : : colName, RelationGetRelationName(rel))));
8738 : :
8739 : 181 : rewrite = (attgenerated == ATTRIBUTE_GENERATED_STORED);
8740 : :
8741 : 181 : ReleaseSysCache(tuple);
8742 : :
8743 [ + + ]: 181 : if (rewrite)
8744 : : {
8745 : : /*
8746 : : * Clear all the missing values if we're rewriting the table, since
8747 : : * this renders them pointless.
8748 : : */
8749 : 97 : RelationClearMissing(rel);
8750 : :
8751 : : /* make sure we don't conflict with later attribute modifications */
8752 : 97 : CommandCounterIncrement();
8753 : : }
8754 : :
8755 : : /*
8756 : : * Find everything that depends on the column (constraints, indexes, etc),
8757 : : * and record enough information to let us recreate the objects.
8758 : : */
8759 : 181 : RememberAllDependentForRebuilding(tab, AT_SetExpression, rel, attnum, colName);
8760 : :
8761 : : /*
8762 : : * Find whole-row referenced objects that depend on the column
8763 : : * (constraints, indexes, etc.), and record enough information to let us
8764 : : * recreate the objects.
8765 : : */
8766 : 181 : RememberWholeRowDependentForRebuilding(tab, AT_SetExpression, rel);
8767 : :
8768 : : /*
8769 : : * Drop the dependency records of the GENERATED expression, in particular
8770 : : * its INTERNAL dependency on the column, which would otherwise cause
8771 : : * dependency.c to refuse to perform the deletion.
8772 : : */
8773 : 181 : attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
8774 [ - + ]: 181 : if (!OidIsValid(attrdefoid))
8775 [ # # ]: 0 : elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
8776 : : RelationGetRelid(rel), attnum);
8777 : 181 : (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
8778 : :
8779 : : /* Make above changes visible */
8780 : 181 : CommandCounterIncrement();
8781 : :
8782 : : /*
8783 : : * Get rid of the GENERATED expression itself. We use RESTRICT here for
8784 : : * safety, but at present we do not expect anything to depend on the
8785 : : * expression.
8786 : : */
8787 : 181 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT,
8788 : : false, false);
8789 : :
8790 : : /* Prepare to store the new expression, in the catalogs */
8791 : 181 : rawEnt = palloc_object(RawColumnDefault);
8792 : 181 : rawEnt->attnum = attnum;
8793 : 181 : rawEnt->raw_default = newExpr;
8794 : 181 : rawEnt->generated = attgenerated;
8795 : :
8796 : : /* Store the generated expression */
8797 : 181 : AddRelationNewConstraints(rel, list_make1(rawEnt), NIL,
8798 : : false, true, false, NULL);
8799 : :
8800 : : /* Make above new expression visible */
8801 : 181 : CommandCounterIncrement();
8802 : :
8803 [ + + ]: 181 : if (rewrite)
8804 : : {
8805 : : /* Prepare for table rewrite */
8806 : 97 : defval = (Expr *) build_column_default(rel, attnum);
8807 : :
8808 : 97 : newval = palloc0_object(NewColumnValue);
8809 : 97 : newval->attnum = attnum;
8810 : 97 : newval->expr = expression_planner(defval);
8811 : 97 : newval->is_generated = true;
8812 : :
8813 : 97 : tab->newvals = lappend(tab->newvals, newval);
8814 : 97 : tab->rewrite |= AT_REWRITE_DEFAULT_VAL;
8815 : : }
8816 : :
8817 : : /* Drop any pg_statistic entry for the column */
8818 : 181 : RemoveStatistics(RelationGetRelid(rel), attnum);
8819 : :
8820 [ - + ]: 181 : InvokeObjectPostAlterHook(RelationRelationId,
8821 : : RelationGetRelid(rel), attnum);
8822 : :
8823 : 181 : ObjectAddressSubSet(address, RelationRelationId,
8824 : : RelationGetRelid(rel), attnum);
8825 : 181 : return address;
8826 : : }
8827 : :
8828 : : /*
8829 : : * ALTER TABLE ALTER COLUMN DROP EXPRESSION
8830 : : */
8831 : : static void
8832 : 93 : ATPrepDropExpression(Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
8833 : : {
8834 : : /*
8835 : : * Reject ONLY if there are child tables -- but only, of course, at the
8836 : : * top of the tree, otherwise it'd be impossible to run this command with
8837 : : * trees deeper than two levels. Caller already got lock.
8838 : : */
8839 [ + + + + : 105 : if (!recurse && !recursing &&
+ - ]
8840 : 12 : find_inheritance_children(RelationGetRelid(rel), NoLock))
8841 [ + - ]: 12 : ereport(ERROR,
8842 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8843 : : errmsg("ALTER TABLE / DROP EXPRESSION must be applied to child tables too")));
8844 : :
8845 : : /*
8846 : : * Cannot drop generation expression from inherited columns.
8847 : : */
8848 [ + + ]: 81 : if (!recursing)
8849 : : {
8850 : : HeapTuple tuple;
8851 : : Form_pg_attribute attTup;
8852 : :
8853 : 53 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), cmd->name);
8854 [ - + ]: 53 : if (!HeapTupleIsValid(tuple))
8855 [ # # ]: 0 : ereport(ERROR,
8856 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8857 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8858 : : cmd->name, RelationGetRelationName(rel))));
8859 : :
8860 : 53 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8861 : :
8862 [ + + ]: 53 : if (attTup->attinhcount > 0)
8863 [ + - ]: 12 : ereport(ERROR,
8864 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8865 : : errmsg("cannot drop generation expression from inherited column")));
8866 : : }
8867 : 69 : }
8868 : :
8869 : : /*
8870 : : * Return the address of the affected column.
8871 : : */
8872 : : static ObjectAddress
8873 : 61 : ATExecDropExpression(Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode)
8874 : : {
8875 : : HeapTuple tuple;
8876 : : Form_pg_attribute attTup;
8877 : : AttrNumber attnum;
8878 : : Relation attrelation;
8879 : : Oid attrdefoid;
8880 : : ObjectAddress address;
8881 : :
8882 : 61 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8883 : 61 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8884 [ - + ]: 61 : if (!HeapTupleIsValid(tuple))
8885 [ # # ]: 0 : ereport(ERROR,
8886 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
8887 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
8888 : : colName, RelationGetRelationName(rel))));
8889 : :
8890 : 61 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8891 : 61 : attnum = attTup->attnum;
8892 : :
8893 [ - + ]: 61 : if (attnum <= 0)
8894 [ # # ]: 0 : ereport(ERROR,
8895 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8896 : : errmsg("cannot alter system column \"%s\"",
8897 : : colName)));
8898 : :
8899 : : /*
8900 : : * TODO: This could be done, but it would need a table rewrite to
8901 : : * materialize the generated values. Note that for the time being, we
8902 : : * still error with missing_ok, so that we don't silently leave the column
8903 : : * as generated.
8904 : : */
8905 [ + + ]: 61 : if (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
8906 [ + - ]: 8 : ereport(ERROR,
8907 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8908 : : errmsg("ALTER TABLE / DROP EXPRESSION is not supported for virtual generated columns"),
8909 : : errdetail("Column \"%s\" of relation \"%s\" is a virtual generated column.",
8910 : : colName, RelationGetRelationName(rel))));
8911 : :
8912 [ + + ]: 53 : if (!attTup->attgenerated)
8913 : : {
8914 [ + + ]: 16 : if (!missing_ok)
8915 [ + - ]: 8 : ereport(ERROR,
8916 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8917 : : errmsg("column \"%s\" of relation \"%s\" is not a generated column",
8918 : : colName, RelationGetRelationName(rel))));
8919 : : else
8920 : : {
8921 [ + - ]: 8 : ereport(NOTICE,
8922 : : (errmsg("column \"%s\" of relation \"%s\" is not a generated column, skipping",
8923 : : colName, RelationGetRelationName(rel))));
8924 : 8 : heap_freetuple(tuple);
8925 : 8 : table_close(attrelation, RowExclusiveLock);
8926 : 8 : return InvalidObjectAddress;
8927 : : }
8928 : : }
8929 : :
8930 : : /*
8931 : : * Mark the column as no longer generated. (The atthasdef flag needs to
8932 : : * get cleared too, but RemoveAttrDefault will handle that.)
8933 : : */
8934 : 37 : attTup->attgenerated = '\0';
8935 : 37 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8936 : :
8937 [ - + ]: 37 : InvokeObjectPostAlterHook(RelationRelationId,
8938 : : RelationGetRelid(rel),
8939 : : attnum);
8940 : 37 : heap_freetuple(tuple);
8941 : :
8942 : 37 : table_close(attrelation, RowExclusiveLock);
8943 : :
8944 : : /*
8945 : : * Drop the dependency records of the GENERATED expression, in particular
8946 : : * its INTERNAL dependency on the column, which would otherwise cause
8947 : : * dependency.c to refuse to perform the deletion.
8948 : : */
8949 : 37 : attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
8950 [ - + ]: 37 : if (!OidIsValid(attrdefoid))
8951 [ # # ]: 0 : elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
8952 : : RelationGetRelid(rel), attnum);
8953 : 37 : (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
8954 : :
8955 : : /* Make above changes visible */
8956 : 37 : CommandCounterIncrement();
8957 : :
8958 : : /*
8959 : : * Get rid of the GENERATED expression itself. We use RESTRICT here for
8960 : : * safety, but at present we do not expect anything to depend on the
8961 : : * default.
8962 : : */
8963 : 37 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT,
8964 : : false, false);
8965 : :
8966 : 37 : ObjectAddressSubSet(address, RelationRelationId,
8967 : : RelationGetRelid(rel), attnum);
8968 : 37 : return address;
8969 : : }
8970 : :
8971 : : /*
8972 : : * ALTER TABLE ALTER COLUMN SET STATISTICS
8973 : : *
8974 : : * Return value is the address of the modified column
8975 : : */
8976 : : static ObjectAddress
8977 : 111 : ATExecSetStatistics(Relation rel, const char *colName, int16 colNum, Node *newValue, LOCKMODE lockmode)
8978 : : {
8979 : 111 : int newtarget = 0;
8980 : : bool newtarget_default;
8981 : : Relation attrelation;
8982 : : HeapTuple tuple,
8983 : : newtuple;
8984 : : Form_pg_attribute attrtuple;
8985 : : AttrNumber attnum;
8986 : : ObjectAddress address;
8987 : : Datum repl_val[Natts_pg_attribute];
8988 : : bool repl_null[Natts_pg_attribute];
8989 : : bool repl_repl[Natts_pg_attribute];
8990 : :
8991 : : /*
8992 : : * We allow referencing columns by numbers only for indexes, since table
8993 : : * column numbers could contain gaps if columns are later dropped.
8994 : : */
8995 [ + + ]: 111 : if (rel->rd_rel->relkind != RELKIND_INDEX &&
8996 [ + - - + ]: 69 : rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
8997 : : !colName)
8998 [ # # ]: 0 : ereport(ERROR,
8999 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9000 : : errmsg("cannot refer to non-index column by number")));
9001 : :
9002 : : /* -1 was used in previous versions for the default setting */
9003 [ + + + + ]: 111 : if (newValue && intVal(newValue) != -1)
9004 : : {
9005 : 80 : newtarget = intVal(newValue);
9006 : 80 : newtarget_default = false;
9007 : : }
9008 : : else
9009 : 31 : newtarget_default = true;
9010 : :
9011 [ + + ]: 111 : if (!newtarget_default)
9012 : : {
9013 : : /*
9014 : : * Limit target to a sane range
9015 : : */
9016 [ - + ]: 80 : if (newtarget < 0)
9017 : : {
9018 [ # # ]: 0 : ereport(ERROR,
9019 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9020 : : errmsg("statistics target %d is too low",
9021 : : newtarget)));
9022 : : }
9023 [ - + ]: 80 : else if (newtarget > MAX_STATISTICS_TARGET)
9024 : : {
9025 : 0 : newtarget = MAX_STATISTICS_TARGET;
9026 [ # # ]: 0 : ereport(WARNING,
9027 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
9028 : : errmsg("lowering statistics target to %d",
9029 : : newtarget)));
9030 : : }
9031 : : }
9032 : :
9033 : 111 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9034 : :
9035 [ + + ]: 111 : if (colName)
9036 : : {
9037 : 69 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9038 : :
9039 [ + + ]: 69 : if (!HeapTupleIsValid(tuple))
9040 [ + - ]: 8 : ereport(ERROR,
9041 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
9042 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
9043 : : colName, RelationGetRelationName(rel))));
9044 : : }
9045 : : else
9046 : : {
9047 : 42 : tuple = SearchSysCacheAttNum(RelationGetRelid(rel), colNum);
9048 : :
9049 [ + + ]: 42 : if (!HeapTupleIsValid(tuple))
9050 [ + - ]: 8 : ereport(ERROR,
9051 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
9052 : : errmsg("column number %d of relation \"%s\" does not exist",
9053 : : colNum, RelationGetRelationName(rel))));
9054 : : }
9055 : :
9056 : 95 : attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9057 : :
9058 : 95 : attnum = attrtuple->attnum;
9059 [ - + ]: 95 : if (attnum <= 0)
9060 [ # # ]: 0 : ereport(ERROR,
9061 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9062 : : errmsg("cannot alter system column \"%s\"",
9063 : : colName)));
9064 : :
9065 : : /*
9066 : : * Prevent this as long as the ANALYZE code skips virtual generated
9067 : : * columns.
9068 : : */
9069 [ - + ]: 95 : if (attrtuple->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
9070 [ # # ]: 0 : ereport(ERROR,
9071 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9072 : : errmsg("cannot alter statistics on virtual generated column \"%s\"",
9073 : : colName)));
9074 : :
9075 [ + + ]: 95 : if (rel->rd_rel->relkind == RELKIND_INDEX ||
9076 [ - + ]: 61 : rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
9077 : : {
9078 [ + + ]: 34 : if (attnum > rel->rd_index->indnkeyatts)
9079 [ + - ]: 4 : ereport(ERROR,
9080 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9081 : : errmsg("cannot alter statistics on included column \"%s\" of index \"%s\"",
9082 : : NameStr(attrtuple->attname), RelationGetRelationName(rel))));
9083 [ + + ]: 30 : else if (rel->rd_index->indkey.values[attnum - 1] != 0)
9084 [ + - ]: 12 : ereport(ERROR,
9085 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9086 : : errmsg("cannot alter statistics on non-expression column \"%s\" of index \"%s\"",
9087 : : NameStr(attrtuple->attname), RelationGetRelationName(rel)),
9088 : : errhint("Alter statistics on table column instead.")));
9089 : : }
9090 : :
9091 : : /* Build new tuple. */
9092 : 79 : memset(repl_null, false, sizeof(repl_null));
9093 : 79 : memset(repl_repl, false, sizeof(repl_repl));
9094 [ + + ]: 79 : if (!newtarget_default)
9095 : 48 : repl_val[Anum_pg_attribute_attstattarget - 1] = Int16GetDatum(newtarget);
9096 : : else
9097 : 31 : repl_null[Anum_pg_attribute_attstattarget - 1] = true;
9098 : 79 : repl_repl[Anum_pg_attribute_attstattarget - 1] = true;
9099 : 79 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
9100 : : repl_val, repl_null, repl_repl);
9101 : 79 : CatalogTupleUpdate(attrelation, &tuple->t_self, newtuple);
9102 : :
9103 [ - + ]: 79 : InvokeObjectPostAlterHook(RelationRelationId,
9104 : : RelationGetRelid(rel),
9105 : : attrtuple->attnum);
9106 : 79 : ObjectAddressSubSet(address, RelationRelationId,
9107 : : RelationGetRelid(rel), attnum);
9108 : :
9109 : 79 : heap_freetuple(newtuple);
9110 : :
9111 : 79 : ReleaseSysCache(tuple);
9112 : :
9113 : 79 : table_close(attrelation, RowExclusiveLock);
9114 : :
9115 : 79 : return address;
9116 : : }
9117 : :
9118 : : /*
9119 : : * Return value is the address of the modified column
9120 : : */
9121 : : static ObjectAddress
9122 : 21 : ATExecSetOptions(Relation rel, const char *colName, Node *options,
9123 : : bool isReset, LOCKMODE lockmode)
9124 : : {
9125 : : Relation attrelation;
9126 : : HeapTuple tuple,
9127 : : newtuple;
9128 : : Form_pg_attribute attrtuple;
9129 : : AttrNumber attnum;
9130 : : Datum datum,
9131 : : newOptions;
9132 : : bool isnull;
9133 : : ObjectAddress address;
9134 : : Datum repl_val[Natts_pg_attribute];
9135 : : bool repl_null[Natts_pg_attribute];
9136 : : bool repl_repl[Natts_pg_attribute];
9137 : :
9138 : 21 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9139 : :
9140 : 21 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9141 : :
9142 [ - + ]: 21 : if (!HeapTupleIsValid(tuple))
9143 [ # # ]: 0 : ereport(ERROR,
9144 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
9145 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
9146 : : colName, RelationGetRelationName(rel))));
9147 : 21 : attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9148 : :
9149 : 21 : attnum = attrtuple->attnum;
9150 [ - + ]: 21 : if (attnum <= 0)
9151 [ # # ]: 0 : ereport(ERROR,
9152 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9153 : : errmsg("cannot alter system column \"%s\"",
9154 : : colName)));
9155 : :
9156 : : /* Generate new proposed attoptions (text array) */
9157 : 21 : datum = SysCacheGetAttr(ATTNAME, tuple, Anum_pg_attribute_attoptions,
9158 : : &isnull);
9159 [ + + ]: 21 : newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
9160 : : castNode(List, options), NULL, NULL,
9161 : : false, isReset);
9162 : : /* Validate new options */
9163 : 21 : (void) attribute_reloptions(newOptions, true);
9164 : :
9165 : : /* Build new tuple. */
9166 : 21 : memset(repl_null, false, sizeof(repl_null));
9167 : 21 : memset(repl_repl, false, sizeof(repl_repl));
9168 [ + - ]: 21 : if (newOptions != (Datum) 0)
9169 : 21 : repl_val[Anum_pg_attribute_attoptions - 1] = newOptions;
9170 : : else
9171 : 0 : repl_null[Anum_pg_attribute_attoptions - 1] = true;
9172 : 21 : repl_repl[Anum_pg_attribute_attoptions - 1] = true;
9173 : 21 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrelation),
9174 : : repl_val, repl_null, repl_repl);
9175 : :
9176 : : /* Update system catalog. */
9177 : 21 : CatalogTupleUpdate(attrelation, &newtuple->t_self, newtuple);
9178 : :
9179 [ - + ]: 21 : InvokeObjectPostAlterHook(RelationRelationId,
9180 : : RelationGetRelid(rel),
9181 : : attrtuple->attnum);
9182 : 21 : ObjectAddressSubSet(address, RelationRelationId,
9183 : : RelationGetRelid(rel), attnum);
9184 : :
9185 : 21 : heap_freetuple(newtuple);
9186 : :
9187 : 21 : ReleaseSysCache(tuple);
9188 : :
9189 : 21 : table_close(attrelation, RowExclusiveLock);
9190 : :
9191 : 21 : return address;
9192 : : }
9193 : :
9194 : : /*
9195 : : * Helper function for ATExecSetStorage and ATExecSetCompression
9196 : : *
9197 : : * Set the attstorage and/or attcompression fields for index columns
9198 : : * associated with the specified table column.
9199 : : */
9200 : : static void
9201 : 269 : SetIndexStorageProperties(Relation rel, Relation attrelation,
9202 : : AttrNumber attnum,
9203 : : bool setstorage, char newstorage,
9204 : : bool setcompression, char newcompression,
9205 : : LOCKMODE lockmode)
9206 : : {
9207 : : ListCell *lc;
9208 : :
9209 [ + + + + : 330 : foreach(lc, RelationGetIndexList(rel))
+ + ]
9210 : : {
9211 : 61 : Oid indexoid = lfirst_oid(lc);
9212 : : Relation indrel;
9213 : 61 : AttrNumber indattnum = 0;
9214 : : HeapTuple tuple;
9215 : :
9216 : 61 : indrel = index_open(indexoid, lockmode);
9217 : :
9218 [ + + ]: 103 : for (int i = 0; i < indrel->rd_index->indnatts; i++)
9219 : : {
9220 [ + + ]: 65 : if (indrel->rd_index->indkey.values[i] == attnum)
9221 : : {
9222 : 23 : indattnum = i + 1;
9223 : 23 : break;
9224 : : }
9225 : : }
9226 : :
9227 [ + + ]: 61 : if (indattnum == 0)
9228 : : {
9229 : 38 : index_close(indrel, lockmode);
9230 : 38 : continue;
9231 : : }
9232 : :
9233 : 23 : tuple = SearchSysCacheCopyAttNum(RelationGetRelid(indrel), indattnum);
9234 : :
9235 [ + - ]: 23 : if (HeapTupleIsValid(tuple))
9236 : : {
9237 : 23 : Form_pg_attribute attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9238 : :
9239 [ + + ]: 23 : if (setstorage)
9240 : 15 : attrtuple->attstorage = newstorage;
9241 : :
9242 [ + + ]: 23 : if (setcompression)
9243 : 8 : attrtuple->attcompression = newcompression;
9244 : :
9245 : 23 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
9246 : :
9247 [ - + ]: 23 : InvokeObjectPostAlterHook(RelationRelationId,
9248 : : RelationGetRelid(rel),
9249 : : attrtuple->attnum);
9250 : :
9251 : 23 : heap_freetuple(tuple);
9252 : : }
9253 : :
9254 : 23 : index_close(indrel, lockmode);
9255 : : }
9256 : 269 : }
9257 : :
9258 : : /*
9259 : : * ALTER TABLE ALTER COLUMN SET STORAGE
9260 : : *
9261 : : * Return value is the address of the modified column
9262 : : */
9263 : : static ObjectAddress
9264 : 233 : ATExecSetStorage(Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
9265 : : {
9266 : : Relation attrelation;
9267 : : HeapTuple tuple;
9268 : : Form_pg_attribute attrtuple;
9269 : : AttrNumber attnum;
9270 : : ObjectAddress address;
9271 : :
9272 : 233 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
9273 : :
9274 : 233 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
9275 : :
9276 [ + + ]: 233 : if (!HeapTupleIsValid(tuple))
9277 [ + - ]: 8 : ereport(ERROR,
9278 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
9279 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
9280 : : colName, RelationGetRelationName(rel))));
9281 : 225 : attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
9282 : :
9283 : 225 : attnum = attrtuple->attnum;
9284 [ - + ]: 225 : if (attnum <= 0)
9285 [ # # ]: 0 : ereport(ERROR,
9286 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9287 : : errmsg("cannot alter system column \"%s\"",
9288 : : colName)));
9289 : :
9290 : 225 : attrtuple->attstorage = GetAttributeStorage(attrtuple->atttypid, strVal(newValue));
9291 : :
9292 : 225 : CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
9293 : :
9294 [ - + ]: 225 : InvokeObjectPostAlterHook(RelationRelationId,
9295 : : RelationGetRelid(rel),
9296 : : attrtuple->attnum);
9297 : :
9298 : : /*
9299 : : * Apply the change to indexes as well (only for simple index columns,
9300 : : * matching behavior of index.c ConstructTupleDescriptor()).
9301 : : */
9302 : 225 : SetIndexStorageProperties(rel, attrelation, attnum,
9303 : 225 : true, attrtuple->attstorage,
9304 : : false, 0,
9305 : : lockmode);
9306 : :
9307 : 225 : heap_freetuple(tuple);
9308 : :
9309 : 225 : table_close(attrelation, RowExclusiveLock);
9310 : :
9311 : 225 : ObjectAddressSubSet(address, RelationRelationId,
9312 : : RelationGetRelid(rel), attnum);
9313 : 225 : return address;
9314 : : }
9315 : :
9316 : :
9317 : : /*
9318 : : * ALTER TABLE DROP COLUMN
9319 : : *
9320 : : * DROP COLUMN cannot use the normal ALTER TABLE recursion mechanism,
9321 : : * because we have to decide at runtime whether to recurse or not depending
9322 : : * on whether attinhcount goes to zero or not. (We can't check this in a
9323 : : * static pre-pass because it won't handle multiple inheritance situations
9324 : : * correctly.)
9325 : : */
9326 : : static void
9327 : 1094 : ATPrepDropColumn(List **wqueue, Relation rel, bool recurse, bool recursing,
9328 : : AlterTableCmd *cmd, LOCKMODE lockmode,
9329 : : AlterTableUtilityContext *context)
9330 : : {
9331 [ + + + + ]: 1094 : if (rel->rd_rel->reloftype && !recursing)
9332 [ + - ]: 4 : ereport(ERROR,
9333 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9334 : : errmsg("cannot drop column from typed table")));
9335 : :
9336 [ + + ]: 1090 : if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
9337 : 54 : ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
9338 : :
9339 [ + + ]: 1086 : if (recurse)
9340 : 929 : cmd->recurse = true;
9341 : 1086 : }
9342 : :
9343 : : /*
9344 : : * Drops column 'colName' from relation 'rel' and returns the address of the
9345 : : * dropped column. The column is also dropped (or marked as no longer
9346 : : * inherited from relation) from the relation's inheritance children, if any.
9347 : : *
9348 : : * In the recursive invocations for inheritance child relations, instead of
9349 : : * dropping the column directly (if to be dropped at all), its object address
9350 : : * is added to 'addrs', which must be non-NULL in such invocations. All
9351 : : * columns are dropped at the same time after all the children have been
9352 : : * checked recursively.
9353 : : */
9354 : : static ObjectAddress
9355 : 1459 : ATExecDropColumn(List **wqueue, Relation rel, const char *colName,
9356 : : DropBehavior behavior,
9357 : : bool recurse, bool recursing,
9358 : : bool missing_ok, LOCKMODE lockmode,
9359 : : ObjectAddresses *addrs)
9360 : : {
9361 : : HeapTuple tuple;
9362 : : Form_pg_attribute targetatt;
9363 : : AttrNumber attnum;
9364 : : List *children;
9365 : : ObjectAddress object;
9366 : : bool is_expr;
9367 : :
9368 : : /* At top level, permission check was done in ATPrepCmd, else do it */
9369 [ + + ]: 1459 : if (recursing)
9370 : 373 : ATSimplePermissions(AT_DropColumn, rel,
9371 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
9372 : :
9373 : : /* Initialize addrs on the first invocation */
9374 : : Assert(!recursing || addrs != NULL);
9375 : :
9376 : : /* since this function recurses, it could be driven to stack overflow */
9377 : 1459 : check_stack_depth();
9378 : :
9379 [ + + ]: 1459 : if (!recursing)
9380 : 1086 : addrs = new_object_addresses();
9381 : :
9382 : : /*
9383 : : * get the number of the attribute
9384 : : */
9385 : 1459 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9386 [ + + ]: 1459 : if (!HeapTupleIsValid(tuple))
9387 : : {
9388 [ + + ]: 40 : if (!missing_ok)
9389 : : {
9390 [ + - ]: 24 : ereport(ERROR,
9391 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
9392 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
9393 : : colName, RelationGetRelationName(rel))));
9394 : : }
9395 : : else
9396 : : {
9397 [ + - ]: 16 : ereport(NOTICE,
9398 : : (errmsg("column \"%s\" of relation \"%s\" does not exist, skipping",
9399 : : colName, RelationGetRelationName(rel))));
9400 : 16 : return InvalidObjectAddress;
9401 : : }
9402 : : }
9403 : 1419 : targetatt = (Form_pg_attribute) GETSTRUCT(tuple);
9404 : :
9405 : 1419 : attnum = targetatt->attnum;
9406 : :
9407 : : /* Can't drop a system attribute */
9408 [ + + ]: 1419 : if (attnum <= 0)
9409 [ + - ]: 4 : ereport(ERROR,
9410 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9411 : : errmsg("cannot drop system column \"%s\"",
9412 : : colName)));
9413 : :
9414 : : /*
9415 : : * Don't drop inherited columns, unless recursing (presumably from a drop
9416 : : * of the parent column)
9417 : : */
9418 [ + + + + ]: 1415 : if (targetatt->attinhcount > 0 && !recursing)
9419 [ + - ]: 32 : ereport(ERROR,
9420 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9421 : : errmsg("cannot drop inherited column \"%s\"",
9422 : : colName)));
9423 : :
9424 : : /*
9425 : : * Don't drop columns used in the partition key, either. (If we let this
9426 : : * go through, the key column's dependencies would cause a cascaded drop
9427 : : * of the whole table, which is surely not what the user expected.)
9428 : : */
9429 [ + + ]: 1383 : if (has_partition_attrs(rel,
9430 : : bms_make_singleton(attnum - FirstLowInvalidHeapAttributeNumber),
9431 : : &is_expr))
9432 [ + - ]: 20 : ereport(ERROR,
9433 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9434 : : errmsg("cannot drop column \"%s\" because it is part of the partition key of relation \"%s\"",
9435 : : colName, RelationGetRelationName(rel))));
9436 : :
9437 : 1363 : ReleaseSysCache(tuple);
9438 : :
9439 : : /*
9440 : : * Propagate to children as appropriate. Unlike most other ALTER
9441 : : * routines, we have to do this one level of recursion at a time; we can't
9442 : : * use find_all_inheritors to do it in one pass.
9443 : : */
9444 : : children =
9445 : 1363 : find_inheritance_children(RelationGetRelid(rel), lockmode);
9446 : :
9447 [ + + ]: 1363 : if (children)
9448 : : {
9449 : : Relation attr_rel;
9450 : : ListCell *child;
9451 : :
9452 : : /*
9453 : : * In case of a partitioned table, the column must be dropped from the
9454 : : * partitions as well.
9455 : : */
9456 [ + + + + ]: 204 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !recurse)
9457 [ + - ]: 4 : ereport(ERROR,
9458 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9459 : : errmsg("cannot drop column from only the partitioned table when partitions exist"),
9460 : : errhint("Do not specify the ONLY keyword.")));
9461 : :
9462 : 200 : attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
9463 [ + - + + : 593 : foreach(child, children)
+ + ]
9464 : : {
9465 : 397 : Oid childrelid = lfirst_oid(child);
9466 : : Relation childrel;
9467 : : Form_pg_attribute childatt;
9468 : :
9469 : : /* find_inheritance_children already got lock */
9470 : 397 : childrel = table_open(childrelid, NoLock);
9471 : 397 : CheckAlterTableIsSafe(childrel);
9472 : :
9473 : 397 : tuple = SearchSysCacheCopyAttName(childrelid, colName);
9474 [ - + ]: 397 : if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
9475 [ # # ]: 0 : elog(ERROR, "cache lookup failed for attribute \"%s\" of relation %u",
9476 : : colName, childrelid);
9477 : 397 : childatt = (Form_pg_attribute) GETSTRUCT(tuple);
9478 : :
9479 [ - + ]: 397 : if (childatt->attinhcount <= 0) /* shouldn't happen */
9480 [ # # ]: 0 : elog(ERROR, "relation %u has non-inherited attribute \"%s\"",
9481 : : childrelid, colName);
9482 : :
9483 [ + + ]: 397 : if (recurse)
9484 : : {
9485 : : /*
9486 : : * If the child column has other definition sources, just
9487 : : * decrement its inheritance count; if not, recurse to delete
9488 : : * it.
9489 : : */
9490 [ + - + + ]: 381 : if (childatt->attinhcount == 1 && !childatt->attislocal)
9491 : : {
9492 : : /* Time to delete this child column, too */
9493 : 373 : ATExecDropColumn(wqueue, childrel, colName,
9494 : : behavior, true, true,
9495 : : false, lockmode, addrs);
9496 : : }
9497 : : else
9498 : : {
9499 : : /* Child column must survive my deletion */
9500 : 8 : childatt->attinhcount--;
9501 : :
9502 : 8 : CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
9503 : :
9504 : : /* Make update visible */
9505 : 8 : CommandCounterIncrement();
9506 : : }
9507 : : }
9508 : : else
9509 : : {
9510 : : /*
9511 : : * If we were told to drop ONLY in this table (no recursion),
9512 : : * we need to mark the inheritors' attributes as locally
9513 : : * defined rather than inherited.
9514 : : */
9515 : 16 : childatt->attinhcount--;
9516 : 16 : childatt->attislocal = true;
9517 : :
9518 : 16 : CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
9519 : :
9520 : : /* Make update visible */
9521 : 16 : CommandCounterIncrement();
9522 : : }
9523 : :
9524 : 393 : heap_freetuple(tuple);
9525 : :
9526 : 393 : table_close(childrel, NoLock);
9527 : : }
9528 : 196 : table_close(attr_rel, RowExclusiveLock);
9529 : : }
9530 : :
9531 : : /* Add object to delete */
9532 : 1355 : object.classId = RelationRelationId;
9533 : 1355 : object.objectId = RelationGetRelid(rel);
9534 : 1355 : object.objectSubId = attnum;
9535 : 1355 : add_exact_object_address(&object, addrs);
9536 : :
9537 [ + + ]: 1355 : if (!recursing)
9538 : : {
9539 : : /* Recursion has ended, drop everything that was collected */
9540 : 986 : performMultipleDeletions(addrs, behavior, 0);
9541 : 950 : free_object_addresses(addrs);
9542 : : }
9543 : :
9544 : 1319 : return object;
9545 : : }
9546 : :
9547 : : /*
9548 : : * Prepare to add a primary key on a table, by adding not-null constraints
9549 : : * on all columns.
9550 : : *
9551 : : * The not-null constraints for a primary key must cover the whole inheritance
9552 : : * hierarchy (failing to ensure that leads to funny corner cases). For the
9553 : : * normal case where we're asked to recurse, this routine checks if the
9554 : : * not-null constraints exist already, and if not queues a requirement for
9555 : : * them to be created by phase 2.
9556 : : *
9557 : : * For the case where we're asked not to recurse, we verify that a not-null
9558 : : * constraint exists on each column of each (direct) child table, throwing an
9559 : : * error if not. Not throwing an error would also work, because a not-null
9560 : : * constraint would be created anyway, but it'd cause a silent scan of the
9561 : : * child table to verify absence of nulls. We prefer to let the user know so
9562 : : * that they can add the constraint manually without having to hold
9563 : : * AccessExclusiveLock while at it.
9564 : : *
9565 : : * However, it's also important that we do not acquire locks on children if
9566 : : * the not-null constraints already exist on the parent, to avoid risking
9567 : : * deadlocks during parallel pg_restore of PKs on partitioned tables.
9568 : : */
9569 : : static void
9570 : 10060 : ATPrepAddPrimaryKey(List **wqueue, Relation rel, AlterTableCmd *cmd,
9571 : : bool recurse, LOCKMODE lockmode,
9572 : : AlterTableUtilityContext *context)
9573 : : {
9574 : : Constraint *pkconstr;
9575 : 10060 : List *children = NIL;
9576 : 10060 : bool got_children = false;
9577 : :
9578 : 10060 : pkconstr = castNode(Constraint, cmd->def);
9579 [ + + ]: 10060 : if (pkconstr->contype != CONSTR_PRIMARY)
9580 : 5979 : return;
9581 : :
9582 : : /* Verify that columns are not-null, or request that they be made so */
9583 [ + + + + : 8743 : foreach_node(String, column, pkconstr->keys)
+ + ]
9584 : : {
9585 : : AlterTableCmd *newcmd;
9586 : : Constraint *nnconstr;
9587 : : HeapTuple tuple;
9588 : :
9589 : : /*
9590 : : * First check if a suitable constraint exists. If it does, we don't
9591 : : * need to request another one. We do need to bail out if it's not
9592 : : * valid, though.
9593 : : */
9594 : 621 : tuple = findNotNullConstraint(RelationGetRelid(rel), strVal(column));
9595 [ + + ]: 621 : if (tuple != NULL)
9596 : : {
9597 : 294 : verifyNotNullPKCompatible(tuple, strVal(column));
9598 : :
9599 : : /* All good with this one; don't request another */
9600 : 286 : heap_freetuple(tuple);
9601 : 286 : continue;
9602 : : }
9603 [ + + ]: 327 : else if (!recurse)
9604 : : {
9605 : : /*
9606 : : * No constraint on this column. Asked not to recurse, we won't
9607 : : * create one here, but verify that all children have one.
9608 : : */
9609 [ + - ]: 24 : if (!got_children)
9610 : : {
9611 : 24 : children = find_inheritance_children(RelationGetRelid(rel),
9612 : : lockmode);
9613 : : /* only search for children on the first time through */
9614 : 24 : got_children = true;
9615 : : }
9616 : :
9617 [ + - + + : 48 : foreach_oid(childrelid, children)
+ + ]
9618 : : {
9619 : : HeapTuple tup;
9620 : :
9621 : 24 : tup = findNotNullConstraint(childrelid, strVal(column));
9622 [ + + ]: 24 : if (!tup)
9623 [ + - ]: 4 : ereport(ERROR,
9624 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9625 : : errmsg("column \"%s\" of table \"%s\" is not marked NOT NULL",
9626 : : strVal(column), get_rel_name(childrelid)));
9627 : : /* verify it's good enough */
9628 : 20 : verifyNotNullPKCompatible(tup, strVal(column));
9629 : : }
9630 : : }
9631 : :
9632 : : /* This column is not already not-null, so add it to the queue */
9633 : 315 : nnconstr = makeNotNullConstraint(column);
9634 : :
9635 : 315 : newcmd = makeNode(AlterTableCmd);
9636 : 315 : newcmd->subtype = AT_AddConstraint;
9637 : : /* note we force recurse=true here; see above */
9638 : 315 : newcmd->recurse = true;
9639 : 315 : newcmd->def = (Node *) nnconstr;
9640 : :
9641 : 315 : ATPrepCmd(wqueue, rel, newcmd, true, false, lockmode, context);
9642 : : }
9643 : : }
9644 : :
9645 : : /*
9646 : : * Verify whether the given not-null constraint is compatible with a
9647 : : * primary key. If not, an error is thrown.
9648 : : */
9649 : : static void
9650 : 314 : verifyNotNullPKCompatible(HeapTuple tuple, const char *colname)
9651 : : {
9652 : 314 : Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(tuple);
9653 : :
9654 [ - + ]: 314 : if (conForm->contype != CONSTRAINT_NOTNULL)
9655 [ # # ]: 0 : elog(ERROR, "constraint %u is not a not-null constraint", conForm->oid);
9656 : :
9657 : : /* a NO INHERIT constraint is no good */
9658 [ + + ]: 314 : if (conForm->connoinherit)
9659 [ + - ]: 8 : ereport(ERROR,
9660 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9661 : : errmsg("cannot create primary key on column \"%s\"", colname),
9662 : : /*- translator: fourth %s is a constraint characteristic such as NOT VALID */
9663 : : errdetail("The constraint \"%s\" on column \"%s\" of table \"%s\", marked %s, is incompatible with a primary key.",
9664 : : NameStr(conForm->conname), colname,
9665 : : get_rel_name(conForm->conrelid), "NO INHERIT"),
9666 : : errhint("You might need to make the existing constraint inheritable using %s.",
9667 : : "ALTER TABLE ... ALTER CONSTRAINT ... INHERIT"));
9668 : :
9669 : : /* an unvalidated constraint is no good */
9670 [ + + ]: 306 : if (!conForm->convalidated)
9671 [ + - ]: 8 : ereport(ERROR,
9672 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9673 : : errmsg("cannot create primary key on column \"%s\"", colname),
9674 : : /*- translator: fourth %s is a constraint characteristic such as NOT VALID */
9675 : : errdetail("The constraint \"%s\" on column \"%s\" of table \"%s\", marked %s, is incompatible with a primary key.",
9676 : : NameStr(conForm->conname), colname,
9677 : : get_rel_name(conForm->conrelid), "NOT VALID"),
9678 : : errhint("You might need to validate it using %s.",
9679 : : "ALTER TABLE ... VALIDATE CONSTRAINT"));
9680 : 298 : }
9681 : :
9682 : : /*
9683 : : * ALTER TABLE ADD INDEX
9684 : : *
9685 : : * There is no such command in the grammar, but parse_utilcmd.c converts
9686 : : * UNIQUE and PRIMARY KEY constraints into AT_AddIndex subcommands. This lets
9687 : : * us schedule creation of the index at the appropriate time during ALTER.
9688 : : *
9689 : : * Return value is the address of the new index.
9690 : : */
9691 : : static ObjectAddress
9692 : 1108 : ATExecAddIndex(AlteredTableInfo *tab, Relation rel,
9693 : : IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
9694 : : {
9695 : : bool check_rights;
9696 : : bool skip_build;
9697 : : bool quiet;
9698 : : ObjectAddress address;
9699 : :
9700 : : Assert(IsA(stmt, IndexStmt));
9701 : : Assert(!stmt->concurrent);
9702 : :
9703 : : /* The IndexStmt has already been through transformIndexStmt */
9704 : : Assert(stmt->transformed);
9705 : :
9706 : : /* suppress schema rights check when rebuilding existing index */
9707 : 1108 : check_rights = !is_rebuild;
9708 : : /* skip index build if phase 3 will do it or we're reusing an old one */
9709 [ + + + + ]: 1108 : skip_build = tab->rewrite > 0 || RelFileNumberIsValid(stmt->oldNumber);
9710 : : /* suppress notices when rebuilding existing index */
9711 : 1108 : quiet = is_rebuild;
9712 : :
9713 : 1108 : address = DefineIndex(NULL,
9714 : : RelationGetRelid(rel),
9715 : : stmt,
9716 : : InvalidOid, /* no predefined OID */
9717 : : InvalidOid, /* no parent index */
9718 : : InvalidOid, /* no parent constraint */
9719 : : -1, /* total_parts unknown */
9720 : : true, /* is_alter_table */
9721 : : check_rights,
9722 : : false, /* check_not_in_use - we did it already */
9723 : : skip_build,
9724 : : quiet);
9725 : :
9726 : : /*
9727 : : * If TryReuseIndex() stashed a relfilenumber for us, we used it for the
9728 : : * new index instead of building from scratch. Restore associated fields.
9729 : : * This may store InvalidSubTransactionId in both fields, in which case
9730 : : * relcache.c will assume it can rebuild the relcache entry. Hence, do
9731 : : * this after the CCI that made catalog rows visible to any rebuild. The
9732 : : * DROP of the old edition of this index will have scheduled the storage
9733 : : * for deletion at commit, so cancel that pending deletion.
9734 : : */
9735 [ + + ]: 995 : if (RelFileNumberIsValid(stmt->oldNumber))
9736 : : {
9737 : 49 : Relation irel = index_open(address.objectId, NoLock);
9738 : :
9739 : 49 : irel->rd_createSubid = stmt->oldCreateSubid;
9740 : 49 : irel->rd_firstRelfilelocatorSubid = stmt->oldFirstRelfilelocatorSubid;
9741 : 49 : RelationPreserveStorage(irel->rd_locator, true);
9742 : 49 : index_close(irel, NoLock);
9743 : : }
9744 : :
9745 : 995 : return address;
9746 : : }
9747 : :
9748 : : /*
9749 : : * ALTER TABLE ADD STATISTICS
9750 : : *
9751 : : * This is no such command in the grammar, but we use this internally to add
9752 : : * AT_ReAddStatistics subcommands to rebuild extended statistics after a table
9753 : : * column type change.
9754 : : */
9755 : : static ObjectAddress
9756 : 57 : ATExecAddStatistics(AlteredTableInfo *tab, Relation rel,
9757 : : CreateStatsStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
9758 : : {
9759 : : ObjectAddress address;
9760 : :
9761 : : Assert(IsA(stmt, CreateStatsStmt));
9762 : :
9763 : : /* The CreateStatsStmt has already been through transformStatsStmt */
9764 : : Assert(stmt->transformed);
9765 : :
9766 : : /* The owner must be set to the original statistics owner */
9767 : : Assert(OidIsValid(stmt->owner));
9768 : :
9769 : 57 : address = CreateStatistics(list_make1_oid(RelationGetRelid(rel)),
9770 : 57 : stmt, !is_rebuild);
9771 : :
9772 : 57 : return address;
9773 : : }
9774 : :
9775 : : /*
9776 : : * ALTER TABLE ADD CONSTRAINT USING INDEX
9777 : : *
9778 : : * Returns the address of the new constraint.
9779 : : */
9780 : : static ObjectAddress
9781 : 6323 : ATExecAddIndexConstraint(AlteredTableInfo *tab, Relation rel,
9782 : : IndexStmt *stmt, LOCKMODE lockmode)
9783 : : {
9784 : 6323 : Oid index_oid = stmt->indexOid;
9785 : : Relation indexRel;
9786 : : char *indexName;
9787 : : IndexInfo *indexInfo;
9788 : : char *constraintName;
9789 : : char constraintType;
9790 : : ObjectAddress address;
9791 : : uint16 flags;
9792 : :
9793 : : Assert(IsA(stmt, IndexStmt));
9794 : : Assert(OidIsValid(index_oid));
9795 : : Assert(stmt->isconstraint);
9796 : :
9797 : : /*
9798 : : * Doing this on partitioned tables is not a simple feature to implement,
9799 : : * so let's punt for now.
9800 : : */
9801 [ + + ]: 6323 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
9802 [ + - ]: 4 : ereport(ERROR,
9803 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9804 : : errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX is not supported on partitioned tables")));
9805 : :
9806 : 6319 : indexRel = index_open(index_oid, AccessShareLock);
9807 : :
9808 : 6319 : indexName = pstrdup(RelationGetRelationName(indexRel));
9809 : :
9810 : 6319 : indexInfo = BuildIndexInfo(indexRel);
9811 : :
9812 : : /* this should have been checked at parse time */
9813 [ - + ]: 6319 : if (!indexInfo->ii_Unique)
9814 [ # # ]: 0 : elog(ERROR, "index \"%s\" is not unique", indexName);
9815 : :
9816 : : /*
9817 : : * Determine name to assign to constraint. We require a constraint to
9818 : : * have the same name as the underlying index; therefore, use the index's
9819 : : * existing name as the default constraint name, and if the user
9820 : : * explicitly gives some other name for the constraint, rename the index
9821 : : * to match.
9822 : : */
9823 : 6319 : constraintName = stmt->idxname;
9824 [ + + ]: 6319 : if (constraintName == NULL)
9825 : 6302 : constraintName = indexName;
9826 [ + + ]: 17 : else if (strcmp(constraintName, indexName) != 0)
9827 : : {
9828 [ + - ]: 13 : ereport(NOTICE,
9829 : : (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
9830 : : indexName, constraintName)));
9831 : 13 : RenameRelationInternal(index_oid, constraintName, false, true);
9832 : : }
9833 : :
9834 : : /* Extra checks needed if making primary key */
9835 [ + + ]: 6319 : if (stmt->primary)
9836 : 3570 : index_check_primary_key(rel, indexInfo, true, stmt);
9837 : :
9838 : : /* Note we currently don't support EXCLUSION constraints here */
9839 [ + + ]: 6315 : if (stmt->primary)
9840 : 3566 : constraintType = CONSTRAINT_PRIMARY;
9841 : : else
9842 : 2749 : constraintType = CONSTRAINT_UNIQUE;
9843 : :
9844 : : /* Create the catalog entries for the constraint */
9845 : 6315 : flags = INDEX_CONSTR_CREATE_UPDATE_INDEX |
9846 : : INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS |
9847 [ - + ]: 12630 : (stmt->initdeferred ? INDEX_CONSTR_CREATE_INIT_DEFERRED : 0) |
9848 [ - + ]: 6315 : (stmt->deferrable ? INDEX_CONSTR_CREATE_DEFERRABLE : 0) |
9849 : 6315 : (stmt->primary ? INDEX_CONSTR_CREATE_MARK_AS_PRIMARY : 0);
9850 : :
9851 : 6315 : address = index_constraint_create(rel,
9852 : : index_oid,
9853 : : InvalidOid,
9854 : : indexInfo,
9855 : : constraintName,
9856 : : constraintType,
9857 : : flags,
9858 : : allowSystemTableMods,
9859 : : false); /* is_internal */
9860 : :
9861 : 6315 : index_close(indexRel, NoLock);
9862 : :
9863 : 6315 : return address;
9864 : : }
9865 : :
9866 : : /*
9867 : : * ALTER TABLE ADD CONSTRAINT
9868 : : *
9869 : : * Return value is the address of the new constraint; if no constraint was
9870 : : * added, InvalidObjectAddress is returned.
9871 : : */
9872 : : static ObjectAddress
9873 : 8191 : ATExecAddConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
9874 : : Constraint *newConstraint, bool recurse, bool is_readd,
9875 : : LOCKMODE lockmode)
9876 : : {
9877 : 8191 : ObjectAddress address = InvalidObjectAddress;
9878 : :
9879 : : Assert(IsA(newConstraint, Constraint));
9880 : :
9881 : : /*
9882 : : * Currently, we only expect to see CONSTR_CHECK, CONSTR_NOTNULL and
9883 : : * CONSTR_FOREIGN nodes arriving here (see the preprocessing done in
9884 : : * parse_utilcmd.c).
9885 : : */
9886 [ + + - ]: 8191 : switch (newConstraint->contype)
9887 : : {
9888 : 6299 : case CONSTR_CHECK:
9889 : : case CONSTR_NOTNULL:
9890 : : address =
9891 : 6299 : ATAddCheckNNConstraint(wqueue, tab, rel,
9892 : : newConstraint, recurse, false, is_readd,
9893 : : lockmode);
9894 : 6199 : break;
9895 : :
9896 : 1892 : case CONSTR_FOREIGN:
9897 : :
9898 : : /*
9899 : : * Assign or validate constraint name
9900 : : */
9901 [ + + ]: 1892 : if (newConstraint->conname)
9902 : : {
9903 [ - + ]: 762 : if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
9904 : : RelationGetRelid(rel),
9905 : 762 : newConstraint->conname))
9906 [ # # ]: 0 : ereport(ERROR,
9907 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
9908 : : errmsg("constraint \"%s\" for relation \"%s\" already exists",
9909 : : newConstraint->conname,
9910 : : RelationGetRelationName(rel))));
9911 : : }
9912 : : else
9913 : 1130 : newConstraint->conname =
9914 : 1130 : ChooseConstraintName(RelationGetRelationName(rel),
9915 : 1130 : ChooseForeignKeyConstraintNameAddition(newConstraint->fk_attrs),
9916 : : "fkey",
9917 : 1130 : RelationGetNamespace(rel),
9918 : : NIL);
9919 : :
9920 : 1892 : address = ATAddForeignKeyConstraint(wqueue, tab, rel,
9921 : : newConstraint,
9922 : : recurse, false,
9923 : : lockmode);
9924 : 1523 : break;
9925 : :
9926 : 0 : default:
9927 [ # # ]: 0 : elog(ERROR, "unrecognized constraint type: %d",
9928 : : (int) newConstraint->contype);
9929 : : }
9930 : :
9931 : 7722 : return address;
9932 : : }
9933 : :
9934 : : /*
9935 : : * Generate the column-name portion of the constraint name for a new foreign
9936 : : * key given the list of column names that reference the referenced
9937 : : * table. This will be passed to ChooseConstraintName along with the parent
9938 : : * table name and the "fkey" suffix.
9939 : : *
9940 : : * We know that less than NAMEDATALEN characters will actually be used, so we
9941 : : * can truncate the result once we've generated that many.
9942 : : *
9943 : : * XXX see also ChooseExtendedStatisticNameAddition and
9944 : : * ChooseIndexNameAddition.
9945 : : */
9946 : : static char *
9947 : 1130 : ChooseForeignKeyConstraintNameAddition(List *colnames)
9948 : : {
9949 : : char buf[NAMEDATALEN * 2];
9950 : 1130 : int buflen = 0;
9951 : : ListCell *lc;
9952 : :
9953 : 1130 : buf[0] = '\0';
9954 [ + - + + : 2554 : foreach(lc, colnames)
+ + ]
9955 : : {
9956 : 1424 : const char *name = strVal(lfirst(lc));
9957 : :
9958 [ + + ]: 1424 : if (buflen > 0)
9959 : 294 : buf[buflen++] = '_'; /* insert _ between names */
9960 : :
9961 : : /*
9962 : : * At this point we have buflen <= NAMEDATALEN. name should be less
9963 : : * than NAMEDATALEN already, but use strlcpy for paranoia.
9964 : : */
9965 : 1424 : strlcpy(buf + buflen, name, NAMEDATALEN);
9966 : 1424 : buflen += strlen(buf + buflen);
9967 [ - + ]: 1424 : if (buflen >= NAMEDATALEN)
9968 : 0 : break;
9969 : : }
9970 : 1130 : return pstrdup(buf);
9971 : : }
9972 : :
9973 : : /*
9974 : : * Add a check or not-null constraint to a single table and its children.
9975 : : * Returns the address of the constraint added to the parent relation,
9976 : : * if one gets added, or InvalidObjectAddress otherwise.
9977 : : *
9978 : : * Subroutine for ATExecAddConstraint.
9979 : : *
9980 : : * We must recurse to child tables during execution, rather than using
9981 : : * ALTER TABLE's normal prep-time recursion. The reason is that all the
9982 : : * constraints *must* be given the same name, else they won't be seen as
9983 : : * related later. If the user didn't explicitly specify a name, then
9984 : : * AddRelationNewConstraints would normally assign different names to the
9985 : : * child constraints. To fix that, we must capture the name assigned at
9986 : : * the parent table and pass that down.
9987 : : */
9988 : : static ObjectAddress
9989 : 6905 : ATAddCheckNNConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
9990 : : Constraint *constr, bool recurse, bool recursing,
9991 : : bool is_readd, LOCKMODE lockmode)
9992 : : {
9993 : : List *newcons;
9994 : : ListCell *lcon;
9995 : : List *children;
9996 : : ListCell *child;
9997 : 6905 : ObjectAddress address = InvalidObjectAddress;
9998 : :
9999 : : /* Guard against stack overflow due to overly deep inheritance tree. */
10000 : 6905 : check_stack_depth();
10001 : :
10002 : : /* At top level, permission check was done in ATPrepCmd, else do it */
10003 [ + + ]: 6905 : if (recursing)
10004 : 606 : ATSimplePermissions(AT_AddConstraint, rel,
10005 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
10006 : :
10007 : : /*
10008 : : * Call AddRelationNewConstraints to do the work, making sure it works on
10009 : : * a copy of the Constraint so transformExpr can't modify the original. It
10010 : : * returns a list of cooked constraints.
10011 : : *
10012 : : * If the constraint ends up getting merged with a pre-existing one, it's
10013 : : * omitted from the returned list, which is what we want: we do not need
10014 : : * to do any validation work. That can only happen at child tables,
10015 : : * though, since we disallow merging at the top level.
10016 : : */
10017 : 6905 : newcons = AddRelationNewConstraints(rel, NIL,
10018 : : list_make1(copyObject(constr)),
10019 [ + + ]: 6905 : recursing || is_readd, /* allow_merge */
10020 : : !recursing, /* is_local */
10021 : : is_readd, /* is_internal */
10022 [ + + ]: 13810 : NULL); /* queryString not available
10023 : : * here */
10024 : :
10025 : : /* we don't expect more than one constraint here */
10026 : : Assert(list_length(newcons) <= 1);
10027 : :
10028 : : /* Add each to-be-validated constraint to Phase 3's queue */
10029 [ + + + + : 13488 : foreach(lcon, newcons)
+ + ]
10030 : : {
10031 : 6679 : CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
10032 : :
10033 [ + + + + ]: 6679 : if (!ccon->skip_validation && ccon->contype != CONSTR_NOTNULL)
10034 : : {
10035 : : NewConstraint *newcon;
10036 : :
10037 : 695 : newcon = palloc0_object(NewConstraint);
10038 : 695 : newcon->name = ccon->name;
10039 : 695 : newcon->contype = ccon->contype;
10040 : 695 : newcon->qual = ccon->expr;
10041 : :
10042 : 695 : tab->constraints = lappend(tab->constraints, newcon);
10043 : : }
10044 : :
10045 : : /* Save the actually assigned name if it was defaulted */
10046 [ + + ]: 6679 : if (constr->conname == NULL)
10047 : 5382 : constr->conname = ccon->name;
10048 : :
10049 : : /*
10050 : : * If adding a valid not-null constraint, set the pg_attribute flag
10051 : : * and tell phase 3 to verify existing rows, if needed. For an
10052 : : * invalid constraint, just set attnotnull, without queueing
10053 : : * verification.
10054 : : */
10055 [ + + ]: 6679 : if (constr->contype == CONSTR_NOTNULL)
10056 : 5719 : set_attnotnull(wqueue, rel, ccon->attnum,
10057 : 5719 : !constr->skip_validation);
10058 : :
10059 : 6679 : ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
10060 : : }
10061 : :
10062 : : /* At this point we must have a locked-down name to use */
10063 : : Assert(newcons == NIL || constr->conname != NULL);
10064 : :
10065 : : /* Advance command counter in case same table is visited multiple times */
10066 : 6809 : CommandCounterIncrement();
10067 : :
10068 : : /*
10069 : : * If the constraint got merged with an existing constraint, we're done.
10070 : : * We mustn't recurse to child tables in this case, because they've
10071 : : * already got the constraint, and visiting them again would lead to an
10072 : : * incorrect value for coninhcount.
10073 : : */
10074 [ + + ]: 6809 : if (newcons == NIL)
10075 : 130 : return address;
10076 : :
10077 : : /*
10078 : : * If adding a NO INHERIT constraint, no need to find our children.
10079 : : */
10080 [ + + ]: 6679 : if (constr->is_no_inherit)
10081 : 56 : return address;
10082 : :
10083 : : /*
10084 : : * Propagate to children as appropriate. Unlike most other ALTER
10085 : : * routines, we have to do this one level of recursion at a time; we can't
10086 : : * use find_all_inheritors to do it in one pass.
10087 : : */
10088 : : children =
10089 : 6623 : find_inheritance_children(RelationGetRelid(rel), lockmode);
10090 : :
10091 : : /*
10092 : : * Check if ONLY was specified with ALTER TABLE. If so, allow the
10093 : : * constraint creation only if there are no children currently. Error out
10094 : : * otherwise.
10095 : : */
10096 [ + + + + ]: 6623 : if (!recurse && children != NIL)
10097 [ + - ]: 4 : ereport(ERROR,
10098 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10099 : : errmsg("constraint must be added to child tables too")));
10100 : :
10101 : : /*
10102 : : * Recurse to create the constraint on each child.
10103 : : */
10104 [ + + + + : 7205 : foreach(child, children)
+ + ]
10105 : : {
10106 : 606 : Oid childrelid = lfirst_oid(child);
10107 : : Relation childrel;
10108 : : AlteredTableInfo *childtab;
10109 : :
10110 : : /* find_inheritance_children already got lock */
10111 : 606 : childrel = table_open(childrelid, NoLock);
10112 : 606 : CheckAlterTableIsSafe(childrel);
10113 : :
10114 : : /* Find or create work queue entry for this table */
10115 : 606 : childtab = ATGetQueueEntry(wqueue, childrel);
10116 : :
10117 : : /* Recurse to this child */
10118 : 606 : ATAddCheckNNConstraint(wqueue, childtab, childrel,
10119 : : constr, recurse, true, is_readd, lockmode);
10120 : :
10121 : 586 : table_close(childrel, NoLock);
10122 : : }
10123 : :
10124 : 6599 : return address;
10125 : : }
10126 : :
10127 : : /*
10128 : : * Add a foreign-key constraint to a single table; return the new constraint's
10129 : : * address.
10130 : : *
10131 : : * Subroutine for ATExecAddConstraint. Must already hold exclusive
10132 : : * lock on the rel, and have done appropriate validity checks for it.
10133 : : * We do permissions checks here, however.
10134 : : *
10135 : : * When the referenced or referencing tables (or both) are partitioned,
10136 : : * multiple pg_constraint rows are required -- one for each partitioned table
10137 : : * and each partition on each side (fortunately, not one for every combination
10138 : : * thereof). We also need action triggers on each leaf partition on the
10139 : : * referenced side, and check triggers on each leaf partition on the
10140 : : * referencing side.
10141 : : */
10142 : : static ObjectAddress
10143 : 1892 : ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
10144 : : Constraint *fkconstraint,
10145 : : bool recurse, bool recursing, LOCKMODE lockmode)
10146 : : {
10147 : : Relation pkrel;
10148 : 1892 : int16 pkattnum[INDEX_MAX_KEYS] = {0};
10149 : 1892 : int16 fkattnum[INDEX_MAX_KEYS] = {0};
10150 : 1892 : Oid pktypoid[INDEX_MAX_KEYS] = {0};
10151 : 1892 : Oid fktypoid[INDEX_MAX_KEYS] = {0};
10152 : 1892 : Oid pkcolloid[INDEX_MAX_KEYS] = {0};
10153 : 1892 : Oid fkcolloid[INDEX_MAX_KEYS] = {0};
10154 : 1892 : Oid opclasses[INDEX_MAX_KEYS] = {0};
10155 : 1892 : Oid pfeqoperators[INDEX_MAX_KEYS] = {0};
10156 : 1892 : Oid ppeqoperators[INDEX_MAX_KEYS] = {0};
10157 : 1892 : Oid ffeqoperators[INDEX_MAX_KEYS] = {0};
10158 : 1892 : int16 fkdelsetcols[INDEX_MAX_KEYS] = {0};
10159 : : bool with_period;
10160 : : bool pk_has_without_overlaps;
10161 : : int i;
10162 : : int numfks,
10163 : : numpks,
10164 : : numfkdelsetcols;
10165 : : Oid indexOid;
10166 : : bool old_check_ok;
10167 : : ObjectAddress address;
10168 : 1892 : ListCell *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
10169 : :
10170 : : /*
10171 : : * Grab ShareRowExclusiveLock on the pk table, so that someone doesn't
10172 : : * delete rows out from under us.
10173 : : */
10174 [ + + ]: 1892 : if (OidIsValid(fkconstraint->old_pktable_oid))
10175 : 48 : pkrel = table_open(fkconstraint->old_pktable_oid, ShareRowExclusiveLock);
10176 : : else
10177 : 1844 : pkrel = table_openrv(fkconstraint->pktable, ShareRowExclusiveLock);
10178 : :
10179 : : /*
10180 : : * Validity checks (permission checks wait till we have the column
10181 : : * numbers)
10182 : : */
10183 [ + + + + ]: 1888 : if (!recurse && rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
10184 [ + - ]: 4 : ereport(ERROR,
10185 : : errcode(ERRCODE_WRONG_OBJECT_TYPE),
10186 : : errmsg("cannot use ONLY for foreign key on partitioned table \"%s\" referencing relation \"%s\"",
10187 : : RelationGetRelationName(rel),
10188 : : RelationGetRelationName(pkrel)));
10189 : :
10190 [ + + ]: 1884 : if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
10191 [ - + ]: 226 : pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
10192 [ # # ]: 0 : ereport(ERROR,
10193 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10194 : : errmsg("referenced relation \"%s\" is not a table",
10195 : : RelationGetRelationName(pkrel))));
10196 : :
10197 : : /*
10198 : : * Conflict log tables are used internally for logical replication
10199 : : * conflict logging and should not be referenced by foreign keys, as it
10200 : : * could disrupt conflict logging.
10201 : : */
10202 [ + + ]: 1884 : if (IsConflictLogTableClass(pkrel->rd_rel))
10203 [ + - ]: 4 : ereport(ERROR,
10204 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10205 : : errmsg("cannot reference conflict log table \"%s\"",
10206 : : RelationGetRelationName(pkrel)),
10207 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
10208 : :
10209 [ + + + + ]: 1880 : if (!allowSystemTableMods && IsSystemRelation(pkrel))
10210 [ + - ]: 1 : ereport(ERROR,
10211 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
10212 : : errmsg("permission denied: \"%s\" is a system catalog",
10213 : : RelationGetRelationName(pkrel))));
10214 : :
10215 : : /*
10216 : : * References from permanent or unlogged tables to temp tables, and from
10217 : : * permanent tables to unlogged tables, are disallowed because the
10218 : : * referenced data can vanish out from under us. References from temp
10219 : : * tables to any other table type are also disallowed, because other
10220 : : * backends might need to run the RI triggers on the perm table, but they
10221 : : * can't reliably see tuples in the local buffers of other backends.
10222 : : */
10223 [ + + + - ]: 1879 : switch (rel->rd_rel->relpersistence)
10224 : : {
10225 : 1686 : case RELPERSISTENCE_PERMANENT:
10226 [ - + ]: 1686 : if (!RelationIsPermanent(pkrel))
10227 [ # # ]: 0 : ereport(ERROR,
10228 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10229 : : errmsg("constraints on permanent tables may reference only permanent tables")));
10230 : 1686 : break;
10231 : 8 : case RELPERSISTENCE_UNLOGGED:
10232 [ + - ]: 8 : if (!RelationIsPermanent(pkrel)
10233 [ - + ]: 8 : && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
10234 [ # # ]: 0 : ereport(ERROR,
10235 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10236 : : errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
10237 : 8 : break;
10238 : 185 : case RELPERSISTENCE_TEMP:
10239 [ - + ]: 185 : if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
10240 [ # # ]: 0 : ereport(ERROR,
10241 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10242 : : errmsg("constraints on temporary tables may reference only temporary tables")));
10243 [ + - - + ]: 185 : if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
10244 [ # # ]: 0 : ereport(ERROR,
10245 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
10246 : : errmsg("constraints on temporary tables must involve temporary tables of this session")));
10247 : 185 : break;
10248 : : }
10249 : :
10250 : : /*
10251 : : * Look up the referencing attributes to make sure they exist, and record
10252 : : * their attnums and type and collation OIDs.
10253 : : */
10254 : 1879 : numfks = transformColumnNameList(RelationGetRelid(rel),
10255 : : fkconstraint->fk_attrs,
10256 : : fkattnum, fktypoid, fkcolloid);
10257 [ + + + + ]: 1859 : with_period = fkconstraint->fk_with_period || fkconstraint->pk_with_period;
10258 [ + + + + ]: 1859 : if (with_period && !fkconstraint->fk_with_period)
10259 [ + - ]: 16 : ereport(ERROR,
10260 : : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10261 : : errmsg("foreign key uses PERIOD on the referenced table but not the referencing table"));
10262 : :
10263 : 1843 : numfkdelsetcols = transformColumnNameList(RelationGetRelid(rel),
10264 : : fkconstraint->fk_del_set_cols,
10265 : : fkdelsetcols, NULL, NULL);
10266 : 1839 : numfkdelsetcols = validateFkOnDeleteSetColumns(numfks, fkattnum,
10267 : : numfkdelsetcols,
10268 : : fkdelsetcols,
10269 : : fkconstraint->fk_del_set_cols);
10270 : :
10271 : : /*
10272 : : * If the attribute list for the referenced table was omitted, lookup the
10273 : : * definition of the primary key and use it. Otherwise, validate the
10274 : : * supplied attribute list. In either case, discover the index OID and
10275 : : * index opclasses, and the attnums and type and collation OIDs of the
10276 : : * attributes.
10277 : : */
10278 [ + + ]: 1835 : if (fkconstraint->pk_attrs == NIL)
10279 : : {
10280 : 904 : numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
10281 : : &fkconstraint->pk_attrs,
10282 : : pkattnum, pktypoid, pkcolloid,
10283 : : opclasses, &pk_has_without_overlaps);
10284 : :
10285 : : /* If the primary key uses WITHOUT OVERLAPS, the fk must use PERIOD */
10286 [ + + + + ]: 904 : if (pk_has_without_overlaps && !fkconstraint->fk_with_period)
10287 [ + - ]: 16 : ereport(ERROR,
10288 : : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10289 : : errmsg("foreign key uses PERIOD on the referenced table but not the referencing table"));
10290 : : }
10291 : : else
10292 : : {
10293 : 931 : numpks = transformColumnNameList(RelationGetRelid(pkrel),
10294 : : fkconstraint->pk_attrs,
10295 : : pkattnum, pktypoid, pkcolloid);
10296 : :
10297 : : /* Since we got pk_attrs, one should be a period. */
10298 [ + + + + ]: 911 : if (with_period && !fkconstraint->pk_with_period)
10299 [ + - ]: 16 : ereport(ERROR,
10300 : : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10301 : : errmsg("foreign key uses PERIOD on the referencing table but not the referenced table"));
10302 : :
10303 : : /* Look for an index matching the column list */
10304 : 895 : indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
10305 : : with_period, opclasses, &pk_has_without_overlaps);
10306 : : }
10307 : :
10308 : : /*
10309 : : * If the referenced primary key has WITHOUT OVERLAPS, the foreign key
10310 : : * must use PERIOD.
10311 : : */
10312 [ + + + + ]: 1759 : if (pk_has_without_overlaps && !with_period)
10313 [ + - ]: 8 : ereport(ERROR,
10314 : : errcode(ERRCODE_INVALID_FOREIGN_KEY),
10315 : : errmsg("foreign key must use PERIOD when referencing a primary key using WITHOUT OVERLAPS"));
10316 : :
10317 : : /*
10318 : : * Now we can check permissions.
10319 : : */
10320 : 1751 : checkFkeyPermissions(pkrel, pkattnum, numpks);
10321 : :
10322 : : /*
10323 : : * Check some things for generated columns.
10324 : : */
10325 [ + + ]: 4095 : for (i = 0; i < numfks; i++)
10326 : : {
10327 : 2364 : char attgenerated = TupleDescAttr(RelationGetDescr(rel), fkattnum[i] - 1)->attgenerated;
10328 : :
10329 [ + + ]: 2364 : if (attgenerated)
10330 : : {
10331 : : /*
10332 : : * Check restrictions on UPDATE/DELETE actions, per SQL standard
10333 : : */
10334 [ + - ]: 32 : if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
10335 [ + - ]: 32 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT ||
10336 [ + + ]: 32 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE)
10337 [ + - ]: 8 : ereport(ERROR,
10338 : : (errcode(ERRCODE_SYNTAX_ERROR),
10339 : : errmsg("invalid %s action for foreign key constraint containing generated column",
10340 : : "ON UPDATE")));
10341 [ + + ]: 24 : if (fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
10342 [ - + ]: 16 : fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
10343 [ + - ]: 8 : ereport(ERROR,
10344 : : (errcode(ERRCODE_SYNTAX_ERROR),
10345 : : errmsg("invalid %s action for foreign key constraint containing generated column",
10346 : : "ON DELETE")));
10347 : : }
10348 : :
10349 : : /*
10350 : : * FKs on virtual columns are not supported. This would require
10351 : : * various additional support in ri_triggers.c, including special
10352 : : * handling in ri_NullCheck(), ri_KeysEqual(),
10353 : : * RI_FKey_fk_upd_check_required() (since all virtual columns appear
10354 : : * as NULL there). Also not really practical as long as you can't
10355 : : * index virtual columns.
10356 : : */
10357 [ + + ]: 2348 : if (attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
10358 [ + - ]: 4 : ereport(ERROR,
10359 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10360 : : errmsg("foreign key constraints on virtual generated columns are not supported")));
10361 : : }
10362 : :
10363 : : /*
10364 : : * Some actions are currently unsupported for foreign keys using PERIOD.
10365 : : */
10366 [ + + ]: 1731 : if (fkconstraint->fk_with_period)
10367 : : {
10368 [ + + ]: 178 : if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_RESTRICT ||
10369 [ + + ]: 170 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE ||
10370 [ + + ]: 158 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
10371 [ + + ]: 146 : fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT)
10372 [ + - ]: 44 : ereport(ERROR,
10373 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10374 : : errmsg("unsupported %s action for foreign key constraint using PERIOD",
10375 : : "ON UPDATE"));
10376 : :
10377 [ + + ]: 134 : if (fkconstraint->fk_del_action == FKCONSTR_ACTION_RESTRICT ||
10378 [ + - ]: 130 : fkconstraint->fk_del_action == FKCONSTR_ACTION_CASCADE ||
10379 [ + - ]: 130 : fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
10380 [ - + ]: 130 : fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
10381 [ + - ]: 4 : ereport(ERROR,
10382 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10383 : : errmsg("unsupported %s action for foreign key constraint using PERIOD",
10384 : : "ON DELETE"));
10385 : : }
10386 : :
10387 : : /*
10388 : : * Look up the equality operators to use in the constraint.
10389 : : *
10390 : : * Note that we have to be careful about the difference between the actual
10391 : : * PK column type and the opclass' declared input type, which might be
10392 : : * only binary-compatible with it. The declared opcintype is the right
10393 : : * thing to probe pg_amop with.
10394 : : */
10395 [ - + ]: 1683 : if (numfks != numpks)
10396 [ # # ]: 0 : ereport(ERROR,
10397 : : (errcode(ERRCODE_INVALID_FOREIGN_KEY),
10398 : : errmsg("number of referencing and referenced columns for foreign key disagree")));
10399 : :
10400 : : /*
10401 : : * On the strength of a previous constraint, we might avoid scanning
10402 : : * tables to validate this one. See below.
10403 : : */
10404 : 1683 : old_check_ok = (fkconstraint->old_conpfeqop != NIL);
10405 : : Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
10406 : :
10407 [ + + ]: 3675 : for (i = 0; i < numpks; i++)
10408 : : {
10409 : 2152 : Oid pktype = pktypoid[i];
10410 : 2152 : Oid fktype = fktypoid[i];
10411 : : Oid fktyped;
10412 : 2152 : Oid pkcoll = pkcolloid[i];
10413 : 2152 : Oid fkcoll = fkcolloid[i];
10414 : : HeapTuple cla_ht;
10415 : : Form_pg_opclass cla_tup;
10416 : : Oid amid;
10417 : : Oid opfamily;
10418 : : Oid opcintype;
10419 : : bool for_overlaps;
10420 : : CompareType cmptype;
10421 : : Oid pfeqop;
10422 : : Oid ppeqop;
10423 : : Oid ffeqop;
10424 : : int16 eqstrategy;
10425 : : Oid pfeqop_right;
10426 : :
10427 : : /* We need several fields out of the pg_opclass entry */
10428 : 2152 : cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
10429 [ - + ]: 2152 : if (!HeapTupleIsValid(cla_ht))
10430 [ # # ]: 0 : elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
10431 : 2152 : cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
10432 : 2152 : amid = cla_tup->opcmethod;
10433 : 2152 : opfamily = cla_tup->opcfamily;
10434 : 2152 : opcintype = cla_tup->opcintype;
10435 : 2152 : ReleaseSysCache(cla_ht);
10436 : :
10437 : : /*
10438 : : * Get strategy number from index AM.
10439 : : *
10440 : : * For a normal foreign-key constraint, this should not fail, since we
10441 : : * already checked that the index is unique and should therefore have
10442 : : * appropriate equal operators. For a period foreign key, this could
10443 : : * fail if we selected a non-matching exclusion constraint earlier.
10444 : : * (XXX Maybe we should do these lookups earlier so we don't end up
10445 : : * doing that.)
10446 : : */
10447 [ + + + + ]: 2152 : for_overlaps = with_period && i == numpks - 1;
10448 [ + + ]: 2152 : cmptype = for_overlaps ? COMPARE_OVERLAP : COMPARE_EQ;
10449 : 2152 : eqstrategy = IndexAmTranslateCompareType(cmptype, amid, opfamily, true);
10450 [ - + ]: 2152 : if (eqstrategy == InvalidStrategy)
10451 [ # # # # ]: 0 : ereport(ERROR,
10452 : : errcode(ERRCODE_UNDEFINED_OBJECT),
10453 : : for_overlaps
10454 : : ? errmsg("could not identify an overlaps operator for foreign key")
10455 : : : errmsg("could not identify an equality operator for foreign key"),
10456 : : errdetail("Could not translate compare type %d for operator family \"%s\" of access method \"%s\".",
10457 : : cmptype, get_opfamily_name(opfamily, false), get_am_name(amid)));
10458 : :
10459 : : /*
10460 : : * There had better be a primary equality operator for the index.
10461 : : * We'll use it for PK = PK comparisons.
10462 : : */
10463 : 2152 : ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
10464 : : eqstrategy);
10465 : :
10466 [ - + ]: 2152 : if (!OidIsValid(ppeqop))
10467 [ # # ]: 0 : elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
10468 : : eqstrategy, opcintype, opcintype, opfamily);
10469 : :
10470 : : /*
10471 : : * Are there equality operators that take exactly the FK type? Assume
10472 : : * we should look through any domain here.
10473 : : */
10474 : 2152 : fktyped = getBaseType(fktype);
10475 : :
10476 : 2152 : pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
10477 : : eqstrategy);
10478 [ + + ]: 2152 : if (OidIsValid(pfeqop))
10479 : : {
10480 : 1671 : pfeqop_right = fktyped;
10481 : 1671 : ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
10482 : : eqstrategy);
10483 : : }
10484 : : else
10485 : : {
10486 : : /* keep compiler quiet */
10487 : 481 : pfeqop_right = InvalidOid;
10488 : 481 : ffeqop = InvalidOid;
10489 : : }
10490 : :
10491 [ + + - + ]: 2152 : if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
10492 : : {
10493 : : /*
10494 : : * Otherwise, look for an implicit cast from the FK type to the
10495 : : * opcintype, and if found, use the primary equality operator.
10496 : : * This is a bit tricky because opcintype might be a polymorphic
10497 : : * type such as ANYARRAY or ANYENUM; so what we have to test is
10498 : : * whether the two actual column types can be concurrently cast to
10499 : : * that type. (Otherwise, we'd fail to reject combinations such
10500 : : * as int[] and point[].)
10501 : : */
10502 : : Oid input_typeids[2];
10503 : : Oid target_typeids[2];
10504 : :
10505 : 481 : input_typeids[0] = pktype;
10506 : 481 : input_typeids[1] = fktype;
10507 : 481 : target_typeids[0] = opcintype;
10508 : 481 : target_typeids[1] = opcintype;
10509 [ + + ]: 481 : if (can_coerce_type(2, input_typeids, target_typeids,
10510 : : COERCION_IMPLICIT))
10511 : : {
10512 : 329 : pfeqop = ffeqop = ppeqop;
10513 : 329 : pfeqop_right = opcintype;
10514 : : }
10515 : : }
10516 : :
10517 [ + + - + ]: 2152 : if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
10518 [ + - ]: 152 : ereport(ERROR,
10519 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
10520 : : errmsg("foreign key constraint \"%s\" cannot be implemented",
10521 : : fkconstraint->conname),
10522 : : errdetail("Key columns \"%s\" of the referencing table and \"%s\" of the referenced table "
10523 : : "are of incompatible types: %s and %s.",
10524 : : strVal(list_nth(fkconstraint->fk_attrs, i)),
10525 : : strVal(list_nth(fkconstraint->pk_attrs, i)),
10526 : : format_type_be(fktype),
10527 : : format_type_be(pktype))));
10528 : :
10529 : : /*
10530 : : * This shouldn't be possible, but better check to make sure we have a
10531 : : * consistent state for the check below.
10532 : : */
10533 [ + + + - : 2000 : if ((OidIsValid(pkcoll) && !OidIsValid(fkcoll)) || (!OidIsValid(pkcoll) && OidIsValid(fkcoll)))
+ + - + ]
10534 [ # # ]: 0 : elog(ERROR, "key columns are not both collatable");
10535 : :
10536 [ + + + - ]: 2000 : if (OidIsValid(pkcoll) && OidIsValid(fkcoll))
10537 : : {
10538 : : bool pkcolldet;
10539 : : bool fkcolldet;
10540 : :
10541 : 85 : pkcolldet = get_collation_isdeterministic(pkcoll);
10542 : 85 : fkcolldet = get_collation_isdeterministic(fkcoll);
10543 : :
10544 : : /*
10545 : : * SQL requires that both collations are the same. This is
10546 : : * because we need a consistent notion of equality on both
10547 : : * columns. We relax this by allowing different collations if
10548 : : * they are both deterministic. (This is also for backward
10549 : : * compatibility, because PostgreSQL has always allowed this.)
10550 : : */
10551 [ + + + + : 85 : if ((!pkcolldet || !fkcolldet) && pkcoll != fkcoll)
+ + ]
10552 [ + - ]: 8 : ereport(ERROR,
10553 : : (errcode(ERRCODE_COLLATION_MISMATCH),
10554 : : errmsg("foreign key constraint \"%s\" cannot be implemented", fkconstraint->conname),
10555 : : errdetail("Key columns \"%s\" of the referencing table and \"%s\" of the referenced table "
10556 : : "have incompatible collations: \"%s\" and \"%s\". "
10557 : : "If either collation is nondeterministic, then both collations have to be the same.",
10558 : : strVal(list_nth(fkconstraint->fk_attrs, i)),
10559 : : strVal(list_nth(fkconstraint->pk_attrs, i)),
10560 : : get_collation_name(fkcoll),
10561 : : get_collation_name(pkcoll))));
10562 : : }
10563 : :
10564 [ + + ]: 1992 : if (old_check_ok)
10565 : : {
10566 : : /*
10567 : : * When a pfeqop changes, revalidate the constraint. We could
10568 : : * permit intra-opfamily changes, but that adds subtle complexity
10569 : : * without any concrete benefit for core types. We need not
10570 : : * assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
10571 : : */
10572 : 4 : old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
10573 : 4 : old_pfeqop_item = lnext(fkconstraint->old_conpfeqop,
10574 : : old_pfeqop_item);
10575 : : }
10576 [ + + ]: 1992 : if (old_check_ok)
10577 : : {
10578 : : Oid old_fktype;
10579 : : Oid new_fktype;
10580 : : CoercionPathType old_pathtype;
10581 : : CoercionPathType new_pathtype;
10582 : : Oid old_castfunc;
10583 : : Oid new_castfunc;
10584 : : Oid old_fkcoll;
10585 : : Oid new_fkcoll;
10586 : 4 : Form_pg_attribute attr = TupleDescAttr(tab->oldDesc,
10587 : 4 : fkattnum[i] - 1);
10588 : :
10589 : : /*
10590 : : * Identify coercion pathways from each of the old and new FK-side
10591 : : * column types to the right (foreign) operand type of the pfeqop.
10592 : : * We may assume that pg_constraint.conkey is not changing.
10593 : : */
10594 : 4 : old_fktype = attr->atttypid;
10595 : 4 : new_fktype = fktype;
10596 : 4 : old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
10597 : : &old_castfunc);
10598 : 4 : new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
10599 : : &new_castfunc);
10600 : :
10601 : 4 : old_fkcoll = attr->attcollation;
10602 : 4 : new_fkcoll = fkcoll;
10603 : :
10604 : : /*
10605 : : * Upon a change to the cast from the FK column to its pfeqop
10606 : : * operand, revalidate the constraint. For this evaluation, a
10607 : : * binary coercion cast is equivalent to no cast at all. While
10608 : : * type implementors should design implicit casts with an eye
10609 : : * toward consistency of operations like equality, we cannot
10610 : : * assume here that they have done so.
10611 : : *
10612 : : * A function with a polymorphic argument could change behavior
10613 : : * arbitrarily in response to get_fn_expr_argtype(). Therefore,
10614 : : * when the cast destination is polymorphic, we only avoid
10615 : : * revalidation if the input type has not changed at all. Given
10616 : : * just the core data types and operator classes, this requirement
10617 : : * prevents no would-be optimizations.
10618 : : *
10619 : : * If the cast converts from a base type to a domain thereon, then
10620 : : * that domain type must be the opcintype of the unique index.
10621 : : * Necessarily, the primary key column must then be of the domain
10622 : : * type. Since the constraint was previously valid, all values on
10623 : : * the foreign side necessarily exist on the primary side and in
10624 : : * turn conform to the domain. Consequently, we need not treat
10625 : : * domains specially here.
10626 : : *
10627 : : * If the collation changes, revalidation is required, unless both
10628 : : * collations are deterministic, because those share the same
10629 : : * notion of equality (because texteq reduces to bitwise
10630 : : * equality).
10631 : : *
10632 : : * We need not directly consider the PK type. It's necessarily
10633 : : * binary coercible to the opcintype of the unique index column,
10634 : : * and ri_triggers.c will only deal with PK datums in terms of
10635 : : * that opcintype. Changing the opcintype also changes pfeqop.
10636 : : */
10637 : 4 : old_check_ok = (new_pathtype == old_pathtype &&
10638 [ + - + - ]: 4 : new_castfunc == old_castfunc &&
10639 [ + - + - : 4 : (!IsPolymorphicType(pfeqop_right) ||
+ - + - +
- + - + -
+ - + - -
+ - - ]
10640 [ + - - + ]: 8 : new_fktype == old_fktype) &&
10641 [ # # ]: 0 : (new_fkcoll == old_fkcoll ||
10642 [ # # ]: 0 : (get_collation_isdeterministic(old_fkcoll) && get_collation_isdeterministic(new_fkcoll))));
10643 : : }
10644 : :
10645 : 1992 : pfeqoperators[i] = pfeqop;
10646 : 1992 : ppeqoperators[i] = ppeqop;
10647 : 1992 : ffeqoperators[i] = ffeqop;
10648 : : }
10649 : :
10650 : : /*
10651 : : * For FKs with PERIOD we need additional operators to check whether the
10652 : : * referencing row's range is contained by the aggregated ranges of the
10653 : : * referenced row(s). For rangetypes and multirangetypes this is
10654 : : * fk.periodatt <@ range_agg(pk.periodatt). Those are the only types we
10655 : : * support for now. FKs will look these up at "runtime", but we should
10656 : : * make sure the lookup works here, even if we don't use the values.
10657 : : */
10658 [ + + ]: 1523 : if (with_period)
10659 : : {
10660 : : Oid periodoperoid;
10661 : : Oid aggedperiodoperoid;
10662 : : Oid intersectoperoid;
10663 : :
10664 : 118 : FindFKPeriodOpers(opclasses[numpks - 1], &periodoperoid, &aggedperiodoperoid,
10665 : : &intersectoperoid);
10666 : : }
10667 : :
10668 : : /* First, create the constraint catalog entry itself. */
10669 : 1523 : address = addFkConstraint(addFkBothSides,
10670 : : fkconstraint->conname, fkconstraint, rel, pkrel,
10671 : : indexOid,
10672 : : InvalidOid, /* no parent constraint */
10673 : : numfks,
10674 : : pkattnum,
10675 : : fkattnum,
10676 : : pfeqoperators,
10677 : : ppeqoperators,
10678 : : ffeqoperators,
10679 : : numfkdelsetcols,
10680 : : fkdelsetcols,
10681 : : false,
10682 : : with_period);
10683 : :
10684 : : /* Next process the action triggers at the referenced side and recurse */
10685 : 1523 : addFkRecurseReferenced(fkconstraint, rel, pkrel,
10686 : : indexOid,
10687 : : address.objectId,
10688 : : numfks,
10689 : : pkattnum,
10690 : : fkattnum,
10691 : : pfeqoperators,
10692 : : ppeqoperators,
10693 : : ffeqoperators,
10694 : : numfkdelsetcols,
10695 : : fkdelsetcols,
10696 : : old_check_ok,
10697 : : InvalidOid, InvalidOid,
10698 : : with_period);
10699 : :
10700 : : /* Lastly create the check triggers at the referencing side and recurse */
10701 : 1523 : addFkRecurseReferencing(wqueue, fkconstraint, rel, pkrel,
10702 : : indexOid,
10703 : : address.objectId,
10704 : : numfks,
10705 : : pkattnum,
10706 : : fkattnum,
10707 : : pfeqoperators,
10708 : : ppeqoperators,
10709 : : ffeqoperators,
10710 : : numfkdelsetcols,
10711 : : fkdelsetcols,
10712 : : old_check_ok,
10713 : : lockmode,
10714 : : InvalidOid, InvalidOid,
10715 : : with_period);
10716 : :
10717 : : /*
10718 : : * Done. Close pk table, but keep lock until we've committed.
10719 : : */
10720 : 1523 : table_close(pkrel, NoLock);
10721 : :
10722 : 1523 : return address;
10723 : : }
10724 : :
10725 : : /*
10726 : : * validateFkOnDeleteSetColumns
10727 : : * Verifies that columns used in ON DELETE SET NULL/DEFAULT (...)
10728 : : * column lists are valid.
10729 : : *
10730 : : * If there are duplicates in the fksetcolsattnums[] array, this silently
10731 : : * removes the dups. The new count of numfksetcols is returned.
10732 : : */
10733 : : static int
10734 : 1839 : validateFkOnDeleteSetColumns(int numfks, const int16 *fkattnums,
10735 : : int numfksetcols, int16 *fksetcolsattnums,
10736 : : List *fksetcols)
10737 : : {
10738 : 1839 : int numcolsout = 0;
10739 : :
10740 [ + + ]: 1859 : for (int i = 0; i < numfksetcols; i++)
10741 : : {
10742 : 24 : int16 setcol_attnum = fksetcolsattnums[i];
10743 : 24 : bool seen = false;
10744 : :
10745 : : /* Make sure it's in fkattnums[] */
10746 [ + + ]: 44 : for (int j = 0; j < numfks; j++)
10747 : : {
10748 [ + + ]: 40 : if (fkattnums[j] == setcol_attnum)
10749 : : {
10750 : 20 : seen = true;
10751 : 20 : break;
10752 : : }
10753 : : }
10754 : :
10755 [ + + ]: 24 : if (!seen)
10756 : : {
10757 : 4 : char *col = strVal(list_nth(fksetcols, i));
10758 : :
10759 [ + - ]: 4 : ereport(ERROR,
10760 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
10761 : : errmsg("column \"%s\" referenced in ON DELETE SET action must be part of foreign key", col)));
10762 : : }
10763 : :
10764 : : /* Now check for dups */
10765 : 20 : seen = false;
10766 [ + + ]: 20 : for (int j = 0; j < numcolsout; j++)
10767 : : {
10768 [ + - ]: 4 : if (fksetcolsattnums[j] == setcol_attnum)
10769 : : {
10770 : 4 : seen = true;
10771 : 4 : break;
10772 : : }
10773 : : }
10774 [ + + ]: 20 : if (!seen)
10775 : 16 : fksetcolsattnums[numcolsout++] = setcol_attnum;
10776 : : }
10777 : 1835 : return numcolsout;
10778 : : }
10779 : :
10780 : : /*
10781 : : * addFkConstraint
10782 : : * Install pg_constraint entries to implement a foreign key constraint.
10783 : : * Caller must separately invoke addFkRecurseReferenced and
10784 : : * addFkRecurseReferencing, as appropriate, to install pg_trigger entries
10785 : : * and (for partitioned tables) recurse to partitions.
10786 : : *
10787 : : * fkside: the side of the FK (or both) to create. Caller should
10788 : : * call addFkRecurseReferenced if this is addFkReferencedSide,
10789 : : * addFkRecurseReferencing if it's addFkReferencingSide, or both if it's
10790 : : * addFkBothSides.
10791 : : * constraintname: the base name for the constraint being added,
10792 : : * copied to fkconstraint->conname if the latter is not set
10793 : : * fkconstraint: the constraint being added
10794 : : * rel: the root referencing relation
10795 : : * pkrel: the referenced relation; might be a partition, if recursing
10796 : : * indexOid: the OID of the index (on pkrel) implementing this constraint
10797 : : * parentConstr: the OID of a parent constraint; InvalidOid if this is a
10798 : : * top-level constraint
10799 : : * numfks: the number of columns in the foreign key
10800 : : * pkattnum: the attnum array of referenced attributes
10801 : : * fkattnum: the attnum array of referencing attributes
10802 : : * pf/pp/ffeqoperators: OID array of operators between columns
10803 : : * numfkdelsetcols: the number of columns in the ON DELETE SET NULL/DEFAULT
10804 : : * (...) clause
10805 : : * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
10806 : : * NULL/DEFAULT clause
10807 : : * with_period: true if this is a temporal FK
10808 : : */
10809 : : static ObjectAddress
10810 : 2790 : addFkConstraint(addFkConstraintSides fkside,
10811 : : char *constraintname, Constraint *fkconstraint,
10812 : : Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
10813 : : int numfks, int16 *pkattnum,
10814 : : int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators,
10815 : : Oid *ffeqoperators, int numfkdelsetcols, int16 *fkdelsetcols,
10816 : : bool is_internal, bool with_period)
10817 : : {
10818 : : ObjectAddress address;
10819 : : Oid constrOid;
10820 : : char *conname;
10821 : : bool conislocal;
10822 : : int16 coninhcount;
10823 : : bool connoinherit;
10824 : :
10825 : : /*
10826 : : * Verify relkind for each referenced partition. At the top level, this
10827 : : * is redundant with a previous check, but we need it when recursing.
10828 : : */
10829 [ + + ]: 2790 : if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
10830 [ - + ]: 559 : pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
10831 [ # # ]: 0 : ereport(ERROR,
10832 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10833 : : errmsg("referenced relation \"%s\" is not a table",
10834 : : RelationGetRelationName(pkrel))));
10835 : :
10836 : : /*
10837 : : * Caller supplies us with a constraint name; however, it may be used in
10838 : : * this partition, so come up with a different one in that case. Unless
10839 : : * truncation to NAMEDATALEN dictates otherwise, the new name will be the
10840 : : * supplied name with an underscore and digit(s) appended.
10841 : : */
10842 [ + + ]: 2790 : if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
10843 : : RelationGetRelid(rel),
10844 : : constraintname))
10845 : 755 : conname = ChooseConstraintName(constraintname,
10846 : : NULL,
10847 : : "",
10848 : 755 : RelationGetNamespace(rel), NIL);
10849 : : else
10850 : 2035 : conname = constraintname;
10851 : :
10852 [ + + ]: 2790 : if (fkconstraint->conname == NULL)
10853 : 243 : fkconstraint->conname = pstrdup(conname);
10854 : :
10855 [ + + ]: 2790 : if (OidIsValid(parentConstr))
10856 : : {
10857 : 1267 : conislocal = false;
10858 : 1267 : coninhcount = 1;
10859 : 1267 : connoinherit = false;
10860 : : }
10861 : : else
10862 : : {
10863 : 1523 : conislocal = true;
10864 : 1523 : coninhcount = 0;
10865 : :
10866 : : /*
10867 : : * always inherit for partitioned tables, never for legacy inheritance
10868 : : */
10869 : 1523 : connoinherit = rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE;
10870 : : }
10871 : :
10872 : : /*
10873 : : * Record the FK constraint in pg_constraint.
10874 : : */
10875 : 2790 : constrOid = CreateConstraintEntry(conname,
10876 : 2790 : RelationGetNamespace(rel),
10877 : : CONSTRAINT_FOREIGN,
10878 : 2790 : fkconstraint->deferrable,
10879 : 2790 : fkconstraint->initdeferred,
10880 : 2790 : fkconstraint->is_enforced,
10881 : 2790 : fkconstraint->initially_valid,
10882 : : parentConstr,
10883 : : RelationGetRelid(rel),
10884 : : fkattnum,
10885 : : numfks,
10886 : : numfks,
10887 : : InvalidOid, /* not a domain constraint */
10888 : : indexOid,
10889 : : RelationGetRelid(pkrel),
10890 : : pkattnum,
10891 : : pfeqoperators,
10892 : : ppeqoperators,
10893 : : ffeqoperators,
10894 : : numfks,
10895 : 2790 : fkconstraint->fk_upd_action,
10896 : 2790 : fkconstraint->fk_del_action,
10897 : : fkdelsetcols,
10898 : : numfkdelsetcols,
10899 : 2790 : fkconstraint->fk_matchtype,
10900 : : NULL, /* no exclusion constraint */
10901 : : NULL, /* no check constraint */
10902 : : NULL,
10903 : : conislocal, /* islocal */
10904 : : coninhcount, /* inhcount */
10905 : : connoinherit, /* conNoInherit */
10906 : : with_period, /* conPeriod */
10907 : : is_internal); /* is_internal */
10908 : :
10909 : 2790 : ObjectAddressSet(address, ConstraintRelationId, constrOid);
10910 : :
10911 : : /*
10912 : : * In partitioning cases, create the dependency entries for this
10913 : : * constraint. (For non-partitioned cases, relevant entries were created
10914 : : * by CreateConstraintEntry.)
10915 : : *
10916 : : * On the referenced side, we need the constraint to have an internal
10917 : : * dependency on its parent constraint; this means that this constraint
10918 : : * cannot be dropped on its own -- only through the parent constraint. It
10919 : : * also means the containing partition cannot be dropped on its own, but
10920 : : * it can be detached, at which point this dependency is removed (after
10921 : : * verifying that no rows are referenced via this FK.)
10922 : : *
10923 : : * When processing the referencing side, we link the constraint via the
10924 : : * special partitioning dependencies: the parent constraint is the primary
10925 : : * dependent, and the partition on which the foreign key exists is the
10926 : : * secondary dependency. That way, this constraint is dropped if either
10927 : : * of these objects is.
10928 : : *
10929 : : * Note that this is only necessary for the subsidiary pg_constraint rows
10930 : : * in partitions; the topmost row doesn't need any of this.
10931 : : */
10932 [ + + ]: 2790 : if (OidIsValid(parentConstr))
10933 : : {
10934 : : ObjectAddress referenced;
10935 : :
10936 : 1267 : ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
10937 : :
10938 : : Assert(fkside != addFkBothSides);
10939 [ + + ]: 1267 : if (fkside == addFkReferencedSide)
10940 : 751 : recordDependencyOn(&address, &referenced, DEPENDENCY_INTERNAL);
10941 : : else
10942 : : {
10943 : 516 : recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_PRI);
10944 : 516 : ObjectAddressSet(referenced, RelationRelationId, RelationGetRelid(rel));
10945 : 516 : recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_SEC);
10946 : : }
10947 : : }
10948 : :
10949 : : /* make new constraint visible, in case we add more */
10950 : 2790 : CommandCounterIncrement();
10951 : :
10952 : 2790 : return address;
10953 : : }
10954 : :
10955 : : /*
10956 : : * addFkRecurseReferenced
10957 : : * Recursive helper for the referenced side of foreign key creation,
10958 : : * which creates the action triggers and recurses
10959 : : *
10960 : : * If the referenced relation is a plain relation, create the necessary action
10961 : : * triggers that implement the constraint. If the referenced relation is a
10962 : : * partitioned table, then we create a pg_constraint row referencing the parent
10963 : : * of the referencing side for it and recurse on this routine for each
10964 : : * partition.
10965 : : *
10966 : : * fkconstraint: the constraint being added
10967 : : * rel: the root referencing relation
10968 : : * pkrel: the referenced relation; might be a partition, if recursing
10969 : : * indexOid: the OID of the index (on pkrel) implementing this constraint
10970 : : * parentConstr: the OID of a parent constraint; InvalidOid if this is a
10971 : : * top-level constraint
10972 : : * numfks: the number of columns in the foreign key
10973 : : * pkattnum: the attnum array of referenced attributes
10974 : : * fkattnum: the attnum array of referencing attributes
10975 : : * numfkdelsetcols: the number of columns in the ON DELETE SET
10976 : : * NULL/DEFAULT (...) clause
10977 : : * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
10978 : : * NULL/DEFAULT clause
10979 : : * pf/pp/ffeqoperators: OID array of operators between columns
10980 : : * old_check_ok: true if this constraint replaces an existing one that
10981 : : * was already validated (thus this one doesn't need validation)
10982 : : * parentDelTrigger and parentUpdTrigger: when recursively called on a
10983 : : * partition, the OIDs of the parent action triggers for DELETE and
10984 : : * UPDATE respectively.
10985 : : * with_period: true if this is a temporal FK
10986 : : */
10987 : : static void
10988 : 2342 : addFkRecurseReferenced(Constraint *fkconstraint, Relation rel,
10989 : : Relation pkrel, Oid indexOid, Oid parentConstr,
10990 : : int numfks,
10991 : : int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators,
10992 : : Oid *ppeqoperators, Oid *ffeqoperators,
10993 : : int numfkdelsetcols, int16 *fkdelsetcols,
10994 : : bool old_check_ok,
10995 : : Oid parentDelTrigger, Oid parentUpdTrigger,
10996 : : bool with_period)
10997 : : {
10998 : 2342 : Oid deleteTriggerOid = InvalidOid,
10999 : 2342 : updateTriggerOid = InvalidOid;
11000 : :
11001 : : Assert(CheckRelationLockedByMe(pkrel, ShareRowExclusiveLock, true));
11002 : : Assert(CheckRelationLockedByMe(rel, ShareRowExclusiveLock, true));
11003 : :
11004 : : /*
11005 : : * Create action triggers to enforce the constraint, or skip them if the
11006 : : * constraint is NOT ENFORCED.
11007 : : */
11008 [ + + ]: 2342 : if (fkconstraint->is_enforced)
11009 : 2305 : createForeignKeyActionTriggers(RelationGetRelid(rel),
11010 : : RelationGetRelid(pkrel),
11011 : : fkconstraint,
11012 : : parentConstr, indexOid,
11013 : : parentDelTrigger, parentUpdTrigger,
11014 : : &deleteTriggerOid, &updateTriggerOid);
11015 : :
11016 : : /*
11017 : : * If the referenced table is partitioned, recurse on ourselves to handle
11018 : : * each partition. We need one pg_constraint row created for each
11019 : : * partition in addition to the pg_constraint row for the parent table.
11020 : : */
11021 [ + + ]: 2342 : if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
11022 : : {
11023 : 363 : PartitionDesc pd = RelationGetPartitionDesc(pkrel, true);
11024 : :
11025 [ + + ]: 1010 : for (int i = 0; i < pd->nparts; i++)
11026 : : {
11027 : : Relation partRel;
11028 : : AttrMap *map;
11029 : : AttrNumber *mapped_pkattnum;
11030 : : Oid partIndexId;
11031 : : ObjectAddress address;
11032 : :
11033 : : /* XXX would it be better to acquire these locks beforehand? */
11034 : 647 : partRel = table_open(pd->oids[i], ShareRowExclusiveLock);
11035 : :
11036 : : /*
11037 : : * Map the attribute numbers in the referenced side of the FK
11038 : : * definition to match the partition's column layout.
11039 : : */
11040 : 647 : map = build_attrmap_by_name_if_req(RelationGetDescr(partRel),
11041 : : RelationGetDescr(pkrel),
11042 : : false);
11043 [ + + ]: 647 : if (map)
11044 : : {
11045 : 89 : mapped_pkattnum = palloc_array(AttrNumber, numfks);
11046 [ + + ]: 186 : for (int j = 0; j < numfks; j++)
11047 : 97 : mapped_pkattnum[j] = map->attnums[pkattnum[j] - 1];
11048 : : }
11049 : : else
11050 : 558 : mapped_pkattnum = pkattnum;
11051 : :
11052 : : /* Determine the index to use at this level */
11053 : 647 : partIndexId = index_get_partition(partRel, indexOid);
11054 [ - + ]: 647 : if (!OidIsValid(partIndexId))
11055 [ # # ]: 0 : elog(ERROR, "index for %u not found in partition %s",
11056 : : indexOid, RelationGetRelationName(partRel));
11057 : :
11058 : : /* Create entry at this level ... */
11059 : 647 : address = addFkConstraint(addFkReferencedSide,
11060 : : fkconstraint->conname, fkconstraint, rel,
11061 : : partRel, partIndexId, parentConstr,
11062 : : numfks, mapped_pkattnum,
11063 : : fkattnum, pfeqoperators, ppeqoperators,
11064 : : ffeqoperators, numfkdelsetcols,
11065 : : fkdelsetcols, true, with_period);
11066 : : /* ... and recurse to our children */
11067 : 647 : addFkRecurseReferenced(fkconstraint, rel, partRel,
11068 : : partIndexId, address.objectId, numfks,
11069 : : mapped_pkattnum, fkattnum,
11070 : : pfeqoperators, ppeqoperators, ffeqoperators,
11071 : : numfkdelsetcols, fkdelsetcols,
11072 : : old_check_ok,
11073 : : deleteTriggerOid, updateTriggerOid,
11074 : : with_period);
11075 : :
11076 : : /* Done -- clean up (but keep the lock) */
11077 : 647 : table_close(partRel, NoLock);
11078 [ + + ]: 647 : if (map)
11079 : : {
11080 : 89 : pfree(mapped_pkattnum);
11081 : 89 : free_attrmap(map);
11082 : : }
11083 : : }
11084 : : }
11085 : 2342 : }
11086 : :
11087 : : /*
11088 : : * addFkRecurseReferencing
11089 : : * Recursive helper for the referencing side of foreign key creation,
11090 : : * which creates the check triggers and recurses
11091 : : *
11092 : : * If the referencing relation is a plain relation, create the necessary check
11093 : : * triggers that implement the constraint, and set up for Phase 3 constraint
11094 : : * verification. If the referencing relation is a partitioned table, then
11095 : : * we create a pg_constraint row for it and recurse on this routine for each
11096 : : * partition.
11097 : : *
11098 : : * We assume that the referenced relation is locked against concurrent
11099 : : * deletions. If it's a partitioned relation, every partition must be so
11100 : : * locked.
11101 : : *
11102 : : * wqueue: the ALTER TABLE work queue; NULL when not running as part
11103 : : * of an ALTER TABLE sequence.
11104 : : * fkconstraint: the constraint being added
11105 : : * rel: the referencing relation; might be a partition, if recursing
11106 : : * pkrel: the root referenced relation
11107 : : * indexOid: the OID of the index (on pkrel) implementing this constraint
11108 : : * parentConstr: the OID of the parent constraint (there is always one)
11109 : : * numfks: the number of columns in the foreign key
11110 : : * pkattnum: the attnum array of referenced attributes
11111 : : * fkattnum: the attnum array of referencing attributes
11112 : : * pf/pp/ffeqoperators: OID array of operators between columns
11113 : : * numfkdelsetcols: the number of columns in the ON DELETE SET NULL/DEFAULT
11114 : : * (...) clause
11115 : : * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
11116 : : * NULL/DEFAULT clause
11117 : : * old_check_ok: true if this constraint replaces an existing one that
11118 : : * was already validated (thus this one doesn't need validation)
11119 : : * lockmode: the lockmode to acquire on partitions when recursing
11120 : : * parentInsTrigger and parentUpdTrigger: when being recursively called on
11121 : : * a partition, the OIDs of the parent check triggers for INSERT and
11122 : : * UPDATE respectively.
11123 : : * with_period: true if this is a temporal FK
11124 : : */
11125 : : static void
11126 : 2039 : addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint, Relation rel,
11127 : : Relation pkrel, Oid indexOid, Oid parentConstr,
11128 : : int numfks, int16 *pkattnum, int16 *fkattnum,
11129 : : Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
11130 : : int numfkdelsetcols, int16 *fkdelsetcols,
11131 : : bool old_check_ok, LOCKMODE lockmode,
11132 : : Oid parentInsTrigger, Oid parentUpdTrigger,
11133 : : bool with_period)
11134 : : {
11135 : 2039 : Oid insertTriggerOid = InvalidOid,
11136 : 2039 : updateTriggerOid = InvalidOid;
11137 : :
11138 : : Assert(OidIsValid(parentConstr));
11139 : : Assert(CheckRelationLockedByMe(rel, ShareRowExclusiveLock, true));
11140 : : Assert(CheckRelationLockedByMe(pkrel, ShareRowExclusiveLock, true));
11141 : :
11142 [ - + ]: 2039 : if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
11143 [ # # ]: 0 : ereport(ERROR,
11144 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11145 : : errmsg("foreign key constraints are not supported on foreign tables")));
11146 : :
11147 : : /*
11148 : : * Add check triggers if the constraint is ENFORCED, and if needed,
11149 : : * schedule them to be checked in Phase 3.
11150 : : *
11151 : : * If the relation is partitioned, drill down to do it to its partitions.
11152 : : */
11153 [ + + ]: 2039 : if (fkconstraint->is_enforced)
11154 : 2006 : createForeignKeyCheckTriggers(RelationGetRelid(rel),
11155 : : RelationGetRelid(pkrel),
11156 : : fkconstraint,
11157 : : parentConstr,
11158 : : indexOid,
11159 : : parentInsTrigger, parentUpdTrigger,
11160 : : &insertTriggerOid, &updateTriggerOid);
11161 : :
11162 [ + + ]: 2039 : if (rel->rd_rel->relkind == RELKIND_RELATION)
11163 : : {
11164 : : /*
11165 : : * Tell Phase 3 to check that the constraint is satisfied by existing
11166 : : * rows. We can skip this during table creation, when constraint is
11167 : : * specified as NOT ENFORCED, or when requested explicitly by
11168 : : * specifying NOT VALID in an ADD FOREIGN KEY command, and when we're
11169 : : * recreating a constraint following a SET DATA TYPE operation that
11170 : : * did not impugn its validity.
11171 : : */
11172 [ + + + + : 1730 : if (wqueue && !old_check_ok && !fkconstraint->skip_validation &&
+ + ]
11173 [ + - ]: 613 : fkconstraint->is_enforced)
11174 : : {
11175 : : NewConstraint *newcon;
11176 : : AlteredTableInfo *tab;
11177 : :
11178 : 613 : tab = ATGetQueueEntry(wqueue, rel);
11179 : :
11180 : 613 : newcon = palloc0_object(NewConstraint);
11181 : 613 : newcon->name = get_constraint_name(parentConstr);
11182 : 613 : newcon->contype = CONSTR_FOREIGN;
11183 : 613 : newcon->refrelid = RelationGetRelid(pkrel);
11184 : 613 : newcon->refindid = indexOid;
11185 : 613 : newcon->conid = parentConstr;
11186 : 613 : newcon->conwithperiod = fkconstraint->fk_with_period;
11187 : 613 : newcon->qual = (Node *) fkconstraint;
11188 : :
11189 : 613 : tab->constraints = lappend(tab->constraints, newcon);
11190 : : }
11191 : : }
11192 [ + - ]: 309 : else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
11193 : : {
11194 : 309 : PartitionDesc pd = RelationGetPartitionDesc(rel, true);
11195 : : Relation trigrel;
11196 : :
11197 : : /*
11198 : : * Triggers of the foreign keys will be manipulated a bunch of times
11199 : : * in the loop below. To avoid repeatedly opening/closing the trigger
11200 : : * catalog relation, we open it here and pass it to the subroutines
11201 : : * called below.
11202 : : */
11203 : 309 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
11204 : :
11205 : : /*
11206 : : * Recurse to take appropriate action on each partition; either we
11207 : : * find an existing constraint to reparent to ours, or we create a new
11208 : : * one.
11209 : : */
11210 [ + + ]: 590 : for (int i = 0; i < pd->nparts; i++)
11211 : : {
11212 : 285 : Relation partition = table_open(pd->oids[i], lockmode);
11213 : : List *partFKs;
11214 : : AttrMap *attmap;
11215 : : AttrNumber mapped_fkattnum[INDEX_MAX_KEYS];
11216 : : bool attached;
11217 : : ObjectAddress address;
11218 : :
11219 : 285 : CheckAlterTableIsSafe(partition);
11220 : :
11221 : 281 : attmap = build_attrmap_by_name(RelationGetDescr(partition),
11222 : : RelationGetDescr(rel),
11223 : : false);
11224 [ + + ]: 706 : for (int j = 0; j < numfks; j++)
11225 : 425 : mapped_fkattnum[j] = attmap->attnums[fkattnum[j] - 1];
11226 : :
11227 : : /* Check whether an existing constraint can be repurposed */
11228 : 281 : partFKs = copyObject(RelationGetFKeyList(partition));
11229 : 281 : attached = false;
11230 [ + + + + : 571 : foreach_node(ForeignKeyCacheInfo, fk, partFKs)
+ + ]
11231 : : {
11232 [ + + ]: 17 : if (tryAttachPartitionForeignKey(wqueue,
11233 : : fk,
11234 : : partition,
11235 : : parentConstr,
11236 : : numfks,
11237 : : mapped_fkattnum,
11238 : : pkattnum,
11239 : : pfeqoperators,
11240 : : insertTriggerOid,
11241 : : updateTriggerOid,
11242 : : trigrel))
11243 : : {
11244 : 8 : attached = true;
11245 : 8 : break;
11246 : : }
11247 : : }
11248 [ + + ]: 281 : if (attached)
11249 : : {
11250 : 8 : table_close(partition, NoLock);
11251 : 8 : continue;
11252 : : }
11253 : :
11254 : : /*
11255 : : * No luck finding a good constraint to reuse; create our own.
11256 : : */
11257 : 273 : address = addFkConstraint(addFkReferencingSide,
11258 : : fkconstraint->conname, fkconstraint,
11259 : : partition, pkrel, indexOid, parentConstr,
11260 : : numfks, pkattnum,
11261 : : mapped_fkattnum, pfeqoperators,
11262 : : ppeqoperators, ffeqoperators,
11263 : : numfkdelsetcols, fkdelsetcols, true,
11264 : : with_period);
11265 : :
11266 : : /* call ourselves to finalize the creation and we're done */
11267 : 273 : addFkRecurseReferencing(wqueue, fkconstraint, partition, pkrel,
11268 : : indexOid,
11269 : : address.objectId,
11270 : : numfks,
11271 : : pkattnum,
11272 : : mapped_fkattnum,
11273 : : pfeqoperators,
11274 : : ppeqoperators,
11275 : : ffeqoperators,
11276 : : numfkdelsetcols,
11277 : : fkdelsetcols,
11278 : : old_check_ok,
11279 : : lockmode,
11280 : : insertTriggerOid,
11281 : : updateTriggerOid,
11282 : : with_period);
11283 : :
11284 : 273 : table_close(partition, NoLock);
11285 : : }
11286 : :
11287 : 305 : table_close(trigrel, RowExclusiveLock);
11288 : : }
11289 : 2035 : }
11290 : :
11291 : : /*
11292 : : * CloneForeignKeyConstraints
11293 : : * Clone foreign keys from a partitioned table to a newly acquired
11294 : : * partition.
11295 : : *
11296 : : * partitionRel is a partition of parentRel, so we can be certain that it has
11297 : : * the same columns with the same datatypes. The columns may be in different
11298 : : * order, though.
11299 : : *
11300 : : * wqueue must be passed to set up phase 3 constraint checking, unless the
11301 : : * referencing-side partition is known to be empty (such as in CREATE TABLE /
11302 : : * PARTITION OF).
11303 : : */
11304 : : static void
11305 : 7001 : CloneForeignKeyConstraints(List **wqueue, Relation parentRel,
11306 : : Relation partitionRel)
11307 : : {
11308 : : /* This only works for declarative partitioning */
11309 : : Assert(parentRel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
11310 : :
11311 : : /*
11312 : : * First, clone constraints where the parent is on the referencing side.
11313 : : */
11314 : 7001 : CloneFkReferencing(wqueue, parentRel, partitionRel);
11315 : :
11316 : : /*
11317 : : * Clone constraints for which the parent is on the referenced side.
11318 : : */
11319 : 6989 : CloneFkReferenced(parentRel, partitionRel);
11320 : 6989 : }
11321 : :
11322 : : /*
11323 : : * CloneFkReferenced
11324 : : * Subroutine for CloneForeignKeyConstraints
11325 : : *
11326 : : * Find all the FKs that have the parent relation on the referenced side;
11327 : : * clone those constraints to the given partition. This is to be called
11328 : : * when the partition is being created or attached.
11329 : : *
11330 : : * This recurses to partitions, if the relation being attached is partitioned.
11331 : : * Recursion is done by calling addFkRecurseReferenced.
11332 : : */
11333 : : static void
11334 : 6989 : CloneFkReferenced(Relation parentRel, Relation partitionRel)
11335 : : {
11336 : : Relation pg_constraint;
11337 : : AttrMap *attmap;
11338 : : ListCell *cell;
11339 : : SysScanDesc scan;
11340 : : ScanKeyData key[2];
11341 : : HeapTuple tuple;
11342 : 6989 : List *clone = NIL;
11343 : : Relation trigrel;
11344 : :
11345 : : /*
11346 : : * Search for any constraints where this partition's parent is in the
11347 : : * referenced side. However, we must not clone any constraint whose
11348 : : * parent constraint is also going to be cloned, to avoid duplicates. So
11349 : : * do it in two steps: first construct the list of constraints to clone,
11350 : : * then go over that list cloning those whose parents are not in the list.
11351 : : * (We must not rely on the parent being seen first, since the catalog
11352 : : * scan could return children first.)
11353 : : */
11354 : 6989 : pg_constraint = table_open(ConstraintRelationId, RowShareLock);
11355 : 6989 : ScanKeyInit(&key[0],
11356 : : Anum_pg_constraint_confrelid, BTEqualStrategyNumber,
11357 : : F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(parentRel)));
11358 : 6989 : ScanKeyInit(&key[1],
11359 : : Anum_pg_constraint_contype, BTEqualStrategyNumber,
11360 : : F_CHAREQ, CharGetDatum(CONSTRAINT_FOREIGN));
11361 : : /* This is a seqscan, as we don't have a usable index ... */
11362 : 6989 : scan = systable_beginscan(pg_constraint, InvalidOid, true,
11363 : : NULL, 2, key);
11364 [ + + ]: 7241 : while ((tuple = systable_getnext(scan)) != NULL)
11365 : : {
11366 : 252 : Form_pg_constraint constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
11367 : :
11368 : 252 : clone = lappend_oid(clone, constrForm->oid);
11369 : : }
11370 : 6989 : systable_endscan(scan);
11371 : 6989 : table_close(pg_constraint, RowShareLock);
11372 : :
11373 : : /*
11374 : : * Triggers of the foreign keys will be manipulated a bunch of times in
11375 : : * the loop below. To avoid repeatedly opening/closing the trigger
11376 : : * catalog relation, we open it here and pass it to the subroutines called
11377 : : * below.
11378 : : */
11379 : 6989 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
11380 : :
11381 : 6989 : attmap = build_attrmap_by_name(RelationGetDescr(partitionRel),
11382 : : RelationGetDescr(parentRel),
11383 : : false);
11384 [ + + + + : 7241 : foreach(cell, clone)
+ + ]
11385 : : {
11386 : 252 : Oid constrOid = lfirst_oid(cell);
11387 : : Form_pg_constraint constrForm;
11388 : : Relation fkRel;
11389 : : Oid indexOid;
11390 : : Oid partIndexId;
11391 : : int numfks;
11392 : : AttrNumber conkey[INDEX_MAX_KEYS];
11393 : : AttrNumber mapped_confkey[INDEX_MAX_KEYS];
11394 : : AttrNumber confkey[INDEX_MAX_KEYS];
11395 : : Oid conpfeqop[INDEX_MAX_KEYS];
11396 : : Oid conppeqop[INDEX_MAX_KEYS];
11397 : : Oid conffeqop[INDEX_MAX_KEYS];
11398 : : int numfkdelsetcols;
11399 : : AttrNumber confdelsetcols[INDEX_MAX_KEYS];
11400 : : Constraint *fkconstraint;
11401 : : ObjectAddress address;
11402 : 252 : Oid deleteTriggerOid = InvalidOid,
11403 : 252 : updateTriggerOid = InvalidOid;
11404 : :
11405 : 252 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
11406 [ - + ]: 252 : if (!HeapTupleIsValid(tuple))
11407 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", constrOid);
11408 : 252 : constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
11409 : :
11410 : : /*
11411 : : * As explained above: don't try to clone a constraint for which we're
11412 : : * going to clone the parent.
11413 : : */
11414 [ + + ]: 252 : if (list_member_oid(clone, constrForm->conparentid))
11415 : : {
11416 : 148 : ReleaseSysCache(tuple);
11417 : 148 : continue;
11418 : : }
11419 : :
11420 : : /* We need the same lock level that CreateTrigger will acquire */
11421 : 104 : fkRel = table_open(constrForm->conrelid, ShareRowExclusiveLock);
11422 : :
11423 : 104 : indexOid = constrForm->conindid;
11424 : 104 : DeconstructFkConstraintRow(tuple,
11425 : : &numfks,
11426 : : conkey,
11427 : : confkey,
11428 : : conpfeqop,
11429 : : conppeqop,
11430 : : conffeqop,
11431 : : &numfkdelsetcols,
11432 : : confdelsetcols);
11433 : :
11434 [ + + ]: 236 : for (int i = 0; i < numfks; i++)
11435 : 132 : mapped_confkey[i] = attmap->attnums[confkey[i] - 1];
11436 : :
11437 : 104 : fkconstraint = makeNode(Constraint);
11438 : 104 : fkconstraint->contype = CONSTRAINT_FOREIGN;
11439 : 104 : fkconstraint->conname = NameStr(constrForm->conname);
11440 : 104 : fkconstraint->deferrable = constrForm->condeferrable;
11441 : 104 : fkconstraint->initdeferred = constrForm->condeferred;
11442 : 104 : fkconstraint->location = -1;
11443 : 104 : fkconstraint->pktable = NULL;
11444 : : /* ->fk_attrs determined below */
11445 : 104 : fkconstraint->pk_attrs = NIL;
11446 : 104 : fkconstraint->fk_matchtype = constrForm->confmatchtype;
11447 : 104 : fkconstraint->fk_upd_action = constrForm->confupdtype;
11448 : 104 : fkconstraint->fk_del_action = constrForm->confdeltype;
11449 : 104 : fkconstraint->fk_del_set_cols = NIL;
11450 : 104 : fkconstraint->old_conpfeqop = NIL;
11451 : 104 : fkconstraint->old_pktable_oid = InvalidOid;
11452 : 104 : fkconstraint->is_enforced = constrForm->conenforced;
11453 : 104 : fkconstraint->skip_validation = false;
11454 : 104 : fkconstraint->initially_valid = constrForm->convalidated;
11455 : :
11456 : : /* set up colnames that are used to generate the constraint name */
11457 [ + + ]: 236 : for (int i = 0; i < numfks; i++)
11458 : : {
11459 : : Form_pg_attribute att;
11460 : :
11461 : 132 : att = TupleDescAttr(RelationGetDescr(fkRel),
11462 : 132 : conkey[i] - 1);
11463 : 132 : fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
11464 : 132 : makeString(NameStr(att->attname)));
11465 : : }
11466 : :
11467 : : /*
11468 : : * Add the new foreign key constraint pointing to the new partition.
11469 : : * Because this new partition appears in the referenced side of the
11470 : : * constraint, we don't need to set up for Phase 3 check.
11471 : : */
11472 : 104 : partIndexId = index_get_partition(partitionRel, indexOid);
11473 [ - + ]: 104 : if (!OidIsValid(partIndexId))
11474 [ # # ]: 0 : elog(ERROR, "index for %u not found in partition %s",
11475 : : indexOid, RelationGetRelationName(partitionRel));
11476 : :
11477 : : /*
11478 : : * Get the "action" triggers belonging to the constraint to pass as
11479 : : * parent OIDs for similar triggers that will be created on the
11480 : : * partition in addFkRecurseReferenced().
11481 : : */
11482 [ + - ]: 104 : if (constrForm->conenforced)
11483 : 104 : GetForeignKeyActionTriggers(trigrel, constrOid,
11484 : : constrForm->confrelid, constrForm->conrelid,
11485 : : &deleteTriggerOid, &updateTriggerOid);
11486 : :
11487 : : /* Add this constraint ... */
11488 : 104 : address = addFkConstraint(addFkReferencedSide,
11489 : : fkconstraint->conname, fkconstraint, fkRel,
11490 : : partitionRel, partIndexId, constrOid,
11491 : : numfks, mapped_confkey,
11492 : : conkey, conpfeqop, conppeqop, conffeqop,
11493 : : numfkdelsetcols, confdelsetcols, false,
11494 : 104 : constrForm->conperiod);
11495 : : /* ... and recurse */
11496 : 104 : addFkRecurseReferenced(fkconstraint,
11497 : : fkRel,
11498 : : partitionRel,
11499 : : partIndexId,
11500 : : address.objectId,
11501 : : numfks,
11502 : : mapped_confkey,
11503 : : conkey,
11504 : : conpfeqop,
11505 : : conppeqop,
11506 : : conffeqop,
11507 : : numfkdelsetcols,
11508 : : confdelsetcols,
11509 : : true,
11510 : : deleteTriggerOid,
11511 : : updateTriggerOid,
11512 : 104 : constrForm->conperiod);
11513 : :
11514 : 104 : table_close(fkRel, NoLock);
11515 : 104 : ReleaseSysCache(tuple);
11516 : : }
11517 : :
11518 : 6989 : table_close(trigrel, RowExclusiveLock);
11519 : 6989 : }
11520 : :
11521 : : /*
11522 : : * CloneFkReferencing
11523 : : * Subroutine for CloneForeignKeyConstraints
11524 : : *
11525 : : * For each FK constraint of the parent relation in the given list, find an
11526 : : * equivalent constraint in its partition relation that can be reparented;
11527 : : * if one cannot be found, create a new constraint in the partition as its
11528 : : * child.
11529 : : *
11530 : : * If wqueue is given, it is used to set up phase-3 verification for each
11531 : : * cloned constraint; omit it if such verification is not needed
11532 : : * (example: the partition is being created anew).
11533 : : */
11534 : : static void
11535 : 7001 : CloneFkReferencing(List **wqueue, Relation parentRel, Relation partRel)
11536 : : {
11537 : : AttrMap *attmap;
11538 : : List *partFKs;
11539 : 7001 : List *clone = NIL;
11540 : : ListCell *cell;
11541 : : Relation trigrel;
11542 : :
11543 : : /* obtain a list of constraints that we need to clone */
11544 [ + + + + : 7788 : foreach(cell, RelationGetFKeyList(parentRel))
+ + ]
11545 : : {
11546 : 791 : ForeignKeyCacheInfo *fk = lfirst(cell);
11547 : :
11548 : : /*
11549 : : * Refuse to attach a table as partition that this partitioned table
11550 : : * already has a foreign key to. This isn't useful schema, which is
11551 : : * proven by the fact that there have been no user complaints that
11552 : : * it's already impossible to achieve this in the opposite direction,
11553 : : * i.e., creating a foreign key that references a partition. This
11554 : : * restriction allows us to dodge some complexities around
11555 : : * pg_constraint and pg_trigger row creations that would be needed
11556 : : * during ATTACH/DETACH for this kind of relationship.
11557 : : */
11558 [ + + ]: 791 : if (fk->confrelid == RelationGetRelid(partRel))
11559 [ + - ]: 4 : ereport(ERROR,
11560 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
11561 : : errmsg("cannot attach table \"%s\" as a partition because it is referenced by foreign key \"%s\"",
11562 : : RelationGetRelationName(partRel),
11563 : : get_constraint_name(fk->conoid))));
11564 : :
11565 : 787 : clone = lappend_oid(clone, fk->conoid);
11566 : : }
11567 : :
11568 : : /*
11569 : : * Silently do nothing if there's nothing to do. In particular, this
11570 : : * avoids throwing a spurious error for foreign tables.
11571 : : */
11572 [ + + ]: 6997 : if (clone == NIL)
11573 : 6674 : return;
11574 : :
11575 [ - + ]: 323 : if (partRel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
11576 [ # # ]: 0 : ereport(ERROR,
11577 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11578 : : errmsg("foreign key constraints are not supported on foreign tables")));
11579 : :
11580 : : /*
11581 : : * Triggers of the foreign keys will be manipulated a bunch of times in
11582 : : * the loop below. To avoid repeatedly opening/closing the trigger
11583 : : * catalog relation, we open it here and pass it to the subroutines called
11584 : : * below.
11585 : : */
11586 : 323 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
11587 : :
11588 : : /*
11589 : : * The constraint key may differ, if the columns in the partition are
11590 : : * different. This map is used to convert them.
11591 : : */
11592 : 323 : attmap = build_attrmap_by_name(RelationGetDescr(partRel),
11593 : : RelationGetDescr(parentRel),
11594 : : false);
11595 : :
11596 : 323 : partFKs = copyObject(RelationGetFKeyList(partRel));
11597 : :
11598 [ + - + + : 1102 : foreach(cell, clone)
+ + ]
11599 : : {
11600 : 787 : Oid parentConstrOid = lfirst_oid(cell);
11601 : : Form_pg_constraint constrForm;
11602 : : Relation pkrel;
11603 : : HeapTuple tuple;
11604 : : int numfks;
11605 : : AttrNumber conkey[INDEX_MAX_KEYS];
11606 : : AttrNumber mapped_conkey[INDEX_MAX_KEYS];
11607 : : AttrNumber confkey[INDEX_MAX_KEYS];
11608 : : Oid conpfeqop[INDEX_MAX_KEYS];
11609 : : Oid conppeqop[INDEX_MAX_KEYS];
11610 : : Oid conffeqop[INDEX_MAX_KEYS];
11611 : : int numfkdelsetcols;
11612 : : AttrNumber confdelsetcols[INDEX_MAX_KEYS];
11613 : : Constraint *fkconstraint;
11614 : : bool attached;
11615 : : Oid indexOid;
11616 : : ObjectAddress address;
11617 : : ListCell *lc;
11618 : 787 : Oid insertTriggerOid = InvalidOid,
11619 : 787 : updateTriggerOid = InvalidOid;
11620 : : bool with_period;
11621 : :
11622 : 787 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(parentConstrOid));
11623 [ - + ]: 787 : if (!HeapTupleIsValid(tuple))
11624 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u",
11625 : : parentConstrOid);
11626 : 787 : constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
11627 : :
11628 : : /* Don't clone constraints whose parents are being cloned */
11629 [ + + ]: 787 : if (list_member_oid(clone, constrForm->conparentid))
11630 : : {
11631 : 440 : ReleaseSysCache(tuple);
11632 : 540 : continue;
11633 : : }
11634 : :
11635 : : /*
11636 : : * Need to prevent concurrent deletions. If pkrel is a partitioned
11637 : : * relation, that means to lock all partitions.
11638 : : */
11639 : 347 : pkrel = table_open(constrForm->confrelid, ShareRowExclusiveLock);
11640 [ + + ]: 347 : if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
11641 : 148 : (void) find_all_inheritors(RelationGetRelid(pkrel),
11642 : : ShareRowExclusiveLock, NULL);
11643 : :
11644 : 347 : DeconstructFkConstraintRow(tuple, &numfks, conkey, confkey,
11645 : : conpfeqop, conppeqop, conffeqop,
11646 : : &numfkdelsetcols, confdelsetcols);
11647 [ + + ]: 850 : for (int i = 0; i < numfks; i++)
11648 : 503 : mapped_conkey[i] = attmap->attnums[conkey[i] - 1];
11649 : :
11650 : : /*
11651 : : * Get the "check" triggers belonging to the constraint, if it is
11652 : : * ENFORCED, to pass as parent OIDs for similar triggers that will be
11653 : : * created on the partition in addFkRecurseReferencing(). They are
11654 : : * also passed to tryAttachPartitionForeignKey() below to simply
11655 : : * assign as parents to the partition's existing "check" triggers,
11656 : : * that is, if the corresponding constraints is deemed attachable to
11657 : : * the parent constraint.
11658 : : */
11659 [ + + ]: 347 : if (constrForm->conenforced)
11660 : 339 : GetForeignKeyCheckTriggers(trigrel, constrForm->oid,
11661 : : constrForm->confrelid, constrForm->conrelid,
11662 : : &insertTriggerOid, &updateTriggerOid);
11663 : :
11664 : : /*
11665 : : * Before creating a new constraint, see whether any existing FKs are
11666 : : * fit for the purpose. If one is, attach the parent constraint to
11667 : : * it, and don't clone anything. This way we avoid the expensive
11668 : : * verification step and don't end up with a duplicate FK, and we
11669 : : * don't need to recurse to partitions for this constraint.
11670 : : */
11671 : 347 : attached = false;
11672 [ + + + + : 407 : foreach(lc, partFKs)
+ + ]
11673 : : {
11674 : 164 : ForeignKeyCacheInfo *fk = lfirst_node(ForeignKeyCacheInfo, lc);
11675 : :
11676 [ + + ]: 164 : if (tryAttachPartitionForeignKey(wqueue,
11677 : : fk,
11678 : : partRel,
11679 : : parentConstrOid,
11680 : : numfks,
11681 : : mapped_conkey,
11682 : : confkey,
11683 : : conpfeqop,
11684 : : insertTriggerOid,
11685 : : updateTriggerOid,
11686 : : trigrel))
11687 : : {
11688 : 100 : attached = true;
11689 : 100 : table_close(pkrel, NoLock);
11690 : 100 : break;
11691 : : }
11692 : : }
11693 [ + + ]: 343 : if (attached)
11694 : : {
11695 : 100 : ReleaseSysCache(tuple);
11696 : 100 : continue;
11697 : : }
11698 : :
11699 : : /* No dice. Set up to create our own constraint */
11700 : 243 : fkconstraint = makeNode(Constraint);
11701 : 243 : fkconstraint->contype = CONSTRAINT_FOREIGN;
11702 : : /* ->conname determined below */
11703 : 243 : fkconstraint->deferrable = constrForm->condeferrable;
11704 : 243 : fkconstraint->initdeferred = constrForm->condeferred;
11705 : 243 : fkconstraint->location = -1;
11706 : 243 : fkconstraint->pktable = NULL;
11707 : : /* ->fk_attrs determined below */
11708 : 243 : fkconstraint->pk_attrs = NIL;
11709 : 243 : fkconstraint->fk_matchtype = constrForm->confmatchtype;
11710 : 243 : fkconstraint->fk_upd_action = constrForm->confupdtype;
11711 : 243 : fkconstraint->fk_del_action = constrForm->confdeltype;
11712 : 243 : fkconstraint->fk_del_set_cols = NIL;
11713 : 243 : fkconstraint->old_conpfeqop = NIL;
11714 : 243 : fkconstraint->old_pktable_oid = InvalidOid;
11715 : 243 : fkconstraint->is_enforced = constrForm->conenforced;
11716 : 243 : fkconstraint->skip_validation = false;
11717 : 243 : fkconstraint->initially_valid = constrForm->convalidated;
11718 [ + + ]: 566 : for (int i = 0; i < numfks; i++)
11719 : : {
11720 : : Form_pg_attribute att;
11721 : :
11722 : 323 : att = TupleDescAttr(RelationGetDescr(partRel),
11723 : 323 : mapped_conkey[i] - 1);
11724 : 323 : fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
11725 : 323 : makeString(NameStr(att->attname)));
11726 : : }
11727 : :
11728 : 243 : indexOid = constrForm->conindid;
11729 : 243 : with_period = constrForm->conperiod;
11730 : :
11731 : : /* Create the pg_constraint entry at this level */
11732 : 243 : address = addFkConstraint(addFkReferencingSide,
11733 : 243 : NameStr(constrForm->conname), fkconstraint,
11734 : : partRel, pkrel, indexOid, parentConstrOid,
11735 : : numfks, confkey,
11736 : : mapped_conkey, conpfeqop,
11737 : : conppeqop, conffeqop,
11738 : : numfkdelsetcols, confdelsetcols,
11739 : : false, with_period);
11740 : :
11741 : : /* Done with the cloned constraint's tuple */
11742 : 243 : ReleaseSysCache(tuple);
11743 : :
11744 : : /* Create the check triggers, and recurse to partitions, if any */
11745 : 243 : addFkRecurseReferencing(wqueue,
11746 : : fkconstraint,
11747 : : partRel,
11748 : : pkrel,
11749 : : indexOid,
11750 : : address.objectId,
11751 : : numfks,
11752 : : confkey,
11753 : : mapped_conkey,
11754 : : conpfeqop,
11755 : : conppeqop,
11756 : : conffeqop,
11757 : : numfkdelsetcols,
11758 : : confdelsetcols,
11759 : : false, /* no old check exists */
11760 : : AccessExclusiveLock,
11761 : : insertTriggerOid,
11762 : : updateTriggerOid,
11763 : : with_period);
11764 : 239 : table_close(pkrel, NoLock);
11765 : : }
11766 : :
11767 : 315 : table_close(trigrel, RowExclusiveLock);
11768 : : }
11769 : :
11770 : : /*
11771 : : * When the parent of a partition receives [the referencing side of] a foreign
11772 : : * key, we must propagate that foreign key to the partition. However, the
11773 : : * partition might already have an equivalent foreign key; this routine
11774 : : * compares the given ForeignKeyCacheInfo (in the partition) to the FK defined
11775 : : * by the other parameters. If they are equivalent, create the link between
11776 : : * the two constraints and return true.
11777 : : *
11778 : : * If the given FK does not match the one defined by rest of the params,
11779 : : * return false.
11780 : : */
11781 : : static bool
11782 : 181 : tryAttachPartitionForeignKey(List **wqueue,
11783 : : ForeignKeyCacheInfo *fk,
11784 : : Relation partition,
11785 : : Oid parentConstrOid,
11786 : : int numfks,
11787 : : AttrNumber *mapped_conkey,
11788 : : AttrNumber *confkey,
11789 : : Oid *conpfeqop,
11790 : : Oid parentInsTrigger,
11791 : : Oid parentUpdTrigger,
11792 : : Relation trigrel)
11793 : : {
11794 : : HeapTuple parentConstrTup;
11795 : : Form_pg_constraint parentConstr;
11796 : : HeapTuple partcontup;
11797 : : Form_pg_constraint partConstr;
11798 : :
11799 : 181 : parentConstrTup = SearchSysCache1(CONSTROID,
11800 : : ObjectIdGetDatum(parentConstrOid));
11801 [ - + ]: 181 : if (!HeapTupleIsValid(parentConstrTup))
11802 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", parentConstrOid);
11803 : 181 : parentConstr = (Form_pg_constraint) GETSTRUCT(parentConstrTup);
11804 : :
11805 : : /*
11806 : : * Do some quick & easy initial checks. If any of these fail, we cannot
11807 : : * use this constraint.
11808 : : */
11809 [ + - - + ]: 181 : if (fk->confrelid != parentConstr->confrelid || fk->nkeys != numfks)
11810 : : {
11811 : 0 : ReleaseSysCache(parentConstrTup);
11812 : 0 : return false;
11813 : : }
11814 [ + + ]: 503 : for (int i = 0; i < numfks; i++)
11815 : : {
11816 [ + - ]: 322 : if (fk->conkey[i] != mapped_conkey[i] ||
11817 [ + - ]: 322 : fk->confkey[i] != confkey[i] ||
11818 [ - + ]: 322 : fk->conpfeqop[i] != conpfeqop[i])
11819 : : {
11820 : 0 : ReleaseSysCache(parentConstrTup);
11821 : 0 : return false;
11822 : : }
11823 : : }
11824 : :
11825 : : /* Looks good so far; perform more extensive checks. */
11826 : 181 : partcontup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(fk->conoid));
11827 [ - + ]: 181 : if (!HeapTupleIsValid(partcontup))
11828 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", fk->conoid);
11829 : 181 : partConstr = (Form_pg_constraint) GETSTRUCT(partcontup);
11830 : :
11831 : : /*
11832 : : * An error should be raised if the constraint enforceability is
11833 : : * different. Returning false without raising an error, as we do for other
11834 : : * attributes, could lead to a duplicate constraint with the same
11835 : : * enforceability as the parent. While this may be acceptable, it may not
11836 : : * be ideal. Therefore, it's better to raise an error and allow the user
11837 : : * to correct the enforceability before proceeding.
11838 : : */
11839 [ + + ]: 181 : if (partConstr->conenforced != parentConstr->conenforced)
11840 [ + - ]: 4 : ereport(ERROR,
11841 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
11842 : : errmsg("constraint \"%s\" enforceability conflicts with constraint \"%s\" on relation \"%s\"",
11843 : : NameStr(parentConstr->conname),
11844 : : NameStr(partConstr->conname),
11845 : : RelationGetRelationName(partition))));
11846 : :
11847 [ + + ]: 177 : if (OidIsValid(partConstr->conparentid) ||
11848 [ + + ]: 158 : partConstr->condeferrable != parentConstr->condeferrable ||
11849 [ + - ]: 140 : partConstr->condeferred != parentConstr->condeferred ||
11850 [ + + ]: 140 : partConstr->confupdtype != parentConstr->confupdtype ||
11851 [ + - ]: 117 : partConstr->confdeltype != parentConstr->confdeltype ||
11852 [ + + ]: 117 : partConstr->confmatchtype != parentConstr->confmatchtype)
11853 : : {
11854 : 69 : ReleaseSysCache(parentConstrTup);
11855 : 69 : ReleaseSysCache(partcontup);
11856 : 69 : return false;
11857 : : }
11858 : :
11859 : 108 : ReleaseSysCache(parentConstrTup);
11860 : 108 : ReleaseSysCache(partcontup);
11861 : :
11862 : : /* Looks good! Attach this constraint. */
11863 : 108 : AttachPartitionForeignKey(wqueue, partition, fk->conoid,
11864 : : parentConstrOid, parentInsTrigger,
11865 : : parentUpdTrigger, trigrel);
11866 : :
11867 : 108 : return true;
11868 : : }
11869 : :
11870 : : /*
11871 : : * AttachPartitionForeignKey
11872 : : *
11873 : : * The subroutine for tryAttachPartitionForeignKey performs the final tasks of
11874 : : * attaching the constraint, removing redundant triggers and entries from
11875 : : * pg_constraint, and setting the constraint's parent.
11876 : : */
11877 : : static void
11878 : 108 : AttachPartitionForeignKey(List **wqueue,
11879 : : Relation partition,
11880 : : Oid partConstrOid,
11881 : : Oid parentConstrOid,
11882 : : Oid parentInsTrigger,
11883 : : Oid parentUpdTrigger,
11884 : : Relation trigrel)
11885 : : {
11886 : : HeapTuple parentConstrTup;
11887 : : Form_pg_constraint parentConstr;
11888 : : HeapTuple partcontup;
11889 : : Form_pg_constraint partConstr;
11890 : : bool queueValidation;
11891 : : Oid partConstrFrelid;
11892 : : Oid partConstrRelid;
11893 : : bool parentConstrIsEnforced;
11894 : :
11895 : : /* Fetch the parent constraint tuple */
11896 : 108 : parentConstrTup = SearchSysCache1(CONSTROID,
11897 : : ObjectIdGetDatum(parentConstrOid));
11898 [ - + ]: 108 : if (!HeapTupleIsValid(parentConstrTup))
11899 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", parentConstrOid);
11900 : 108 : parentConstr = (Form_pg_constraint) GETSTRUCT(parentConstrTup);
11901 : 108 : parentConstrIsEnforced = parentConstr->conenforced;
11902 : :
11903 : : /* Fetch the child constraint tuple */
11904 : 108 : partcontup = SearchSysCache1(CONSTROID,
11905 : : ObjectIdGetDatum(partConstrOid));
11906 [ - + ]: 108 : if (!HeapTupleIsValid(partcontup))
11907 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", partConstrOid);
11908 : 108 : partConstr = (Form_pg_constraint) GETSTRUCT(partcontup);
11909 : 108 : partConstrFrelid = partConstr->confrelid;
11910 : 108 : partConstrRelid = partConstr->conrelid;
11911 : :
11912 : : /*
11913 : : * If the referenced table is partitioned, then the partition we're
11914 : : * attaching now has extra pg_constraint rows and action triggers that are
11915 : : * no longer needed. Remove those.
11916 : : */
11917 [ + + ]: 108 : if (get_rel_relkind(partConstrFrelid) == RELKIND_PARTITIONED_TABLE)
11918 : : {
11919 : 24 : Relation pg_constraint = table_open(ConstraintRelationId, RowShareLock);
11920 : :
11921 : 24 : RemoveInheritedConstraint(pg_constraint, trigrel, partConstrOid,
11922 : : partConstrRelid);
11923 : :
11924 : 24 : table_close(pg_constraint, RowShareLock);
11925 : : }
11926 : :
11927 : : /*
11928 : : * Will we need to validate this constraint? A valid parent constraint
11929 : : * implies that all child constraints have been validated, so if this one
11930 : : * isn't, we must trigger phase 3 validation.
11931 : : */
11932 [ + + + + ]: 108 : queueValidation = parentConstr->convalidated && !partConstr->convalidated;
11933 : :
11934 : 108 : ReleaseSysCache(partcontup);
11935 : 108 : ReleaseSysCache(parentConstrTup);
11936 : :
11937 : : /*
11938 : : * The action triggers in the new partition become redundant -- the parent
11939 : : * table already has equivalent ones, and those will be able to reach the
11940 : : * partition. Remove the ones in the partition. We identify them because
11941 : : * they have our constraint OID, as well as being on the referenced rel.
11942 : : */
11943 : 108 : DropForeignKeyConstraintTriggers(trigrel, partConstrOid, partConstrFrelid,
11944 : : partConstrRelid);
11945 : :
11946 : 108 : ConstraintSetParentConstraint(partConstrOid, parentConstrOid,
11947 : : RelationGetRelid(partition));
11948 : :
11949 : : /*
11950 : : * Like the constraint, attach partition's "check" triggers to the
11951 : : * corresponding parent triggers if the constraint is ENFORCED. NOT
11952 : : * ENFORCED constraints do not have these triggers.
11953 : : */
11954 [ + + ]: 108 : if (parentConstrIsEnforced)
11955 : : {
11956 : : Oid insertTriggerOid,
11957 : : updateTriggerOid;
11958 : :
11959 : 100 : GetForeignKeyCheckTriggers(trigrel,
11960 : : partConstrOid, partConstrFrelid, partConstrRelid,
11961 : : &insertTriggerOid, &updateTriggerOid);
11962 : : Assert(OidIsValid(insertTriggerOid) && OidIsValid(parentInsTrigger));
11963 : 100 : TriggerSetParentTrigger(trigrel, insertTriggerOid, parentInsTrigger,
11964 : : RelationGetRelid(partition));
11965 : : Assert(OidIsValid(updateTriggerOid) && OidIsValid(parentUpdTrigger));
11966 : 100 : TriggerSetParentTrigger(trigrel, updateTriggerOid, parentUpdTrigger,
11967 : : RelationGetRelid(partition));
11968 : : }
11969 : :
11970 : : /*
11971 : : * We updated this pg_constraint row above to set its parent; validating
11972 : : * it will cause its convalidated flag to change, so we need CCI here. In
11973 : : * addition, we need it unconditionally for the rare case where the parent
11974 : : * table has *two* identical constraints; when reaching this function for
11975 : : * the second one, we must have made our changes visible, otherwise we
11976 : : * would try to attach both to this one.
11977 : : */
11978 : 108 : CommandCounterIncrement();
11979 : :
11980 : : /* If validation is needed, put it in the queue now. */
11981 [ + + ]: 108 : if (queueValidation)
11982 : : {
11983 : : Relation conrel;
11984 : : Oid confrelid;
11985 : :
11986 : 12 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
11987 : :
11988 : 12 : partcontup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(partConstrOid));
11989 [ - + ]: 12 : if (!HeapTupleIsValid(partcontup))
11990 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", partConstrOid);
11991 : :
11992 : 12 : confrelid = ((Form_pg_constraint) GETSTRUCT(partcontup))->confrelid;
11993 : :
11994 : : /* Use the same lock as for AT_ValidateConstraint */
11995 : 12 : QueueFKConstraintValidation(wqueue, conrel, partition, confrelid,
11996 : : partcontup, ShareUpdateExclusiveLock);
11997 : 12 : ReleaseSysCache(partcontup);
11998 : 12 : table_close(conrel, RowExclusiveLock);
11999 : : }
12000 : 108 : }
12001 : :
12002 : : /*
12003 : : * RemoveInheritedConstraint
12004 : : *
12005 : : * Removes the constraint and its associated trigger from the specified
12006 : : * relation, which inherited the given constraint.
12007 : : */
12008 : : static void
12009 : 24 : RemoveInheritedConstraint(Relation conrel, Relation trigrel, Oid conoid,
12010 : : Oid conrelid)
12011 : : {
12012 : : ObjectAddresses *objs;
12013 : : HeapTuple consttup;
12014 : : ScanKeyData key;
12015 : : SysScanDesc scan;
12016 : : HeapTuple trigtup;
12017 : :
12018 : 24 : ScanKeyInit(&key,
12019 : : Anum_pg_constraint_conrelid,
12020 : : BTEqualStrategyNumber, F_OIDEQ,
12021 : : ObjectIdGetDatum(conrelid));
12022 : :
12023 : 24 : scan = systable_beginscan(conrel,
12024 : : ConstraintRelidTypidNameIndexId,
12025 : : true, NULL, 1, &key);
12026 : 24 : objs = new_object_addresses();
12027 [ + + ]: 216 : while ((consttup = systable_getnext(scan)) != NULL)
12028 : : {
12029 : 192 : Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(consttup);
12030 : :
12031 [ + + ]: 192 : if (conform->conparentid != conoid)
12032 : 140 : continue;
12033 : : else
12034 : : {
12035 : : ObjectAddress addr;
12036 : : SysScanDesc scan2;
12037 : : ScanKeyData key2;
12038 : : int n PG_USED_FOR_ASSERTS_ONLY;
12039 : :
12040 : 52 : ObjectAddressSet(addr, ConstraintRelationId, conform->oid);
12041 : 52 : add_exact_object_address(&addr, objs);
12042 : :
12043 : : /*
12044 : : * First we must delete the dependency record that binds the
12045 : : * constraint records together.
12046 : : */
12047 : 52 : n = deleteDependencyRecordsForSpecific(ConstraintRelationId,
12048 : : conform->oid,
12049 : : DEPENDENCY_INTERNAL,
12050 : : ConstraintRelationId,
12051 : : conoid);
12052 : : Assert(n == 1); /* actually only one is expected */
12053 : :
12054 : : /*
12055 : : * Now search for the triggers for this constraint and set them up
12056 : : * for deletion too
12057 : : */
12058 : 52 : ScanKeyInit(&key2,
12059 : : Anum_pg_trigger_tgconstraint,
12060 : : BTEqualStrategyNumber, F_OIDEQ,
12061 : : ObjectIdGetDatum(conform->oid));
12062 : 52 : scan2 = systable_beginscan(trigrel, TriggerConstraintIndexId,
12063 : : true, NULL, 1, &key2);
12064 [ + + ]: 156 : while ((trigtup = systable_getnext(scan2)) != NULL)
12065 : : {
12066 : 104 : ObjectAddressSet(addr, TriggerRelationId,
12067 : : ((Form_pg_trigger) GETSTRUCT(trigtup))->oid);
12068 : 104 : add_exact_object_address(&addr, objs);
12069 : : }
12070 : 52 : systable_endscan(scan2);
12071 : : }
12072 : : }
12073 : : /* make the dependency deletions visible */
12074 : 24 : CommandCounterIncrement();
12075 : 24 : performMultipleDeletions(objs, DROP_RESTRICT,
12076 : : PERFORM_DELETION_INTERNAL);
12077 : 24 : systable_endscan(scan);
12078 : 24 : }
12079 : :
12080 : : /*
12081 : : * DropForeignKeyConstraintTriggers
12082 : : *
12083 : : * The subroutine for tryAttachPartitionForeignKey handles the deletion of
12084 : : * action triggers for the foreign key constraint.
12085 : : *
12086 : : * If valid confrelid and conrelid values are not provided, the respective
12087 : : * trigger check will be skipped, and the trigger will be considered for
12088 : : * removal.
12089 : : */
12090 : : static void
12091 : 160 : DropForeignKeyConstraintTriggers(Relation trigrel, Oid conoid, Oid confrelid,
12092 : : Oid conrelid)
12093 : : {
12094 : : ScanKeyData key;
12095 : : SysScanDesc scan;
12096 : : HeapTuple trigtup;
12097 : :
12098 : 160 : ScanKeyInit(&key,
12099 : : Anum_pg_trigger_tgconstraint,
12100 : : BTEqualStrategyNumber, F_OIDEQ,
12101 : : ObjectIdGetDatum(conoid));
12102 : 160 : scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
12103 : : NULL, 1, &key);
12104 [ + + ]: 696 : while ((trigtup = systable_getnext(scan)) != NULL)
12105 : : {
12106 : 536 : Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
12107 : : ObjectAddress trigger;
12108 : :
12109 : : /* Invalid if trigger is not for a referential integrity constraint */
12110 [ - + ]: 536 : if (!OidIsValid(trgform->tgconstrrelid))
12111 : 200 : continue;
12112 [ + + + + ]: 536 : if (OidIsValid(conrelid) && trgform->tgconstrrelid != conrelid)
12113 : 200 : continue;
12114 [ + + - + ]: 336 : if (OidIsValid(confrelid) && trgform->tgrelid != confrelid)
12115 : 0 : continue;
12116 : :
12117 : : /* We should be dropping trigger related to foreign key constraint */
12118 : : Assert(trgform->tgfoid == F_RI_FKEY_CHECK_INS ||
12119 : : trgform->tgfoid == F_RI_FKEY_CHECK_UPD ||
12120 : : trgform->tgfoid == F_RI_FKEY_CASCADE_DEL ||
12121 : : trgform->tgfoid == F_RI_FKEY_CASCADE_UPD ||
12122 : : trgform->tgfoid == F_RI_FKEY_RESTRICT_DEL ||
12123 : : trgform->tgfoid == F_RI_FKEY_RESTRICT_UPD ||
12124 : : trgform->tgfoid == F_RI_FKEY_SETNULL_DEL ||
12125 : : trgform->tgfoid == F_RI_FKEY_SETNULL_UPD ||
12126 : : trgform->tgfoid == F_RI_FKEY_SETDEFAULT_DEL ||
12127 : : trgform->tgfoid == F_RI_FKEY_SETDEFAULT_UPD ||
12128 : : trgform->tgfoid == F_RI_FKEY_NOACTION_DEL ||
12129 : : trgform->tgfoid == F_RI_FKEY_NOACTION_UPD);
12130 : :
12131 : : /*
12132 : : * The constraint is originally set up to contain this trigger as an
12133 : : * implementation object, so there's a dependency record that links
12134 : : * the two; however, since the trigger is no longer needed, we remove
12135 : : * the dependency link in order to be able to drop the trigger while
12136 : : * keeping the constraint intact.
12137 : : */
12138 : 336 : deleteDependencyRecordsFor(TriggerRelationId,
12139 : : trgform->oid,
12140 : : false);
12141 : : /* make dependency deletion visible to performDeletion */
12142 : 336 : CommandCounterIncrement();
12143 : 336 : ObjectAddressSet(trigger, TriggerRelationId,
12144 : : trgform->oid);
12145 : 336 : performDeletion(&trigger, DROP_RESTRICT, 0);
12146 : : /* make trigger drop visible, in case the loop iterates */
12147 : 336 : CommandCounterIncrement();
12148 : : }
12149 : :
12150 : 160 : systable_endscan(scan);
12151 : 160 : }
12152 : :
12153 : : /*
12154 : : * GetForeignKeyActionTriggers
12155 : : * Returns delete and update "action" triggers of the given relation
12156 : : * belonging to the given constraint
12157 : : */
12158 : : static void
12159 : 104 : GetForeignKeyActionTriggers(Relation trigrel,
12160 : : Oid conoid, Oid confrelid, Oid conrelid,
12161 : : Oid *deleteTriggerOid,
12162 : : Oid *updateTriggerOid)
12163 : : {
12164 : : ScanKeyData key;
12165 : : SysScanDesc scan;
12166 : : HeapTuple trigtup;
12167 : :
12168 : 104 : *deleteTriggerOid = *updateTriggerOid = InvalidOid;
12169 : 104 : ScanKeyInit(&key,
12170 : : Anum_pg_trigger_tgconstraint,
12171 : : BTEqualStrategyNumber, F_OIDEQ,
12172 : : ObjectIdGetDatum(conoid));
12173 : :
12174 : 104 : scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
12175 : : NULL, 1, &key);
12176 [ + - ]: 218 : while ((trigtup = systable_getnext(scan)) != NULL)
12177 : : {
12178 : 218 : Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
12179 : :
12180 [ + + ]: 218 : if (trgform->tgconstrrelid != conrelid)
12181 : 9 : continue;
12182 [ - + ]: 209 : if (trgform->tgrelid != confrelid)
12183 : 0 : continue;
12184 : : /* Only ever look at "action" triggers on the PK side. */
12185 [ + + ]: 209 : if (RI_FKey_trigger_type(trgform->tgfoid) != RI_TRIGGER_PK)
12186 : 1 : continue;
12187 [ + + ]: 208 : if (TRIGGER_FOR_DELETE(trgform->tgtype))
12188 : : {
12189 : : Assert(*deleteTriggerOid == InvalidOid);
12190 : 104 : *deleteTriggerOid = trgform->oid;
12191 : : }
12192 [ + - ]: 104 : else if (TRIGGER_FOR_UPDATE(trgform->tgtype))
12193 : : {
12194 : : Assert(*updateTriggerOid == InvalidOid);
12195 : 104 : *updateTriggerOid = trgform->oid;
12196 : : }
12197 : : #ifndef USE_ASSERT_CHECKING
12198 : : /* In an assert-enabled build, continue looking to find duplicates */
12199 [ + + + + ]: 208 : if (OidIsValid(*deleteTriggerOid) && OidIsValid(*updateTriggerOid))
12200 : 104 : break;
12201 : : #endif
12202 : : }
12203 : :
12204 [ - + ]: 104 : if (!OidIsValid(*deleteTriggerOid))
12205 [ # # ]: 0 : elog(ERROR, "could not find ON DELETE action trigger of foreign key constraint %u",
12206 : : conoid);
12207 [ - + ]: 104 : if (!OidIsValid(*updateTriggerOid))
12208 [ # # ]: 0 : elog(ERROR, "could not find ON UPDATE action trigger of foreign key constraint %u",
12209 : : conoid);
12210 : :
12211 : 104 : systable_endscan(scan);
12212 : 104 : }
12213 : :
12214 : : /*
12215 : : * GetForeignKeyCheckTriggers
12216 : : * Returns insert and update "check" triggers of the given relation
12217 : : * belonging to the given constraint
12218 : : */
12219 : : static void
12220 : 507 : GetForeignKeyCheckTriggers(Relation trigrel,
12221 : : Oid conoid, Oid confrelid, Oid conrelid,
12222 : : Oid *insertTriggerOid,
12223 : : Oid *updateTriggerOid)
12224 : : {
12225 : : ScanKeyData key;
12226 : : SysScanDesc scan;
12227 : : HeapTuple trigtup;
12228 : :
12229 : 507 : *insertTriggerOid = *updateTriggerOid = InvalidOid;
12230 : 507 : ScanKeyInit(&key,
12231 : : Anum_pg_trigger_tgconstraint,
12232 : : BTEqualStrategyNumber, F_OIDEQ,
12233 : : ObjectIdGetDatum(conoid));
12234 : :
12235 : 507 : scan = systable_beginscan(trigrel, TriggerConstraintIndexId, true,
12236 : : NULL, 1, &key);
12237 [ + - ]: 1607 : while ((trigtup = systable_getnext(scan)) != NULL)
12238 : : {
12239 : 1607 : Form_pg_trigger trgform = (Form_pg_trigger) GETSTRUCT(trigtup);
12240 : :
12241 [ + + ]: 1607 : if (trgform->tgconstrrelid != confrelid)
12242 : 521 : continue;
12243 [ - + ]: 1086 : if (trgform->tgrelid != conrelid)
12244 : 0 : continue;
12245 : : /* Only ever look at "check" triggers on the FK side. */
12246 [ + + ]: 1086 : if (RI_FKey_trigger_type(trgform->tgfoid) != RI_TRIGGER_FK)
12247 : 72 : continue;
12248 [ + + ]: 1014 : if (TRIGGER_FOR_INSERT(trgform->tgtype))
12249 : : {
12250 : : Assert(*insertTriggerOid == InvalidOid);
12251 : 507 : *insertTriggerOid = trgform->oid;
12252 : : }
12253 [ + - ]: 507 : else if (TRIGGER_FOR_UPDATE(trgform->tgtype))
12254 : : {
12255 : : Assert(*updateTriggerOid == InvalidOid);
12256 : 507 : *updateTriggerOid = trgform->oid;
12257 : : }
12258 : : #ifndef USE_ASSERT_CHECKING
12259 : : /* In an assert-enabled build, continue looking to find duplicates. */
12260 [ + + + + ]: 1014 : if (OidIsValid(*insertTriggerOid) && OidIsValid(*updateTriggerOid))
12261 : 507 : break;
12262 : : #endif
12263 : : }
12264 : :
12265 [ - + ]: 507 : if (!OidIsValid(*insertTriggerOid))
12266 [ # # ]: 0 : elog(ERROR, "could not find ON INSERT check triggers of foreign key constraint %u",
12267 : : conoid);
12268 [ - + ]: 507 : if (!OidIsValid(*updateTriggerOid))
12269 [ # # ]: 0 : elog(ERROR, "could not find ON UPDATE check triggers of foreign key constraint %u",
12270 : : conoid);
12271 : :
12272 : 507 : systable_endscan(scan);
12273 : 507 : }
12274 : :
12275 : : /*
12276 : : * ALTER TABLE ALTER CONSTRAINT
12277 : : *
12278 : : * Update the attributes of a constraint.
12279 : : *
12280 : : * Currently works for Foreign Key, Check, and not null constraints.
12281 : : *
12282 : : * If the constraint is modified, returns its address; otherwise, return
12283 : : * InvalidObjectAddress.
12284 : : */
12285 : : static ObjectAddress
12286 : 332 : ATExecAlterConstraint(List **wqueue, Relation rel, ATAlterConstraint *cmdcon,
12287 : : bool recurse, LOCKMODE lockmode)
12288 : : {
12289 : : Relation conrel;
12290 : : Relation tgrel;
12291 : : SysScanDesc scan;
12292 : : ScanKeyData skey[3];
12293 : : HeapTuple contuple;
12294 : : Form_pg_constraint currcon;
12295 : : ObjectAddress address;
12296 : :
12297 : : /*
12298 : : * Disallow altering ONLY a partitioned table, as it would make no sense.
12299 : : * This is okay for legacy inheritance.
12300 : : */
12301 [ + + - + ]: 332 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE && !recurse)
12302 [ # # ]: 0 : ereport(ERROR,
12303 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
12304 : : errmsg("constraint must be altered in child tables too"),
12305 : : errhint("Do not specify the ONLY keyword."));
12306 : :
12307 : :
12308 : 332 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
12309 : 332 : tgrel = table_open(TriggerRelationId, RowExclusiveLock);
12310 : :
12311 : : /*
12312 : : * Find and check the target constraint
12313 : : */
12314 : 332 : ScanKeyInit(&skey[0],
12315 : : Anum_pg_constraint_conrelid,
12316 : : BTEqualStrategyNumber, F_OIDEQ,
12317 : : ObjectIdGetDatum(RelationGetRelid(rel)));
12318 : 332 : ScanKeyInit(&skey[1],
12319 : : Anum_pg_constraint_contypid,
12320 : : BTEqualStrategyNumber, F_OIDEQ,
12321 : : ObjectIdGetDatum(InvalidOid));
12322 : 332 : ScanKeyInit(&skey[2],
12323 : : Anum_pg_constraint_conname,
12324 : : BTEqualStrategyNumber, F_NAMEEQ,
12325 : 332 : CStringGetDatum(cmdcon->conname));
12326 : 332 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
12327 : : true, NULL, 3, skey);
12328 : :
12329 : : /* There can be at most one matching row */
12330 [ + + ]: 332 : if (!HeapTupleIsValid(contuple = systable_getnext(scan)))
12331 [ + - ]: 4 : ereport(ERROR,
12332 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
12333 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
12334 : : cmdcon->conname, RelationGetRelationName(rel))));
12335 : :
12336 : 328 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12337 [ + + - + ]: 328 : if (cmdcon->alterDeferrability && currcon->contype != CONSTRAINT_FOREIGN)
12338 [ # # ]: 0 : ereport(ERROR,
12339 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12340 : : errmsg("constraint \"%s\" of relation \"%s\" is not a foreign key constraint",
12341 : : cmdcon->conname, RelationGetRelationName(rel))));
12342 [ + + ]: 328 : if (cmdcon->alterEnforceability &&
12343 [ + + + + ]: 192 : (currcon->contype != CONSTRAINT_FOREIGN && currcon->contype != CONSTRAINT_CHECK))
12344 [ + - ]: 8 : ereport(ERROR,
12345 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12346 : : errmsg("cannot alter enforceability of constraint \"%s\" of relation \"%s\"",
12347 : : cmdcon->conname, RelationGetRelationName(rel)),
12348 : : errhint("Only foreign key and check constraints can change enforceability.")));
12349 [ + + ]: 320 : if (cmdcon->alterInheritability &&
12350 [ + + ]: 64 : currcon->contype != CONSTRAINT_NOTNULL)
12351 [ + - ]: 16 : ereport(ERROR,
12352 : : errcode(ERRCODE_WRONG_OBJECT_TYPE),
12353 : : errmsg("constraint \"%s\" of relation \"%s\" is not a not-null constraint",
12354 : : cmdcon->conname, RelationGetRelationName(rel)));
12355 [ + + ]: 304 : if (cmdcon->alterInheritability &&
12356 [ + + + + ]: 48 : cmdcon->noinherit && rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
12357 [ + - ]: 4 : ereport(ERROR,
12358 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
12359 : : errmsg("not-null constraint \"%s\" on partitioned table \"%s\" cannot be NO INHERIT",
12360 : : cmdcon->conname, RelationGetRelationName(rel)));
12361 : :
12362 : : /* Refuse to modify inheritability of inherited constraints */
12363 [ + + ]: 300 : if (cmdcon->alterInheritability &&
12364 [ + + + + ]: 44 : cmdcon->noinherit && currcon->coninhcount > 0)
12365 [ + - ]: 4 : ereport(ERROR,
12366 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
12367 : : errmsg("cannot alter inherited constraint \"%s\" on relation \"%s\"",
12368 : : NameStr(currcon->conname),
12369 : : RelationGetRelationName(rel)));
12370 : :
12371 : : /*
12372 : : * If it's not the topmost constraint, raise an error.
12373 : : *
12374 : : * Altering a non-topmost constraint leaves some triggers untouched, since
12375 : : * they are not directly connected to this constraint; also, pg_dump would
12376 : : * ignore the deferrability status of the individual constraint, since it
12377 : : * only dumps topmost constraints. Avoid these problems by refusing this
12378 : : * operation and telling the user to alter the parent constraint instead.
12379 : : */
12380 [ + + ]: 296 : if (OidIsValid(currcon->conparentid))
12381 : : {
12382 : : HeapTuple tp;
12383 : 8 : Oid parent = currcon->conparentid;
12384 : 8 : char *ancestorname = NULL;
12385 : 8 : char *ancestortable = NULL;
12386 : :
12387 : : /* Loop to find the topmost constraint */
12388 [ + - ]: 16 : while (HeapTupleIsValid(tp = SearchSysCache1(CONSTROID, ObjectIdGetDatum(parent))))
12389 : : {
12390 : 16 : Form_pg_constraint contup = (Form_pg_constraint) GETSTRUCT(tp);
12391 : :
12392 : : /* If no parent, this is the constraint we want */
12393 [ + + ]: 16 : if (!OidIsValid(contup->conparentid))
12394 : : {
12395 : 8 : ancestorname = pstrdup(NameStr(contup->conname));
12396 : 8 : ancestortable = get_rel_name(contup->conrelid);
12397 : 8 : ReleaseSysCache(tp);
12398 : 8 : break;
12399 : : }
12400 : :
12401 : 8 : parent = contup->conparentid;
12402 : 8 : ReleaseSysCache(tp);
12403 : : }
12404 : :
12405 [ + - + - : 8 : ereport(ERROR,
+ - ]
12406 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
12407 : : errmsg("cannot alter constraint \"%s\" on relation \"%s\"",
12408 : : cmdcon->conname, RelationGetRelationName(rel)),
12409 : : ancestorname && ancestortable ?
12410 : : errdetail("Constraint \"%s\" is derived from constraint \"%s\" of relation \"%s\".",
12411 : : cmdcon->conname, ancestorname, ancestortable) : 0,
12412 : : errhint("You may alter the constraint it derives from instead.")));
12413 : : }
12414 : :
12415 : 288 : address = InvalidObjectAddress;
12416 : :
12417 : : /*
12418 : : * Do the actual catalog work, and recurse if necessary.
12419 : : */
12420 [ + + ]: 288 : if (ATExecAlterConstraintInternal(wqueue, cmdcon, conrel, tgrel, rel,
12421 : : contuple, recurse, lockmode))
12422 : 240 : ObjectAddressSet(address, ConstraintRelationId, currcon->oid);
12423 : :
12424 : 256 : systable_endscan(scan);
12425 : :
12426 : 256 : table_close(tgrel, RowExclusiveLock);
12427 : 256 : table_close(conrel, RowExclusiveLock);
12428 : :
12429 : 256 : return address;
12430 : : }
12431 : :
12432 : : /*
12433 : : * A subroutine of ATExecAlterConstraint that calls the respective routines for
12434 : : * altering constraint's enforceability, deferrability or inheritability.
12435 : : */
12436 : : static bool
12437 : 288 : ATExecAlterConstraintInternal(List **wqueue, ATAlterConstraint *cmdcon,
12438 : : Relation conrel, Relation tgrel, Relation rel,
12439 : : HeapTuple contuple, bool recurse,
12440 : : LOCKMODE lockmode)
12441 : : {
12442 : : Form_pg_constraint currcon;
12443 : 288 : bool changed = false;
12444 : 288 : List *otherrelids = NIL;
12445 : :
12446 : 288 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12447 : :
12448 : : /*
12449 : : * Do the catalog work for the enforceability or deferrability change,
12450 : : * recurse if necessary.
12451 : : *
12452 : : * Note that even if deferrability is requested to be altered along with
12453 : : * enforceability, we don't need to explicitly update multiple entries in
12454 : : * pg_trigger related to deferrability.
12455 : : *
12456 : : * Modifying foreign key enforceability involves either creating or
12457 : : * dropping the trigger, during which the deferrability setting will be
12458 : : * adjusted automatically.
12459 : : */
12460 [ + + ]: 288 : if (cmdcon->alterEnforceability)
12461 : : {
12462 [ + + ]: 184 : if (currcon->contype == CONSTRAINT_FOREIGN)
12463 : 56 : changed = ATExecAlterFKConstrEnforceability(wqueue, cmdcon, conrel, tgrel,
12464 : : currcon->conrelid,
12465 : : currcon->confrelid,
12466 : : contuple, lockmode,
12467 : : InvalidOid, InvalidOid,
12468 : : InvalidOid, InvalidOid);
12469 [ + - ]: 128 : else if (currcon->contype == CONSTRAINT_CHECK)
12470 : 128 : changed = ATExecAlterCheckConstrEnforceability(wqueue, cmdcon, conrel,
12471 : : contuple, recurse, false,
12472 : : NIL, lockmode);
12473 : : }
12474 [ + + + - ]: 168 : else if (cmdcon->alterDeferrability &&
12475 : 64 : ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, rel,
12476 : : contuple, recurse, &otherrelids,
12477 : : lockmode))
12478 : : {
12479 : : /*
12480 : : * AlterConstrUpdateConstraintEntry already invalidated relcache for
12481 : : * the relations having the constraint itself; here we also invalidate
12482 : : * for relations that have any triggers that are part of the
12483 : : * constraint.
12484 : : */
12485 [ + + + + : 204 : foreach_oid(relid, otherrelids)
+ + ]
12486 : 76 : CacheInvalidateRelcacheByRelid(relid);
12487 : :
12488 : 64 : changed = true;
12489 : : }
12490 : :
12491 : : /*
12492 : : * Do the catalog work for the inheritability change.
12493 : : */
12494 [ + + + - ]: 296 : if (cmdcon->alterInheritability &&
12495 : 40 : ATExecAlterConstrInheritability(wqueue, cmdcon, conrel, rel, contuple,
12496 : : lockmode))
12497 : 36 : changed = true;
12498 : :
12499 : 256 : return changed;
12500 : : }
12501 : :
12502 : : /*
12503 : : * Returns true if the foreign key constraint's enforceability is altered.
12504 : : *
12505 : : * Depending on whether the constraint is being set to ENFORCED or NOT
12506 : : * ENFORCED, it creates or drops the trigger accordingly.
12507 : : *
12508 : : * Note that we must recurse even when trying to change a constraint to not
12509 : : * enforced if it is already not enforced, in case descendant constraints
12510 : : * might be enforced and need to be changed to not enforced. Conversely, we
12511 : : * should do nothing if a constraint is being set to enforced and is already
12512 : : * enforced, as descendant constraints cannot be different in that case.
12513 : : */
12514 : : static bool
12515 : 120 : ATExecAlterFKConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
12516 : : Relation conrel, Relation tgrel,
12517 : : Oid fkrelid, Oid pkrelid,
12518 : : HeapTuple contuple, LOCKMODE lockmode,
12519 : : Oid ReferencedParentDelTrigger,
12520 : : Oid ReferencedParentUpdTrigger,
12521 : : Oid ReferencingParentInsTrigger,
12522 : : Oid ReferencingParentUpdTrigger)
12523 : : {
12524 : : Form_pg_constraint currcon;
12525 : : Oid conoid;
12526 : : Relation rel;
12527 : 120 : bool changed = false;
12528 : :
12529 : : /* Since this function recurses, it could be driven to stack overflow */
12530 : 120 : check_stack_depth();
12531 : :
12532 : : Assert(cmdcon->alterEnforceability);
12533 : :
12534 : 120 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12535 : 120 : conoid = currcon->oid;
12536 : :
12537 : : /* Should be foreign key constraint */
12538 : : Assert(currcon->contype == CONSTRAINT_FOREIGN);
12539 : :
12540 : 120 : rel = table_open(currcon->conrelid, lockmode);
12541 : :
12542 [ + + ]: 120 : if (currcon->conenforced != cmdcon->is_enforced)
12543 : : {
12544 : 116 : AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
12545 : 116 : changed = true;
12546 : : }
12547 : :
12548 : : /* Drop triggers */
12549 [ + + ]: 120 : if (!cmdcon->is_enforced)
12550 : : {
12551 : : /*
12552 : : * When setting a constraint to NOT ENFORCED, the constraint triggers
12553 : : * need to be dropped. Therefore, we must process the child relations
12554 : : * first, followed by the parent, to account for dependencies.
12555 : : */
12556 [ + + - + ]: 92 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
12557 : 40 : get_rel_relkind(currcon->confrelid) == RELKIND_PARTITIONED_TABLE)
12558 : 12 : AlterFKConstrEnforceabilityRecurse(wqueue, cmdcon, conrel, tgrel,
12559 : : fkrelid, pkrelid, contuple,
12560 : : lockmode, InvalidOid, InvalidOid,
12561 : : InvalidOid, InvalidOid);
12562 : :
12563 : : /* Drop all the triggers */
12564 : 52 : DropForeignKeyConstraintTriggers(tgrel, conoid, InvalidOid, InvalidOid);
12565 : : }
12566 [ + - ]: 68 : else if (changed) /* Create triggers */
12567 : : {
12568 : 68 : Oid ReferencedDelTriggerOid = InvalidOid,
12569 : 68 : ReferencedUpdTriggerOid = InvalidOid,
12570 : 68 : ReferencingInsTriggerOid = InvalidOid,
12571 : 68 : ReferencingUpdTriggerOid = InvalidOid;
12572 : :
12573 : : /* Prepare the minimal information required for trigger creation. */
12574 : 68 : Constraint *fkconstraint = makeNode(Constraint);
12575 : :
12576 : 68 : fkconstraint->conname = pstrdup(NameStr(currcon->conname));
12577 : 68 : fkconstraint->fk_matchtype = currcon->confmatchtype;
12578 : 68 : fkconstraint->fk_upd_action = currcon->confupdtype;
12579 : 68 : fkconstraint->fk_del_action = currcon->confdeltype;
12580 : 68 : fkconstraint->deferrable = currcon->condeferrable;
12581 : 68 : fkconstraint->initdeferred = currcon->condeferred;
12582 : :
12583 : : /* Create referenced triggers */
12584 [ + + ]: 68 : if (currcon->conrelid == fkrelid)
12585 : 40 : createForeignKeyActionTriggers(currcon->conrelid,
12586 : : currcon->confrelid,
12587 : : fkconstraint,
12588 : : conoid,
12589 : : currcon->conindid,
12590 : : ReferencedParentDelTrigger,
12591 : : ReferencedParentUpdTrigger,
12592 : : &ReferencedDelTriggerOid,
12593 : : &ReferencedUpdTriggerOid);
12594 : :
12595 : : /* Create referencing triggers */
12596 [ + + ]: 68 : if (currcon->confrelid == pkrelid)
12597 : 60 : createForeignKeyCheckTriggers(currcon->conrelid,
12598 : : pkrelid,
12599 : : fkconstraint,
12600 : : conoid,
12601 : : currcon->conindid,
12602 : : ReferencingParentInsTrigger,
12603 : : ReferencingParentUpdTrigger,
12604 : : &ReferencingInsTriggerOid,
12605 : : &ReferencingUpdTriggerOid);
12606 : :
12607 : : /*
12608 : : * Tell Phase 3 to check that the constraint is satisfied by existing
12609 : : * rows. Only applies to leaf partitions, and (for constraints that
12610 : : * reference a partitioned table) only if this is not one of the
12611 : : * pg_constraint rows that exist solely to support action triggers.
12612 : : */
12613 [ + + ]: 68 : if (rel->rd_rel->relkind == RELKIND_RELATION &&
12614 [ + + ]: 56 : currcon->confrelid == pkrelid)
12615 : : {
12616 : : AlteredTableInfo *tab;
12617 : : NewConstraint *newcon;
12618 : :
12619 : 48 : newcon = palloc0_object(NewConstraint);
12620 : 48 : newcon->name = fkconstraint->conname;
12621 : 48 : newcon->contype = CONSTR_FOREIGN;
12622 : 48 : newcon->refrelid = currcon->confrelid;
12623 : 48 : newcon->refindid = currcon->conindid;
12624 : 48 : newcon->conid = currcon->oid;
12625 : 48 : newcon->qual = (Node *) fkconstraint;
12626 : :
12627 : : /* Find or create work queue entry for this table */
12628 : 48 : tab = ATGetQueueEntry(wqueue, rel);
12629 : 48 : tab->constraints = lappend(tab->constraints, newcon);
12630 : : }
12631 : :
12632 : : /*
12633 : : * If the table at either end of the constraint is partitioned, we
12634 : : * need to recurse and create triggers for each constraint that is a
12635 : : * child of this one.
12636 : : */
12637 [ + + + + ]: 124 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
12638 : 56 : get_rel_relkind(currcon->confrelid) == RELKIND_PARTITIONED_TABLE)
12639 : 16 : AlterFKConstrEnforceabilityRecurse(wqueue, cmdcon, conrel, tgrel,
12640 : : fkrelid, pkrelid, contuple,
12641 : : lockmode,
12642 : : ReferencedDelTriggerOid,
12643 : : ReferencedUpdTriggerOid,
12644 : : ReferencingInsTriggerOid,
12645 : : ReferencingUpdTriggerOid);
12646 : : }
12647 : :
12648 : 120 : table_close(rel, NoLock);
12649 : :
12650 : 120 : return changed;
12651 : : }
12652 : :
12653 : : /*
12654 : : * Returns true if the CHECK constraint's enforceability is altered.
12655 : : */
12656 : : static bool
12657 : 336 : ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon,
12658 : : Relation conrel, HeapTuple contuple,
12659 : : bool recurse, bool recursing,
12660 : : List *changing_conids,
12661 : : LOCKMODE lockmode)
12662 : : {
12663 : : Form_pg_constraint currcon;
12664 : : Relation rel;
12665 : 336 : bool changed = false;
12666 : 336 : List *children = NIL;
12667 : 336 : bool target_enforced = cmdcon->is_enforced;
12668 : 336 : Oid enforced_parentoid = InvalidOid;
12669 : :
12670 : : /* Since this function recurses, it could be driven to stack overflow */
12671 : 336 : check_stack_depth();
12672 : :
12673 : : Assert(cmdcon->alterEnforceability);
12674 : :
12675 : 336 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12676 : :
12677 : : Assert(currcon->contype == CONSTRAINT_CHECK);
12678 : :
12679 : : /*
12680 : : * Parent relation already locked by caller, children will be locked by
12681 : : * find_all_inheritors. So NoLock is fine here.
12682 : : */
12683 : 336 : rel = table_open(currcon->conrelid, NoLock);
12684 : :
12685 : : /*
12686 : : * When setting a constraint to NOT ENFORCED, check whether any matching
12687 : : * parent constraint remains ENFORCED and is not part of this ALTER.
12688 : : *
12689 : : * For a direct ALTER of an inherited constraint, reject the command,
12690 : : * because the child cannot be weakened while its parent remains enforced.
12691 : : *
12692 : : * During recursion, another parent outside this ALTER may still enforce
12693 : : * the same constraint in a regular inheritance hierarchy. In that case,
12694 : : * keep the child constraint ENFORCED so that its merged enforceability
12695 : : * still reflects the remaining enforced parent. Partitions do not need
12696 : : * this recursive parent check because a partition can have only one
12697 : : * direct parent.
12698 : : */
12699 [ + + ]: 336 : if (!cmdcon->is_enforced &&
12700 [ + + + + : 304 : (!recursing || !rel->rd_rel->relispartition) &&
+ + ]
12701 : 144 : ATCheckCheckConstrHasEnforcedParent(conrel, rel, contuple,
12702 : : changing_conids,
12703 : : &enforced_parentoid))
12704 : : {
12705 [ + + ]: 32 : if (!recursing)
12706 [ + - ]: 20 : ereport(ERROR,
12707 : : errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
12708 : : errmsg("cannot mark inherited constraint \"%s\" as %s",
12709 : : NameStr(currcon->conname),
12710 : : "NOT ENFORCED"),
12711 : : errdetail("The matching constraint on parent table \"%s\" is %s.",
12712 : : get_rel_name(enforced_parentoid), "ENFORCED"));
12713 : :
12714 : 12 : target_enforced = true;
12715 : : }
12716 : :
12717 : : /*
12718 : : * Update to the merged enforceability if needed. This may differ from the
12719 : : * requested enforceability when another matching parent constraint
12720 : : * remains enforced.
12721 : : */
12722 [ + + ]: 316 : if (currcon->conenforced != target_enforced)
12723 : : {
12724 : 248 : ATAlterConstraint updatecon = *cmdcon;
12725 : :
12726 : 248 : updatecon.is_enforced = target_enforced;
12727 : 248 : AlterConstrUpdateConstraintEntry(&updatecon, conrel, contuple);
12728 : 248 : changed = true;
12729 : : }
12730 : :
12731 : : /*
12732 : : * Note that we must recurse even when trying to change a check constraint
12733 : : * to not enforced if it is already not enforced, in case descendant
12734 : : * constraints might be enforced and need to be changed to not enforced,
12735 : : * unless they still inherit an enforced constraint from another parent.
12736 : : * Conversely, we should do nothing if a constraint is being set to
12737 : : * enforced and is already enforced, as descendant constraints cannot be
12738 : : * different in that case.
12739 : : */
12740 [ + + + + ]: 316 : if (!cmdcon->is_enforced || changed)
12741 : : {
12742 : : /*
12743 : : * If we're recursing, the parent has already done this, so skip it.
12744 : : * Also, if the constraint is a NO INHERIT constraint, we shouldn't
12745 : : * try to look for it in the children.
12746 : : */
12747 [ + + + + ]: 300 : if (!recursing && !currcon->connoinherit)
12748 : : {
12749 : : Assert(changing_conids == NIL);
12750 : :
12751 : 104 : children = find_all_inheritors(RelationGetRelid(rel),
12752 : : lockmode, NULL);
12753 : :
12754 : : /*
12755 : : * When setting NOT ENFORCED, build the set of equivalent CHECK
12756 : : * constraints that this command will attempt to change before
12757 : : * visiting descendants. The root itself has already been checked
12758 : : * above.
12759 : : */
12760 [ + + ]: 104 : if (!cmdcon->is_enforced)
12761 : 48 : changing_conids = list_make1_oid(currcon->oid);
12762 : :
12763 [ + - + + : 512 : foreach_oid(childoid, children)
+ + ]
12764 : : {
12765 [ + + ]: 320 : if (childoid == RelationGetRelid(rel))
12766 : 104 : continue;
12767 : :
12768 : : /*
12769 : : * If we are told not to recurse, there had better not be any
12770 : : * child tables, because we can't change constraint
12771 : : * enforceability on the parent unless we have changed
12772 : : * enforceability for all child.
12773 : : */
12774 [ + + ]: 216 : if (!recurse)
12775 [ + - ]: 8 : ereport(ERROR,
12776 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
12777 : : errmsg("constraint must be altered on child tables too"),
12778 : : errhint("Do not specify the ONLY keyword."));
12779 : :
12780 : : /*
12781 : : * It is sufficient to look up the constraint by name here.
12782 : : * Supported DDL ensures that inheritable CHECK constraints
12783 : : * with the same name have equivalent definitions when they
12784 : : * are propagated to children or when inheritance is
12785 : : * established. All descendants returned by
12786 : : * find_all_inheritors must have this constraint: inherited
12787 : : * CHECK constraints propagate to all children at
12788 : : * inheritance-link creation time and cannot be dropped
12789 : : * independently on child tables.
12790 : : */
12791 [ + + ]: 208 : if (!cmdcon->is_enforced)
12792 : : changing_conids =
12793 : 92 : list_append_unique_oid(changing_conids,
12794 : : get_relation_constraint_oid(childoid,
12795 : 92 : cmdcon->conname,
12796 : : false));
12797 : : }
12798 : : }
12799 : :
12800 [ + + + + : 888 : foreach_oid(childoid, children)
+ + ]
12801 : : {
12802 [ + + ]: 304 : if (childoid == RelationGetRelid(rel))
12803 : 96 : continue;
12804 : :
12805 : 208 : AlterCheckConstrEnforceabilityRecurse(wqueue, cmdcon, conrel,
12806 : : childoid, false, true,
12807 : : changing_conids,
12808 : : lockmode);
12809 : : }
12810 : : }
12811 : :
12812 : : /*
12813 : : * Tell Phase 3 to check that the constraint is satisfied by existing
12814 : : * rows. We only need do this when altering the constraint from NOT
12815 : : * ENFORCED to ENFORCED.
12816 : : */
12817 [ + + ]: 308 : if (rel->rd_rel->relkind == RELKIND_RELATION &&
12818 [ + + + + ]: 260 : !currcon->conenforced &&
12819 : : target_enforced)
12820 : : {
12821 : : AlteredTableInfo *tab;
12822 : : NewConstraint *newcon;
12823 : : Datum val;
12824 : : char *conbin;
12825 : :
12826 : 116 : newcon = palloc0_object(NewConstraint);
12827 : 116 : newcon->name = pstrdup(NameStr(currcon->conname));
12828 : 116 : newcon->contype = CONSTR_CHECK;
12829 : :
12830 : 116 : val = SysCacheGetAttrNotNull(CONSTROID, contuple,
12831 : : Anum_pg_constraint_conbin);
12832 : 116 : conbin = TextDatumGetCString(val);
12833 : 116 : newcon->qual = expand_generated_columns_in_expr(stringToNode(conbin), rel, 1);
12834 : :
12835 : : /* Find or create work queue entry for this table */
12836 : 116 : tab = ATGetQueueEntry(wqueue, rel);
12837 : 116 : tab->constraints = lappend(tab->constraints, newcon);
12838 : : }
12839 : :
12840 : 308 : table_close(rel, NoLock);
12841 : :
12842 : 308 : return changed;
12843 : : }
12844 : :
12845 : : /*
12846 : : * Invokes ATExecAlterCheckConstrEnforceability for each CHECK constraint that
12847 : : * is a child of the specified constraint.
12848 : : *
12849 : : * We rely on the parent and child tables having identical CHECK constraint
12850 : : * names to retrieve the child's pg_constraint tuple.
12851 : : *
12852 : : * The arguments to this function have the same meaning as the arguments to
12853 : : * ATExecAlterCheckConstrEnforceability.
12854 : : */
12855 : : static void
12856 : 208 : AlterCheckConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
12857 : : Relation conrel, Oid conrelid,
12858 : : bool recurse, bool recursing,
12859 : : List *changing_conids,
12860 : : LOCKMODE lockmode)
12861 : : {
12862 : : SysScanDesc pscan;
12863 : : HeapTuple childtup;
12864 : : ScanKeyData skey[3];
12865 : :
12866 : 208 : ScanKeyInit(&skey[0],
12867 : : Anum_pg_constraint_conrelid,
12868 : : BTEqualStrategyNumber, F_OIDEQ,
12869 : : ObjectIdGetDatum(conrelid));
12870 : 208 : ScanKeyInit(&skey[1],
12871 : : Anum_pg_constraint_contypid,
12872 : : BTEqualStrategyNumber, F_OIDEQ,
12873 : : ObjectIdGetDatum(InvalidOid));
12874 : 208 : ScanKeyInit(&skey[2],
12875 : : Anum_pg_constraint_conname,
12876 : : BTEqualStrategyNumber, F_NAMEEQ,
12877 : 208 : CStringGetDatum(cmdcon->conname));
12878 : :
12879 : 208 : pscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId, true,
12880 : : NULL, 3, skey);
12881 : :
12882 [ - + ]: 208 : if (!HeapTupleIsValid(childtup = systable_getnext(pscan)))
12883 [ # # ]: 0 : ereport(ERROR,
12884 : : errcode(ERRCODE_UNDEFINED_OBJECT),
12885 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
12886 : : cmdcon->conname, get_rel_name(conrelid)));
12887 : :
12888 : 208 : ATExecAlterCheckConstrEnforceability(wqueue, cmdcon, conrel, childtup,
12889 : : recurse, recursing, changing_conids,
12890 : : lockmode);
12891 : :
12892 : 208 : systable_endscan(pscan);
12893 : 208 : }
12894 : :
12895 : : /*
12896 : : * When setting an inherited CHECK constraint to NOT ENFORCED, look for a
12897 : : * matching parent constraint that remains ENFORCED and is not part of the same
12898 : : * ALTER.
12899 : : */
12900 : : static bool
12901 : 268 : ATCheckCheckConstrHasEnforcedParent(Relation conrel, Relation rel,
12902 : : HeapTuple contuple,
12903 : : List *changing_conids,
12904 : : Oid *enforced_parentoid)
12905 : : {
12906 : : Form_pg_constraint currcon;
12907 : : Relation inhrel;
12908 : : SysScanDesc scan;
12909 : : ScanKeyData skey;
12910 : : HeapTuple inheritsTuple;
12911 : :
12912 : : /* Since this function recurses, it could be driven to stack overflow */
12913 : 268 : check_stack_depth();
12914 : :
12915 : 268 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
12916 : : Assert(currcon->contype == CONSTRAINT_CHECK);
12917 : :
12918 [ + + ]: 268 : if (currcon->coninhcount <= 0)
12919 : 124 : return false;
12920 : :
12921 : 144 : inhrel = table_open(InheritsRelationId, AccessShareLock);
12922 : :
12923 : 144 : ScanKeyInit(&skey,
12924 : : Anum_pg_inherits_inhrelid,
12925 : : BTEqualStrategyNumber, F_OIDEQ,
12926 : : ObjectIdGetDatum(RelationGetRelid(rel)));
12927 : 144 : scan = systable_beginscan(inhrel, InheritsRelidSeqnoIndexId,
12928 : : true, NULL, 1, &skey);
12929 : :
12930 [ + + ]: 304 : while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
12931 : : {
12932 : : Oid parentoid;
12933 : 200 : Relation parentrel = NULL;
12934 : : SysScanDesc pscan;
12935 : : ScanKeyData pkey[3];
12936 : : HeapTuple parenttup;
12937 : :
12938 : 200 : parentoid = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhparent;
12939 : :
12940 : 200 : ScanKeyInit(&pkey[0],
12941 : : Anum_pg_constraint_conrelid,
12942 : : BTEqualStrategyNumber, F_OIDEQ,
12943 : : ObjectIdGetDatum(parentoid));
12944 : 200 : ScanKeyInit(&pkey[1],
12945 : : Anum_pg_constraint_contypid,
12946 : : BTEqualStrategyNumber, F_OIDEQ,
12947 : : ObjectIdGetDatum(InvalidOid));
12948 : 200 : ScanKeyInit(&pkey[2],
12949 : : Anum_pg_constraint_conname,
12950 : : BTEqualStrategyNumber, F_NAMEEQ,
12951 : 200 : NameGetDatum(&currcon->conname));
12952 : :
12953 : 200 : pscan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
12954 : : true, NULL, 3, pkey);
12955 : :
12956 : : /*
12957 : : * ConstraintRelidTypidNameIndexId is unique on (conrelid, contypid,
12958 : : * conname), so this loop body executes at most once per parent.
12959 : : */
12960 [ + + ]: 360 : while (HeapTupleIsValid(parenttup = systable_getnext(pscan)))
12961 : : {
12962 : : Form_pg_constraint parentcon;
12963 : :
12964 : 200 : parentcon = (Form_pg_constraint) GETSTRUCT(parenttup);
12965 : :
12966 [ + - ]: 200 : if (parentcon->contype != CONSTRAINT_CHECK ||
12967 [ + - ]: 200 : parentcon->connoinherit ||
12968 [ + + ]: 200 : !parentcon->conenforced)
12969 : 44 : continue;
12970 : :
12971 [ - + ]: 156 : if (!constraints_equivalent(parenttup, contuple,
12972 : : RelationGetDescr(conrel)))
12973 [ # # ]: 0 : elog(ERROR, "child table \"%s\" has different definition for check constraint \"%s\"",
12974 : : RelationGetRelationName(rel),
12975 : : NameStr(parentcon->conname));
12976 : :
12977 : : /*
12978 : : * A parent listed in changing_conids is being changed by the same
12979 : : * ALTER, but it may not have been updated yet. For regular
12980 : : * inheritance, recurse upward to check whether an equivalent
12981 : : * enforced parent outside the ALTER will make it remain enforced.
12982 : : * Partitions cannot have multiple parents, so they do not need
12983 : : * this check.
12984 : : */
12985 [ + + + + ]: 300 : if (!rel->rd_rel->relispartition &&
12986 : 144 : list_member_oid(changing_conids, parentcon->oid))
12987 : : {
12988 : 124 : Oid parent_enforced_parentoid = InvalidOid;
12989 : :
12990 [ + - ]: 124 : if (parentrel == NULL)
12991 : 124 : parentrel = table_open(parentoid, NoLock);
12992 : :
12993 [ + + ]: 124 : if (!ATCheckCheckConstrHasEnforcedParent(conrel,
12994 : : parentrel,
12995 : : parenttup,
12996 : : changing_conids,
12997 : : &parent_enforced_parentoid))
12998 : 116 : continue;
12999 : : }
13000 : :
13001 : 40 : *enforced_parentoid = parentoid;
13002 [ + + ]: 40 : if (parentrel != NULL)
13003 : 8 : table_close(parentrel, NoLock);
13004 : 40 : systable_endscan(pscan);
13005 : 40 : systable_endscan(scan);
13006 : 40 : table_close(inhrel, AccessShareLock);
13007 : 40 : return true;
13008 : : }
13009 : :
13010 [ + + ]: 160 : if (parentrel != NULL)
13011 : 116 : table_close(parentrel, NoLock);
13012 : 160 : systable_endscan(pscan);
13013 : : }
13014 : :
13015 : 104 : systable_endscan(scan);
13016 : 104 : table_close(inhrel, AccessShareLock);
13017 : :
13018 : 104 : return false;
13019 : : }
13020 : :
13021 : : /*
13022 : : * Returns true if the constraint's deferrability is altered.
13023 : : *
13024 : : * *otherrelids is appended OIDs of relations containing affected triggers.
13025 : : *
13026 : : * Note that we must recurse even when the values are correct, in case
13027 : : * indirect descendants have had their constraints altered locally.
13028 : : * (This could be avoided if we forbade altering constraints in partitions
13029 : : * but existing releases don't do that.)
13030 : : */
13031 : : static bool
13032 : 108 : ATExecAlterConstrDeferrability(List **wqueue, ATAlterConstraint *cmdcon,
13033 : : Relation conrel, Relation tgrel, Relation rel,
13034 : : HeapTuple contuple, bool recurse,
13035 : : List **otherrelids, LOCKMODE lockmode)
13036 : : {
13037 : : Form_pg_constraint currcon;
13038 : : Oid refrelid;
13039 : 108 : bool changed = false;
13040 : :
13041 : : /* since this function recurses, it could be driven to stack overflow */
13042 : 108 : check_stack_depth();
13043 : :
13044 : : Assert(cmdcon->alterDeferrability);
13045 : :
13046 : 108 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13047 : 108 : refrelid = currcon->confrelid;
13048 : :
13049 : : /* Should be foreign key constraint */
13050 : : Assert(currcon->contype == CONSTRAINT_FOREIGN);
13051 : :
13052 : : /*
13053 : : * If called to modify a constraint that's already in the desired state,
13054 : : * silently do nothing.
13055 : : */
13056 [ + + ]: 108 : if (currcon->condeferrable != cmdcon->deferrable ||
13057 [ + - ]: 4 : currcon->condeferred != cmdcon->initdeferred)
13058 : : {
13059 : 108 : AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
13060 : 108 : changed = true;
13061 : :
13062 : : /*
13063 : : * Now we need to update the multiple entries in pg_trigger that
13064 : : * implement the constraint.
13065 : : */
13066 : 108 : AlterConstrTriggerDeferrability(currcon->oid, tgrel, rel,
13067 : 108 : cmdcon->deferrable,
13068 : 108 : cmdcon->initdeferred, otherrelids);
13069 : : }
13070 : :
13071 : : /*
13072 : : * If the table at either end of the constraint is partitioned, we need to
13073 : : * handle every constraint that is a child of this one.
13074 : : */
13075 [ + - + - ]: 108 : if (recurse && changed &&
13076 [ + + + + ]: 200 : (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
13077 : 92 : get_rel_relkind(refrelid) == RELKIND_PARTITIONED_TABLE))
13078 : 28 : AlterConstrDeferrabilityRecurse(wqueue, cmdcon, conrel, tgrel, rel,
13079 : : contuple, recurse, otherrelids,
13080 : : lockmode);
13081 : :
13082 : 108 : return changed;
13083 : : }
13084 : :
13085 : : /*
13086 : : * Returns true if the constraint's inheritability is altered.
13087 : : */
13088 : : static bool
13089 : 40 : ATExecAlterConstrInheritability(List **wqueue, ATAlterConstraint *cmdcon,
13090 : : Relation conrel, Relation rel,
13091 : : HeapTuple contuple, LOCKMODE lockmode)
13092 : : {
13093 : : Form_pg_constraint currcon;
13094 : : AttrNumber colNum;
13095 : : char *colName;
13096 : : List *children;
13097 : :
13098 : : Assert(cmdcon->alterInheritability);
13099 : :
13100 : 40 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13101 : :
13102 : : /* The current implementation only works for NOT NULL constraints */
13103 : : Assert(currcon->contype == CONSTRAINT_NOTNULL);
13104 : :
13105 : : /*
13106 : : * If called to modify a constraint that's already in the desired state,
13107 : : * silently do nothing.
13108 : : */
13109 [ - + ]: 40 : if (cmdcon->noinherit == currcon->connoinherit)
13110 : 0 : return false;
13111 : :
13112 : 40 : AlterConstrUpdateConstraintEntry(cmdcon, conrel, contuple);
13113 : 40 : CommandCounterIncrement();
13114 : :
13115 : : /* Fetch the column number and name */
13116 : 40 : colNum = extractNotNullColumn(contuple);
13117 : 40 : colName = get_attname(currcon->conrelid, colNum, false);
13118 : :
13119 : : /*
13120 : : * Propagate the change to children. For this subcommand type we don't
13121 : : * recursively affect children, just the immediate level.
13122 : : */
13123 : 40 : children = find_inheritance_children(RelationGetRelid(rel),
13124 : : lockmode);
13125 [ + + + + : 128 : foreach_oid(childoid, children)
+ + ]
13126 : : {
13127 : : ObjectAddress addr;
13128 : :
13129 [ + + ]: 56 : if (cmdcon->noinherit)
13130 : : {
13131 : : HeapTuple childtup;
13132 : : Form_pg_constraint childcon;
13133 : :
13134 : 20 : childtup = findNotNullConstraint(childoid, colName);
13135 [ - + ]: 20 : if (!childtup)
13136 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation %u",
13137 : : colName, childoid);
13138 : 20 : childcon = (Form_pg_constraint) GETSTRUCT(childtup);
13139 : : Assert(childcon->coninhcount > 0);
13140 : 20 : childcon->coninhcount--;
13141 : 20 : childcon->conislocal = true;
13142 : 20 : CatalogTupleUpdate(conrel, &childtup->t_self, childtup);
13143 : 20 : heap_freetuple(childtup);
13144 : : }
13145 : : else
13146 : : {
13147 : 36 : Relation childrel = table_open(childoid, NoLock);
13148 : :
13149 : 36 : addr = ATExecSetNotNull(wqueue, childrel, NameStr(currcon->conname),
13150 : : colName, true, true, lockmode);
13151 [ + - ]: 32 : if (OidIsValid(addr.objectId))
13152 : 32 : CommandCounterIncrement();
13153 : 32 : table_close(childrel, NoLock);
13154 : : }
13155 : : }
13156 : :
13157 : 36 : return true;
13158 : : }
13159 : :
13160 : : /*
13161 : : * A subroutine of ATExecAlterConstrDeferrability that updated constraint
13162 : : * trigger's deferrability.
13163 : : *
13164 : : * The arguments to this function have the same meaning as the arguments to
13165 : : * ATExecAlterConstrDeferrability.
13166 : : */
13167 : : static void
13168 : 108 : AlterConstrTriggerDeferrability(Oid conoid, Relation tgrel, Relation rel,
13169 : : bool deferrable, bool initdeferred,
13170 : : List **otherrelids)
13171 : : {
13172 : : HeapTuple tgtuple;
13173 : : ScanKeyData tgkey;
13174 : : SysScanDesc tgscan;
13175 : :
13176 : 108 : ScanKeyInit(&tgkey,
13177 : : Anum_pg_trigger_tgconstraint,
13178 : : BTEqualStrategyNumber, F_OIDEQ,
13179 : : ObjectIdGetDatum(conoid));
13180 : 108 : tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
13181 : : NULL, 1, &tgkey);
13182 [ + + ]: 420 : while (HeapTupleIsValid(tgtuple = systable_getnext(tgscan)))
13183 : : {
13184 : 312 : Form_pg_trigger tgform = (Form_pg_trigger) GETSTRUCT(tgtuple);
13185 : : Form_pg_trigger copy_tg;
13186 : : HeapTuple tgCopyTuple;
13187 : :
13188 : : /*
13189 : : * Remember OIDs of other relation(s) involved in FK constraint.
13190 : : * (Note: it's likely that we could skip forcing a relcache inval for
13191 : : * other rels that don't have a trigger whose properties change, but
13192 : : * let's be conservative.)
13193 : : */
13194 [ + + ]: 312 : if (tgform->tgrelid != RelationGetRelid(rel))
13195 : 152 : *otherrelids = list_append_unique_oid(*otherrelids,
13196 : : tgform->tgrelid);
13197 : :
13198 : : /*
13199 : : * Update enable status and deferrability of RI_FKey_noaction_del,
13200 : : * RI_FKey_noaction_upd, RI_FKey_check_ins and RI_FKey_check_upd
13201 : : * triggers, but not others; see createForeignKeyActionTriggers and
13202 : : * CreateFKCheckTrigger.
13203 : : */
13204 [ + + ]: 312 : if (tgform->tgfoid != F_RI_FKEY_NOACTION_DEL &&
13205 [ + + ]: 248 : tgform->tgfoid != F_RI_FKEY_NOACTION_UPD &&
13206 [ + + ]: 172 : tgform->tgfoid != F_RI_FKEY_CHECK_INS &&
13207 [ + + ]: 92 : tgform->tgfoid != F_RI_FKEY_CHECK_UPD)
13208 : 12 : continue;
13209 : :
13210 : 300 : tgCopyTuple = heap_copytuple(tgtuple);
13211 : 300 : copy_tg = (Form_pg_trigger) GETSTRUCT(tgCopyTuple);
13212 : :
13213 : 300 : copy_tg->tgdeferrable = deferrable;
13214 : 300 : copy_tg->tginitdeferred = initdeferred;
13215 : 300 : CatalogTupleUpdate(tgrel, &tgCopyTuple->t_self, tgCopyTuple);
13216 : :
13217 [ - + ]: 300 : InvokeObjectPostAlterHook(TriggerRelationId, tgform->oid, 0);
13218 : :
13219 : 300 : heap_freetuple(tgCopyTuple);
13220 : : }
13221 : :
13222 : 108 : systable_endscan(tgscan);
13223 : 108 : }
13224 : :
13225 : : /*
13226 : : * Invokes ATExecAlterFKConstrEnforceability for each foreign key constraint
13227 : : * that is a child of the specified constraint.
13228 : : *
13229 : : * Note that this doesn't handle recursion the normal way, viz. by scanning the
13230 : : * list of child relations and recursing; instead it uses the conparentid
13231 : : * relationships. This may need to be reconsidered.
13232 : : *
13233 : : * The arguments to this function have the same meaning as the arguments to
13234 : : * ATExecAlterFKConstrEnforceability.
13235 : : */
13236 : : static void
13237 : 28 : AlterFKConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
13238 : : Relation conrel, Relation tgrel,
13239 : : Oid fkrelid, Oid pkrelid,
13240 : : HeapTuple contuple, LOCKMODE lockmode,
13241 : : Oid ReferencedParentDelTrigger,
13242 : : Oid ReferencedParentUpdTrigger,
13243 : : Oid ReferencingParentInsTrigger,
13244 : : Oid ReferencingParentUpdTrigger)
13245 : : {
13246 : : Form_pg_constraint currcon;
13247 : : Oid conoid;
13248 : : ScanKeyData pkey;
13249 : : SysScanDesc pscan;
13250 : : HeapTuple childtup;
13251 : :
13252 : 28 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13253 : 28 : conoid = currcon->oid;
13254 : :
13255 : 28 : ScanKeyInit(&pkey,
13256 : : Anum_pg_constraint_conparentid,
13257 : : BTEqualStrategyNumber, F_OIDEQ,
13258 : : ObjectIdGetDatum(conoid));
13259 : :
13260 : 28 : pscan = systable_beginscan(conrel, ConstraintParentIndexId,
13261 : : true, NULL, 1, &pkey);
13262 : :
13263 [ + + ]: 92 : while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
13264 : 64 : ATExecAlterFKConstrEnforceability(wqueue, cmdcon, conrel, tgrel, fkrelid,
13265 : : pkrelid, childtup, lockmode,
13266 : : ReferencedParentDelTrigger,
13267 : : ReferencedParentUpdTrigger,
13268 : : ReferencingParentInsTrigger,
13269 : : ReferencingParentUpdTrigger);
13270 : :
13271 : 28 : systable_endscan(pscan);
13272 : 28 : }
13273 : :
13274 : : /*
13275 : : * Invokes ATExecAlterConstrDeferrability for each constraint that is a child of
13276 : : * the specified constraint.
13277 : : *
13278 : : * Note that this doesn't handle recursion the normal way, viz. by scanning the
13279 : : * list of child relations and recursing; instead it uses the conparentid
13280 : : * relationships. This may need to be reconsidered.
13281 : : *
13282 : : * The arguments to this function have the same meaning as the arguments to
13283 : : * ATExecAlterConstrDeferrability.
13284 : : */
13285 : : static void
13286 : 28 : AlterConstrDeferrabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon,
13287 : : Relation conrel, Relation tgrel, Relation rel,
13288 : : HeapTuple contuple, bool recurse,
13289 : : List **otherrelids, LOCKMODE lockmode)
13290 : : {
13291 : : Form_pg_constraint currcon;
13292 : : Oid conoid;
13293 : : ScanKeyData pkey;
13294 : : SysScanDesc pscan;
13295 : : HeapTuple childtup;
13296 : :
13297 : 28 : currcon = (Form_pg_constraint) GETSTRUCT(contuple);
13298 : 28 : conoid = currcon->oid;
13299 : :
13300 : 28 : ScanKeyInit(&pkey,
13301 : : Anum_pg_constraint_conparentid,
13302 : : BTEqualStrategyNumber, F_OIDEQ,
13303 : : ObjectIdGetDatum(conoid));
13304 : :
13305 : 28 : pscan = systable_beginscan(conrel, ConstraintParentIndexId,
13306 : : true, NULL, 1, &pkey);
13307 : :
13308 [ + + ]: 72 : while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
13309 : : {
13310 : 44 : Form_pg_constraint childcon = (Form_pg_constraint) GETSTRUCT(childtup);
13311 : : Relation childrel;
13312 : :
13313 : 44 : childrel = table_open(childcon->conrelid, lockmode);
13314 : :
13315 : 44 : ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, childrel,
13316 : : childtup, recurse, otherrelids, lockmode);
13317 : 44 : table_close(childrel, NoLock);
13318 : : }
13319 : :
13320 : 28 : systable_endscan(pscan);
13321 : 28 : }
13322 : :
13323 : : /*
13324 : : * Update the constraint entry for the given ATAlterConstraint command, and
13325 : : * invoke the appropriate hooks.
13326 : : */
13327 : : static void
13328 : 512 : AlterConstrUpdateConstraintEntry(ATAlterConstraint *cmdcon, Relation conrel,
13329 : : HeapTuple contuple)
13330 : : {
13331 : : HeapTuple copyTuple;
13332 : : Form_pg_constraint copy_con;
13333 : :
13334 : : Assert(cmdcon->alterEnforceability || cmdcon->alterDeferrability ||
13335 : : cmdcon->alterInheritability);
13336 : :
13337 : 512 : copyTuple = heap_copytuple(contuple);
13338 : 512 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13339 : :
13340 [ + + ]: 512 : if (cmdcon->alterEnforceability)
13341 : : {
13342 : 364 : copy_con->conenforced = cmdcon->is_enforced;
13343 : :
13344 : : /*
13345 : : * NB: The convalidated status is irrelevant when the constraint is
13346 : : * set to NOT ENFORCED, but for consistency, it should still be set
13347 : : * appropriately. Similarly, if the constraint is later changed to
13348 : : * ENFORCED, validation will be performed during phase 3, so it makes
13349 : : * sense to mark it as valid in that case.
13350 : : */
13351 : 364 : copy_con->convalidated = cmdcon->is_enforced;
13352 : : }
13353 [ + + ]: 512 : if (cmdcon->alterDeferrability)
13354 : : {
13355 : 112 : copy_con->condeferrable = cmdcon->deferrable;
13356 : 112 : copy_con->condeferred = cmdcon->initdeferred;
13357 : : }
13358 [ + + ]: 512 : if (cmdcon->alterInheritability)
13359 : 40 : copy_con->connoinherit = cmdcon->noinherit;
13360 : :
13361 : 512 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
13362 [ - + ]: 512 : InvokeObjectPostAlterHook(ConstraintRelationId, copy_con->oid, 0);
13363 : :
13364 : : /* Make new constraint flags visible to others */
13365 : 512 : CacheInvalidateRelcacheByRelid(copy_con->conrelid);
13366 : :
13367 : 512 : heap_freetuple(copyTuple);
13368 : 512 : }
13369 : :
13370 : : /*
13371 : : * ALTER TABLE VALIDATE CONSTRAINT
13372 : : *
13373 : : * XXX The reason we handle recursion here rather than at Phase 1 is because
13374 : : * there's no good way to skip recursing when handling foreign keys: there is
13375 : : * no need to lock children in that case, yet we wouldn't be able to avoid
13376 : : * doing so at that level.
13377 : : *
13378 : : * Return value is the address of the validated constraint. If the constraint
13379 : : * was already validated, InvalidObjectAddress is returned.
13380 : : */
13381 : : static ObjectAddress
13382 : 360 : ATExecValidateConstraint(List **wqueue, Relation rel, char *constrName,
13383 : : bool recurse, bool recursing, LOCKMODE lockmode)
13384 : : {
13385 : : Relation conrel;
13386 : : SysScanDesc scan;
13387 : : ScanKeyData skey[3];
13388 : : HeapTuple tuple;
13389 : : Form_pg_constraint con;
13390 : : ObjectAddress address;
13391 : :
13392 : 360 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
13393 : :
13394 : : /*
13395 : : * Find and check the target constraint
13396 : : */
13397 : 360 : ScanKeyInit(&skey[0],
13398 : : Anum_pg_constraint_conrelid,
13399 : : BTEqualStrategyNumber, F_OIDEQ,
13400 : : ObjectIdGetDatum(RelationGetRelid(rel)));
13401 : 360 : ScanKeyInit(&skey[1],
13402 : : Anum_pg_constraint_contypid,
13403 : : BTEqualStrategyNumber, F_OIDEQ,
13404 : : ObjectIdGetDatum(InvalidOid));
13405 : 360 : ScanKeyInit(&skey[2],
13406 : : Anum_pg_constraint_conname,
13407 : : BTEqualStrategyNumber, F_NAMEEQ,
13408 : : CStringGetDatum(constrName));
13409 : 360 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
13410 : : true, NULL, 3, skey);
13411 : :
13412 : : /* There can be at most one matching row */
13413 [ - + ]: 360 : if (!HeapTupleIsValid(tuple = systable_getnext(scan)))
13414 [ # # ]: 0 : ereport(ERROR,
13415 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
13416 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
13417 : : constrName, RelationGetRelationName(rel))));
13418 : :
13419 : 360 : con = (Form_pg_constraint) GETSTRUCT(tuple);
13420 [ + + ]: 360 : if (con->contype != CONSTRAINT_FOREIGN &&
13421 [ + + ]: 174 : con->contype != CONSTRAINT_CHECK &&
13422 [ - + ]: 78 : con->contype != CONSTRAINT_NOTNULL)
13423 [ # # ]: 0 : ereport(ERROR,
13424 : : errcode(ERRCODE_WRONG_OBJECT_TYPE),
13425 : : errmsg("cannot validate constraint \"%s\" of relation \"%s\"",
13426 : : constrName, RelationGetRelationName(rel)),
13427 : : errdetail("This operation is not supported for this type of constraint."));
13428 : :
13429 [ + + ]: 360 : if (!con->conenforced)
13430 [ + - ]: 4 : ereport(ERROR,
13431 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
13432 : : errmsg("cannot validate NOT ENFORCED constraint")));
13433 : :
13434 [ + + ]: 356 : if (!con->convalidated)
13435 : : {
13436 [ + + ]: 344 : if (con->contype == CONSTRAINT_FOREIGN)
13437 : : {
13438 : 182 : QueueFKConstraintValidation(wqueue, conrel, rel, con->confrelid,
13439 : : tuple, lockmode);
13440 : : }
13441 [ + + ]: 162 : else if (con->contype == CONSTRAINT_CHECK)
13442 : : {
13443 : 84 : QueueCheckConstraintValidation(wqueue, conrel, rel, constrName,
13444 : : tuple, recurse, recursing, lockmode);
13445 : : }
13446 [ + - ]: 78 : else if (con->contype == CONSTRAINT_NOTNULL)
13447 : : {
13448 : 78 : QueueNNConstraintValidation(wqueue, conrel, rel,
13449 : : tuple, recurse, recursing, lockmode);
13450 : : }
13451 : :
13452 : 344 : ObjectAddressSet(address, ConstraintRelationId, con->oid);
13453 : : }
13454 : : else
13455 : 12 : address = InvalidObjectAddress; /* already validated */
13456 : :
13457 : 356 : systable_endscan(scan);
13458 : :
13459 : 356 : table_close(conrel, RowExclusiveLock);
13460 : :
13461 : 356 : return address;
13462 : : }
13463 : :
13464 : : /*
13465 : : * QueueFKConstraintValidation
13466 : : *
13467 : : * Add an entry to the wqueue to validate the given foreign key constraint in
13468 : : * Phase 3 and update the convalidated field in the pg_constraint catalog
13469 : : * for the specified relation and all its children.
13470 : : */
13471 : : static void
13472 : 230 : QueueFKConstraintValidation(List **wqueue, Relation conrel, Relation fkrel,
13473 : : Oid pkrelid, HeapTuple contuple, LOCKMODE lockmode)
13474 : : {
13475 : : Form_pg_constraint con;
13476 : : AlteredTableInfo *tab;
13477 : : HeapTuple copyTuple;
13478 : : Form_pg_constraint copy_con;
13479 : :
13480 : : /* since this function recurses, it could be driven to stack overflow */
13481 : 230 : check_stack_depth();
13482 : :
13483 : 230 : con = (Form_pg_constraint) GETSTRUCT(contuple);
13484 : : Assert(con->contype == CONSTRAINT_FOREIGN);
13485 : : Assert(!con->convalidated);
13486 : :
13487 : : /*
13488 : : * Add the validation to phase 3's queue; not needed for partitioned
13489 : : * tables themselves, only for their partitions.
13490 : : *
13491 : : * When the referenced table (pkrelid) is partitioned, the referencing
13492 : : * table (fkrel) has one pg_constraint row pointing to each partition
13493 : : * thereof. These rows are there only to support action triggers and no
13494 : : * table scan is needed, therefore skip this for them as well.
13495 : : */
13496 [ + + ]: 230 : if (fkrel->rd_rel->relkind == RELKIND_RELATION &&
13497 [ + + ]: 198 : con->confrelid == pkrelid)
13498 : : {
13499 : : NewConstraint *newcon;
13500 : : Constraint *fkconstraint;
13501 : :
13502 : : /* Queue validation for phase 3 */
13503 : 190 : fkconstraint = makeNode(Constraint);
13504 : : /* for now this is all we need */
13505 : 190 : fkconstraint->conname = pstrdup(NameStr(con->conname));
13506 : :
13507 : 190 : newcon = palloc0_object(NewConstraint);
13508 : 190 : newcon->name = fkconstraint->conname;
13509 : 190 : newcon->contype = CONSTR_FOREIGN;
13510 : 190 : newcon->refrelid = con->confrelid;
13511 : 190 : newcon->refindid = con->conindid;
13512 : 190 : newcon->conid = con->oid;
13513 : 190 : newcon->qual = (Node *) fkconstraint;
13514 : :
13515 : : /* Find or create work queue entry for this table */
13516 : 190 : tab = ATGetQueueEntry(wqueue, fkrel);
13517 : 190 : tab->constraints = lappend(tab->constraints, newcon);
13518 : : }
13519 : :
13520 : : /*
13521 : : * If the table at either end of the constraint is partitioned, we need to
13522 : : * recurse and handle every unvalidated constraint that is a child of this
13523 : : * constraint.
13524 : : */
13525 [ + + + + ]: 428 : if (fkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
13526 : 198 : get_rel_relkind(con->confrelid) == RELKIND_PARTITIONED_TABLE)
13527 : : {
13528 : : ScanKeyData pkey;
13529 : : SysScanDesc pscan;
13530 : : HeapTuple childtup;
13531 : :
13532 : 48 : ScanKeyInit(&pkey,
13533 : : Anum_pg_constraint_conparentid,
13534 : : BTEqualStrategyNumber, F_OIDEQ,
13535 : : ObjectIdGetDatum(con->oid));
13536 : :
13537 : 48 : pscan = systable_beginscan(conrel, ConstraintParentIndexId,
13538 : : true, NULL, 1, &pkey);
13539 : :
13540 [ + + ]: 96 : while (HeapTupleIsValid(childtup = systable_getnext(pscan)))
13541 : : {
13542 : : Form_pg_constraint childcon;
13543 : : Relation childrel;
13544 : :
13545 : 48 : childcon = (Form_pg_constraint) GETSTRUCT(childtup);
13546 : :
13547 : : /*
13548 : : * If the child constraint has already been validated, no further
13549 : : * action is required for it or its descendants, as they are all
13550 : : * valid.
13551 : : */
13552 [ + + ]: 48 : if (childcon->convalidated)
13553 : 12 : continue;
13554 : :
13555 : 36 : childrel = table_open(childcon->conrelid, lockmode);
13556 : :
13557 : : /*
13558 : : * NB: Note that pkrelid should be passed as-is during recursion,
13559 : : * as it is required to identify the root referenced table.
13560 : : */
13561 : 36 : QueueFKConstraintValidation(wqueue, conrel, childrel, pkrelid,
13562 : : childtup, lockmode);
13563 : 36 : table_close(childrel, NoLock);
13564 : : }
13565 : :
13566 : 48 : systable_endscan(pscan);
13567 : : }
13568 : :
13569 : : /*
13570 : : * Now mark the pg_constraint row as validated (even if we didn't check,
13571 : : * notably the ones for partitions on the referenced side).
13572 : : *
13573 : : * We rely on transaction abort to roll back this change if phase 3
13574 : : * ultimately finds violating rows. This is a bit ugly.
13575 : : */
13576 : 230 : copyTuple = heap_copytuple(contuple);
13577 : 230 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13578 : 230 : copy_con->convalidated = true;
13579 : 230 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
13580 : :
13581 [ - + ]: 230 : InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
13582 : :
13583 : 230 : heap_freetuple(copyTuple);
13584 : 230 : }
13585 : :
13586 : : /*
13587 : : * QueueCheckConstraintValidation
13588 : : *
13589 : : * Add an entry to the wqueue to validate the given check constraint in Phase 3
13590 : : * and update the convalidated field in the pg_constraint catalog for the
13591 : : * specified relation and all its inheriting children.
13592 : : */
13593 : : static void
13594 : 84 : QueueCheckConstraintValidation(List **wqueue, Relation conrel, Relation rel,
13595 : : char *constrName, HeapTuple contuple,
13596 : : bool recurse, bool recursing, LOCKMODE lockmode)
13597 : : {
13598 : : Form_pg_constraint con;
13599 : : AlteredTableInfo *tab;
13600 : : HeapTuple copyTuple;
13601 : : Form_pg_constraint copy_con;
13602 : :
13603 : 84 : List *children = NIL;
13604 : : ListCell *child;
13605 : : NewConstraint *newcon;
13606 : : Datum val;
13607 : : char *conbin;
13608 : :
13609 : 84 : con = (Form_pg_constraint) GETSTRUCT(contuple);
13610 : : Assert(con->contype == CONSTRAINT_CHECK);
13611 : :
13612 : : /*
13613 : : * If we're recursing, the parent has already done this, so skip it. Also,
13614 : : * if the constraint is a NO INHERIT constraint, we shouldn't try to look
13615 : : * for it in the children.
13616 : : */
13617 [ + + + + ]: 84 : if (!recursing && !con->connoinherit)
13618 : 48 : children = find_all_inheritors(RelationGetRelid(rel),
13619 : : lockmode, NULL);
13620 : :
13621 : : /*
13622 : : * For CHECK constraints, we must ensure that we only mark the constraint
13623 : : * as validated on the parent if it's already validated on the children.
13624 : : *
13625 : : * We recurse before validating on the parent, to reduce risk of
13626 : : * deadlocks.
13627 : : */
13628 [ + + + + : 164 : foreach(child, children)
+ + ]
13629 : : {
13630 : 80 : Oid childoid = lfirst_oid(child);
13631 : : Relation childrel;
13632 : :
13633 [ + + ]: 80 : if (childoid == RelationGetRelid(rel))
13634 : 48 : continue;
13635 : :
13636 : : /*
13637 : : * If we are told not to recurse, there had better not be any child
13638 : : * tables, because we can't mark the constraint on the parent valid
13639 : : * unless it is valid for all child tables.
13640 : : */
13641 [ - + ]: 32 : if (!recurse)
13642 [ # # ]: 0 : ereport(ERROR,
13643 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
13644 : : errmsg("constraint must be validated on child tables too")));
13645 : :
13646 : : /* find_all_inheritors already got lock */
13647 : 32 : childrel = table_open(childoid, NoLock);
13648 : :
13649 : 32 : ATExecValidateConstraint(wqueue, childrel, constrName, false,
13650 : : true, lockmode);
13651 : 32 : table_close(childrel, NoLock);
13652 : : }
13653 : :
13654 : : /* Queue validation for phase 3 */
13655 : 84 : newcon = palloc0_object(NewConstraint);
13656 : 84 : newcon->name = constrName;
13657 : 84 : newcon->contype = CONSTR_CHECK;
13658 : 84 : newcon->refrelid = InvalidOid;
13659 : 84 : newcon->refindid = InvalidOid;
13660 : 84 : newcon->conid = con->oid;
13661 : :
13662 : 84 : val = SysCacheGetAttrNotNull(CONSTROID, contuple,
13663 : : Anum_pg_constraint_conbin);
13664 : 84 : conbin = TextDatumGetCString(val);
13665 : 84 : newcon->qual = expand_generated_columns_in_expr(stringToNode(conbin), rel, 1);
13666 : :
13667 : : /* Find or create work queue entry for this table */
13668 : 84 : tab = ATGetQueueEntry(wqueue, rel);
13669 : 84 : tab->constraints = lappend(tab->constraints, newcon);
13670 : :
13671 : : /*
13672 : : * Invalidate relcache so that others see the new validated constraint.
13673 : : */
13674 : 84 : CacheInvalidateRelcache(rel);
13675 : :
13676 : : /*
13677 : : * Now update the catalog, while we have the door open.
13678 : : */
13679 : 84 : copyTuple = heap_copytuple(contuple);
13680 : 84 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13681 : 84 : copy_con->convalidated = true;
13682 : 84 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
13683 : :
13684 [ - + ]: 84 : InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
13685 : :
13686 : 84 : heap_freetuple(copyTuple);
13687 : 84 : }
13688 : :
13689 : : /*
13690 : : * QueueNNConstraintValidation
13691 : : *
13692 : : * Add an entry to the wqueue to validate the given not-null constraint in
13693 : : * Phase 3 and update the convalidated field in the pg_constraint catalog for
13694 : : * the specified relation and all its inheriting children.
13695 : : */
13696 : : static void
13697 : 78 : QueueNNConstraintValidation(List **wqueue, Relation conrel, Relation rel,
13698 : : HeapTuple contuple, bool recurse, bool recursing,
13699 : : LOCKMODE lockmode)
13700 : : {
13701 : : Form_pg_constraint con;
13702 : : AlteredTableInfo *tab;
13703 : : HeapTuple copyTuple;
13704 : : Form_pg_constraint copy_con;
13705 : 78 : List *children = NIL;
13706 : : AttrNumber attnum;
13707 : : char *colname;
13708 : :
13709 : 78 : con = (Form_pg_constraint) GETSTRUCT(contuple);
13710 : : Assert(con->contype == CONSTRAINT_NOTNULL);
13711 : :
13712 : 78 : attnum = extractNotNullColumn(contuple);
13713 : :
13714 : : /*
13715 : : * If we're recursing, we've already done this for parent, so skip it.
13716 : : * Also, if the constraint is a NO INHERIT constraint, we shouldn't try to
13717 : : * look for it in the children.
13718 : : *
13719 : : * We recurse before validating on the parent, to reduce risk of
13720 : : * deadlocks.
13721 : : */
13722 [ + + + - ]: 78 : if (!recursing && !con->connoinherit)
13723 : 54 : children = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
13724 : :
13725 : 78 : colname = get_attname(RelationGetRelid(rel), attnum, false);
13726 [ + + + + : 262 : foreach_oid(childoid, children)
+ + ]
13727 : : {
13728 : : Relation childrel;
13729 : : HeapTuple contup;
13730 : : Form_pg_constraint childcon;
13731 : : char *conname;
13732 : :
13733 [ + + ]: 106 : if (childoid == RelationGetRelid(rel))
13734 : 54 : continue;
13735 : :
13736 : : /*
13737 : : * If we are told not to recurse, there had better not be any child
13738 : : * tables, because we can't mark the constraint on the parent valid
13739 : : * unless it is valid for all child tables.
13740 : : */
13741 [ - + ]: 52 : if (!recurse)
13742 [ # # ]: 0 : ereport(ERROR,
13743 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
13744 : : errmsg("constraint must be validated on child tables too"));
13745 : :
13746 : : /*
13747 : : * The column on child might have a different attnum, so search by
13748 : : * column name.
13749 : : */
13750 : 52 : contup = findNotNullConstraint(childoid, colname);
13751 [ - + ]: 52 : if (!contup)
13752 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
13753 : : colname, get_rel_name(childoid));
13754 : 52 : childcon = (Form_pg_constraint) GETSTRUCT(contup);
13755 [ + + ]: 52 : if (childcon->convalidated)
13756 : 28 : continue;
13757 : :
13758 : : /* find_all_inheritors already got lock */
13759 : 24 : childrel = table_open(childoid, NoLock);
13760 : 24 : conname = pstrdup(NameStr(childcon->conname));
13761 : :
13762 : : /* XXX improve ATExecValidateConstraint API to avoid double search */
13763 : 24 : ATExecValidateConstraint(wqueue, childrel, conname,
13764 : : false, true, lockmode);
13765 : 24 : table_close(childrel, NoLock);
13766 : : }
13767 : :
13768 : : /* Set attnotnull appropriately without queueing another validation */
13769 : 78 : set_attnotnull(NULL, rel, attnum, false);
13770 : :
13771 : 78 : tab = ATGetQueueEntry(wqueue, rel);
13772 : 78 : tab->verify_new_notnull = true;
13773 : :
13774 : : /*
13775 : : * Invalidate relcache so that others see the new validated constraint.
13776 : : */
13777 : 78 : CacheInvalidateRelcache(rel);
13778 : :
13779 : : /*
13780 : : * Now update the catalogs, while we have the door open.
13781 : : */
13782 : 78 : copyTuple = heap_copytuple(contuple);
13783 : 78 : copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
13784 : 78 : copy_con->convalidated = true;
13785 : 78 : CatalogTupleUpdate(conrel, ©Tuple->t_self, copyTuple);
13786 : :
13787 [ - + ]: 78 : InvokeObjectPostAlterHook(ConstraintRelationId, con->oid, 0);
13788 : :
13789 : 78 : heap_freetuple(copyTuple);
13790 : 78 : }
13791 : :
13792 : : /*
13793 : : * transformColumnNameList - transform list of column names
13794 : : *
13795 : : * Lookup each name and return its attnum and, optionally, type and collation
13796 : : * OIDs
13797 : : *
13798 : : * Note: the name of this function suggests that it's general-purpose,
13799 : : * but actually it's only used to look up names appearing in foreign-key
13800 : : * clauses. The error messages would need work to use it in other cases,
13801 : : * and perhaps the validity checks as well.
13802 : : */
13803 : : static int
13804 : 4653 : transformColumnNameList(Oid relId, List *colList,
13805 : : int16 *attnums, Oid *atttypids, Oid *attcollids)
13806 : : {
13807 : : ListCell *l;
13808 : : int attnum;
13809 : :
13810 : 4653 : attnum = 0;
13811 [ + + + + : 8469 : foreach(l, colList)
+ + ]
13812 : : {
13813 : 3860 : char *attname = strVal(lfirst(l));
13814 : : HeapTuple atttuple;
13815 : : Form_pg_attribute attform;
13816 : :
13817 : 3860 : atttuple = SearchSysCacheAttName(relId, attname);
13818 [ + + ]: 3860 : if (!HeapTupleIsValid(atttuple))
13819 [ + - ]: 36 : ereport(ERROR,
13820 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
13821 : : errmsg("column \"%s\" referenced in foreign key constraint does not exist",
13822 : : attname)));
13823 : 3824 : attform = (Form_pg_attribute) GETSTRUCT(atttuple);
13824 [ + + ]: 3824 : if (attform->attnum < 0)
13825 [ + - ]: 8 : ereport(ERROR,
13826 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
13827 : : errmsg("system columns cannot be used in foreign keys")));
13828 [ - + ]: 3816 : if (attnum >= INDEX_MAX_KEYS)
13829 [ # # ]: 0 : ereport(ERROR,
13830 : : (errcode(ERRCODE_TOO_MANY_COLUMNS),
13831 : : errmsg("cannot have more than %d keys in a foreign key",
13832 : : INDEX_MAX_KEYS)));
13833 : 3816 : attnums[attnum] = attform->attnum;
13834 [ + + ]: 3816 : if (atttypids != NULL)
13835 : 3792 : atttypids[attnum] = attform->atttypid;
13836 [ + + ]: 3816 : if (attcollids != NULL)
13837 : 3792 : attcollids[attnum] = attform->attcollation;
13838 : 3816 : ReleaseSysCache(atttuple);
13839 : 3816 : attnum++;
13840 : : }
13841 : :
13842 : 4609 : return attnum;
13843 : : }
13844 : :
13845 : : /*
13846 : : * transformFkeyGetPrimaryKey -
13847 : : *
13848 : : * Look up the names, attnums, types, and collations of the primary key attributes
13849 : : * for the pkrel. Also return the index OID and index opclasses of the
13850 : : * index supporting the primary key. Also return whether the index has
13851 : : * WITHOUT OVERLAPS.
13852 : : *
13853 : : * All parameters except pkrel are output parameters. Also, the function
13854 : : * return value is the number of attributes in the primary key.
13855 : : *
13856 : : * Used when the column list in the REFERENCES specification is omitted.
13857 : : */
13858 : : static int
13859 : 904 : transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid,
13860 : : List **attnamelist,
13861 : : int16 *attnums, Oid *atttypids, Oid *attcollids,
13862 : : Oid *opclasses, bool *pk_has_without_overlaps)
13863 : : {
13864 : : List *indexoidlist;
13865 : : ListCell *indexoidscan;
13866 : 904 : HeapTuple indexTuple = NULL;
13867 : 904 : Form_pg_index indexStruct = NULL;
13868 : : Datum indclassDatum;
13869 : : oidvector *indclass;
13870 : : int i;
13871 : :
13872 : : /*
13873 : : * Get the list of index OIDs for the table from the relcache, and look up
13874 : : * each one in the pg_index syscache until we find one marked primary key
13875 : : * (hopefully there isn't more than one such). Insist it's valid, too.
13876 : : */
13877 : 904 : *indexOid = InvalidOid;
13878 : :
13879 : 904 : indexoidlist = RelationGetIndexList(pkrel);
13880 : :
13881 [ + - + - : 908 : foreach(indexoidscan, indexoidlist)
+ - ]
13882 : : {
13883 : 908 : Oid indexoid = lfirst_oid(indexoidscan);
13884 : :
13885 : 908 : indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
13886 [ - + ]: 908 : if (!HeapTupleIsValid(indexTuple))
13887 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", indexoid);
13888 : 908 : indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
13889 [ + + + - ]: 908 : if (indexStruct->indisprimary && indexStruct->indisvalid)
13890 : : {
13891 : : /*
13892 : : * Refuse to use a deferrable primary key. This is per SQL spec,
13893 : : * and there would be a lot of interesting semantic problems if we
13894 : : * tried to allow it.
13895 : : */
13896 [ - + ]: 904 : if (!indexStruct->indimmediate)
13897 [ # # ]: 0 : ereport(ERROR,
13898 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
13899 : : errmsg("cannot use a deferrable primary key for referenced table \"%s\"",
13900 : : RelationGetRelationName(pkrel))));
13901 : :
13902 : 904 : *indexOid = indexoid;
13903 : 904 : break;
13904 : : }
13905 : 4 : ReleaseSysCache(indexTuple);
13906 : : }
13907 : :
13908 : 904 : list_free(indexoidlist);
13909 : :
13910 : : /*
13911 : : * Check that we found it
13912 : : */
13913 [ - + ]: 904 : if (!OidIsValid(*indexOid))
13914 [ # # ]: 0 : ereport(ERROR,
13915 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
13916 : : errmsg("there is no primary key for referenced table \"%s\"",
13917 : : RelationGetRelationName(pkrel))));
13918 : :
13919 : : /* Must get indclass the hard way */
13920 : 904 : indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
13921 : : Anum_pg_index_indclass);
13922 : 904 : indclass = (oidvector *) DatumGetPointer(indclassDatum);
13923 : :
13924 : : /*
13925 : : * Now build the list of PK attributes from the indkey definition (we
13926 : : * assume a primary key cannot have expressional elements)
13927 : : */
13928 : 904 : *attnamelist = NIL;
13929 [ + + ]: 2124 : for (i = 0; i < indexStruct->indnkeyatts; i++)
13930 : : {
13931 : 1220 : int pkattno = indexStruct->indkey.values[i];
13932 : :
13933 : 1220 : attnums[i] = pkattno;
13934 : 1220 : atttypids[i] = attnumTypeId(pkrel, pkattno);
13935 : 1220 : attcollids[i] = attnumCollationId(pkrel, pkattno);
13936 : 1220 : opclasses[i] = indclass->values[i];
13937 : 1220 : *attnamelist = lappend(*attnamelist,
13938 : 1220 : makeString(pstrdup(NameStr(*attnumAttName(pkrel, pkattno)))));
13939 : : }
13940 : :
13941 : 904 : *pk_has_without_overlaps = indexStruct->indisexclusion;
13942 : :
13943 : 904 : ReleaseSysCache(indexTuple);
13944 : :
13945 : 904 : return i;
13946 : : }
13947 : :
13948 : : /*
13949 : : * transformFkeyCheckAttrs -
13950 : : *
13951 : : * Validate that the 'attnums' columns in the 'pkrel' relation are valid to
13952 : : * reference as part of a foreign key constraint.
13953 : : *
13954 : : * Returns the OID of the unique index supporting the constraint and
13955 : : * populates the caller-provided 'opclasses' array with the opclasses
13956 : : * associated with the index columns. Also sets whether the index
13957 : : * uses WITHOUT OVERLAPS.
13958 : : *
13959 : : * Raises an ERROR on validation failure.
13960 : : */
13961 : : static Oid
13962 : 895 : transformFkeyCheckAttrs(Relation pkrel,
13963 : : int numattrs, int16 *attnums,
13964 : : bool with_period, Oid *opclasses,
13965 : : bool *pk_has_without_overlaps)
13966 : : {
13967 : 895 : Oid indexoid = InvalidOid;
13968 : 895 : bool found = false;
13969 : 895 : bool found_deferrable = false;
13970 : : List *indexoidlist;
13971 : : ListCell *indexoidscan;
13972 : : int i,
13973 : : j;
13974 : :
13975 : : /*
13976 : : * Reject duplicate appearances of columns in the referenced-columns list.
13977 : : * Such a case is forbidden by the SQL standard, and even if we thought it
13978 : : * useful to allow it, there would be ambiguity about how to match the
13979 : : * list to unique indexes (in particular, it'd be unclear which index
13980 : : * opclass goes with which FK column).
13981 : : */
13982 [ + + ]: 2095 : for (i = 0; i < numattrs; i++)
13983 : : {
13984 [ + + ]: 1587 : for (j = i + 1; j < numattrs; j++)
13985 : : {
13986 [ + + ]: 387 : if (attnums[i] == attnums[j])
13987 [ + - ]: 16 : ereport(ERROR,
13988 : : (errcode(ERRCODE_INVALID_FOREIGN_KEY),
13989 : : errmsg("foreign key referenced-columns list must not contain duplicates")));
13990 : : }
13991 : : }
13992 : :
13993 : : /*
13994 : : * Get the list of index OIDs for the table from the relcache, and look up
13995 : : * each one in the pg_index syscache, and match unique indexes to the list
13996 : : * of attnums we are given.
13997 : : */
13998 : 879 : indexoidlist = RelationGetIndexList(pkrel);
13999 : :
14000 [ + - + + : 998 : foreach(indexoidscan, indexoidlist)
+ + ]
14001 : : {
14002 : : HeapTuple indexTuple;
14003 : : Form_pg_index indexStruct;
14004 : :
14005 : 990 : indexoid = lfirst_oid(indexoidscan);
14006 : 990 : indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
14007 [ - + ]: 990 : if (!HeapTupleIsValid(indexTuple))
14008 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", indexoid);
14009 : 990 : indexStruct = (Form_pg_index) GETSTRUCT(indexTuple);
14010 : :
14011 : : /*
14012 : : * Must have the right number of columns; must be unique (or if
14013 : : * temporal then exclusion instead) and not a partial index; forget it
14014 : : * if there are any expressions, too. Invalid indexes are out as well.
14015 : : */
14016 [ + + + + : 990 : if (indexStruct->indnkeyatts == numattrs &&
+ + ]
14017 : 909 : (with_period ? indexStruct->indisexclusion : indexStruct->indisunique) &&
14018 [ + - + - ]: 1818 : indexStruct->indisvalid &&
14019 [ + - ]: 1818 : heap_attisnull(indexTuple, Anum_pg_index_indpred, NULL) &&
14020 : 909 : heap_attisnull(indexTuple, Anum_pg_index_indexprs, NULL))
14021 : : {
14022 : : Datum indclassDatum;
14023 : : oidvector *indclass;
14024 : :
14025 : : /* Must get indclass the hard way */
14026 : 909 : indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
14027 : : Anum_pg_index_indclass);
14028 : 909 : indclass = (oidvector *) DatumGetPointer(indclassDatum);
14029 : :
14030 : : /*
14031 : : * The given attnum list may match the index columns in any order.
14032 : : * Check for a match, and extract the appropriate opclasses while
14033 : : * we're at it.
14034 : : *
14035 : : * We know that attnums[] is duplicate-free per the test at the
14036 : : * start of this function, and we checked above that the number of
14037 : : * index columns agrees, so if we find a match for each attnums[]
14038 : : * entry then we must have a one-to-one match in some order.
14039 : : */
14040 [ + + ]: 2101 : for (i = 0; i < numattrs; i++)
14041 : : {
14042 : 1230 : found = false;
14043 [ + + ]: 1639 : for (j = 0; j < numattrs; j++)
14044 : : {
14045 [ + + ]: 1601 : if (attnums[i] == indexStruct->indkey.values[j])
14046 : : {
14047 : 1192 : opclasses[i] = indclass->values[j];
14048 : 1192 : found = true;
14049 : 1192 : break;
14050 : : }
14051 : : }
14052 [ + + ]: 1230 : if (!found)
14053 : 38 : break;
14054 : : }
14055 : : /* The last attribute in the index must be the PERIOD FK part */
14056 [ + + + + ]: 909 : if (found && with_period)
14057 : : {
14058 : 80 : int16 periodattnum = attnums[numattrs - 1];
14059 : :
14060 : 80 : found = (periodattnum == indexStruct->indkey.values[numattrs - 1]);
14061 : : }
14062 : :
14063 : : /*
14064 : : * Refuse to use a deferrable unique/primary key. This is per SQL
14065 : : * spec, and there would be a lot of interesting semantic problems
14066 : : * if we tried to allow it.
14067 : : */
14068 [ + + - + ]: 909 : if (found && !indexStruct->indimmediate)
14069 : : {
14070 : : /*
14071 : : * Remember that we found an otherwise matching index, so that
14072 : : * we can generate a more appropriate error message.
14073 : : */
14074 : 0 : found_deferrable = true;
14075 : 0 : found = false;
14076 : : }
14077 : :
14078 : : /* We need to know whether the index has WITHOUT OVERLAPS */
14079 [ + + ]: 909 : if (found)
14080 : 871 : *pk_has_without_overlaps = indexStruct->indisexclusion;
14081 : : }
14082 : 990 : ReleaseSysCache(indexTuple);
14083 [ + + ]: 990 : if (found)
14084 : 871 : break;
14085 : : }
14086 : :
14087 [ + + ]: 879 : if (!found)
14088 : : {
14089 [ - + ]: 8 : if (found_deferrable)
14090 [ # # ]: 0 : ereport(ERROR,
14091 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
14092 : : errmsg("cannot use a deferrable unique constraint for referenced table \"%s\"",
14093 : : RelationGetRelationName(pkrel))));
14094 : : else
14095 [ + - ]: 8 : ereport(ERROR,
14096 : : (errcode(ERRCODE_INVALID_FOREIGN_KEY),
14097 : : errmsg("there is no unique constraint matching given keys for referenced table \"%s\"",
14098 : : RelationGetRelationName(pkrel))));
14099 : : }
14100 : :
14101 : 871 : list_free(indexoidlist);
14102 : :
14103 : 871 : return indexoid;
14104 : : }
14105 : :
14106 : : /*
14107 : : * findFkeyCast -
14108 : : *
14109 : : * Wrapper around find_coercion_pathway() for ATAddForeignKeyConstraint().
14110 : : * Caller has equal regard for binary coercibility and for an exact match.
14111 : : */
14112 : : static CoercionPathType
14113 : 8 : findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
14114 : : {
14115 : : CoercionPathType ret;
14116 : :
14117 [ + - ]: 8 : if (targetTypeId == sourceTypeId)
14118 : : {
14119 : 8 : ret = COERCION_PATH_RELABELTYPE;
14120 : 8 : *funcid = InvalidOid;
14121 : : }
14122 : : else
14123 : : {
14124 : 0 : ret = find_coercion_pathway(targetTypeId, sourceTypeId,
14125 : : COERCION_IMPLICIT, funcid);
14126 [ # # ]: 0 : if (ret == COERCION_PATH_NONE)
14127 : : /* A previously-relied-upon cast is now gone. */
14128 [ # # ]: 0 : elog(ERROR, "could not find cast from %u to %u",
14129 : : sourceTypeId, targetTypeId);
14130 : : }
14131 : :
14132 : 8 : return ret;
14133 : : }
14134 : :
14135 : : /*
14136 : : * Permissions checks on the referenced table for ADD FOREIGN KEY
14137 : : *
14138 : : * Note: we have already checked that the user owns the referencing table,
14139 : : * else we'd have failed much earlier; no additional checks are needed for it.
14140 : : */
14141 : : static void
14142 : 1751 : checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
14143 : : {
14144 : 1751 : Oid roleid = GetUserId();
14145 : : AclResult aclresult;
14146 : : int i;
14147 : :
14148 : : /* Okay if we have relation-level REFERENCES permission */
14149 : 1751 : aclresult = pg_class_aclcheck(RelationGetRelid(rel), roleid,
14150 : : ACL_REFERENCES);
14151 [ + - ]: 1751 : if (aclresult == ACLCHECK_OK)
14152 : 1751 : return;
14153 : : /* Else we must have REFERENCES on each column */
14154 [ # # ]: 0 : for (i = 0; i < natts; i++)
14155 : : {
14156 : 0 : aclresult = pg_attribute_aclcheck(RelationGetRelid(rel), attnums[i],
14157 : : roleid, ACL_REFERENCES);
14158 [ # # ]: 0 : if (aclresult != ACLCHECK_OK)
14159 : 0 : aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
14160 : 0 : RelationGetRelationName(rel));
14161 : : }
14162 : : }
14163 : :
14164 : : /*
14165 : : * Scan the existing rows in a table to verify they meet a proposed FK
14166 : : * constraint.
14167 : : *
14168 : : * Caller must have opened and locked both relations appropriately.
14169 : : */
14170 : : static void
14171 : 847 : validateForeignKeyConstraint(char *conname,
14172 : : Relation rel,
14173 : : Relation pkrel,
14174 : : Oid pkindOid,
14175 : : Oid constraintOid,
14176 : : bool hasperiod)
14177 : : {
14178 : : TupleTableSlot *slot;
14179 : : TableScanDesc scan;
14180 : 847 : Trigger trig = {0};
14181 : : Snapshot snapshot;
14182 : : MemoryContext oldcxt;
14183 : : MemoryContext perTupCxt;
14184 : :
14185 [ - + ]: 847 : ereport(DEBUG1,
14186 : : (errmsg_internal("validating foreign key constraint \"%s\"", conname)));
14187 : :
14188 : : /*
14189 : : * Build a trigger call structure; we'll need it either way.
14190 : : */
14191 : 847 : trig.tgoid = InvalidOid;
14192 : 847 : trig.tgname = conname;
14193 : 847 : trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
14194 : 847 : trig.tgisinternal = true;
14195 : 847 : trig.tgconstrrelid = RelationGetRelid(pkrel);
14196 : 847 : trig.tgconstrindid = pkindOid;
14197 : 847 : trig.tgconstraint = constraintOid;
14198 : 847 : trig.tgdeferrable = false;
14199 : 847 : trig.tginitdeferred = false;
14200 : : /* we needn't fill in remaining fields */
14201 : :
14202 : : /*
14203 : : * See if we can do it with a single LEFT JOIN query. A false result
14204 : : * indicates we must proceed with the fire-the-trigger method. We can't do
14205 : : * a LEFT JOIN for temporal FKs yet, but we can once we support temporal
14206 : : * left joins.
14207 : : */
14208 [ + + + + ]: 847 : if (!hasperiod && RI_Initial_Check(&trig, rel, pkrel))
14209 : 688 : return;
14210 : :
14211 : : /*
14212 : : * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
14213 : : * if that tuple had just been inserted. If any of those fail, it should
14214 : : * ereport(ERROR) and that's that.
14215 : : */
14216 : 108 : snapshot = RegisterSnapshot(GetLatestSnapshot());
14217 : 108 : slot = table_slot_create(rel, NULL);
14218 : 108 : scan = table_beginscan(rel, snapshot, 0, NULL,
14219 : : SO_NONE);
14220 : 108 : perTupCxt = AllocSetContextCreate(CurrentMemoryContext,
14221 : : "validateForeignKeyConstraint",
14222 : : ALLOCSET_SMALL_SIZES);
14223 : 108 : oldcxt = MemoryContextSwitchTo(perTupCxt);
14224 : :
14225 [ + + ]: 177 : while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
14226 : : {
14227 : 109 : LOCAL_FCINFO(fcinfo, 0);
14228 : 109 : TriggerData trigdata = {0};
14229 : :
14230 [ - + ]: 109 : CHECK_FOR_INTERRUPTS();
14231 : :
14232 : : /*
14233 : : * Make a call to the trigger function
14234 : : *
14235 : : * No parameters are passed, but we do set a context
14236 : : */
14237 [ + - + - : 545 : MemSet(fcinfo, 0, SizeForFunctionCallInfo(0));
+ - + - +
+ ]
14238 : :
14239 : : /*
14240 : : * We assume RI_FKey_check_ins won't look at flinfo...
14241 : : */
14242 : 109 : trigdata.type = T_TriggerData;
14243 : 109 : trigdata.tg_event = TRIGGER_EVENT_INSERT | TRIGGER_EVENT_ROW;
14244 : 109 : trigdata.tg_relation = rel;
14245 : 109 : trigdata.tg_trigtuple = ExecFetchSlotHeapTuple(slot, false, NULL);
14246 : 109 : trigdata.tg_trigslot = slot;
14247 : 109 : trigdata.tg_trigger = &trig;
14248 : :
14249 : 109 : fcinfo->context = (Node *) &trigdata;
14250 : :
14251 : 109 : RI_FKey_check_ins(fcinfo);
14252 : :
14253 : 69 : MemoryContextReset(perTupCxt);
14254 : : }
14255 : :
14256 : 68 : MemoryContextSwitchTo(oldcxt);
14257 : 68 : MemoryContextDelete(perTupCxt);
14258 : 68 : table_endscan(scan);
14259 : 68 : UnregisterSnapshot(snapshot);
14260 : 68 : ExecDropSingleTupleTableSlot(slot);
14261 : : }
14262 : :
14263 : : /*
14264 : : * CreateFKCheckTrigger
14265 : : * Creates the insert (on_insert=true) or update "check" trigger that
14266 : : * implements a given foreign key
14267 : : *
14268 : : * Returns the OID of the so created trigger.
14269 : : */
14270 : : static Oid
14271 : 4132 : CreateFKCheckTrigger(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
14272 : : Oid constraintOid, Oid indexOid, Oid parentTrigOid,
14273 : : bool on_insert)
14274 : : {
14275 : : ObjectAddress trigAddress;
14276 : : CreateTrigStmt *fk_trigger;
14277 : :
14278 : : /*
14279 : : * Note: for a self-referential FK (referencing and referenced tables are
14280 : : * the same), it is important that the ON UPDATE action fires before the
14281 : : * CHECK action, since both triggers will fire on the same row during an
14282 : : * UPDATE event; otherwise the CHECK trigger will be checking a non-final
14283 : : * state of the row. Triggers fire in name order, so we ensure this by
14284 : : * using names like "RI_ConstraintTrigger_a_NNNN" for the action triggers
14285 : : * and "RI_ConstraintTrigger_c_NNNN" for the check triggers.
14286 : : */
14287 : 4132 : fk_trigger = makeNode(CreateTrigStmt);
14288 : 4132 : fk_trigger->replace = false;
14289 : 4132 : fk_trigger->isconstraint = true;
14290 : 4132 : fk_trigger->trigname = "RI_ConstraintTrigger_c";
14291 : 4132 : fk_trigger->relation = NULL;
14292 : :
14293 : : /* Either ON INSERT or ON UPDATE */
14294 [ + + ]: 4132 : if (on_insert)
14295 : : {
14296 : 2066 : fk_trigger->funcname = SystemFuncName("RI_FKey_check_ins");
14297 : 2066 : fk_trigger->events = TRIGGER_TYPE_INSERT;
14298 : : }
14299 : : else
14300 : : {
14301 : 2066 : fk_trigger->funcname = SystemFuncName("RI_FKey_check_upd");
14302 : 2066 : fk_trigger->events = TRIGGER_TYPE_UPDATE;
14303 : : }
14304 : :
14305 : 4132 : fk_trigger->args = NIL;
14306 : 4132 : fk_trigger->row = true;
14307 : 4132 : fk_trigger->timing = TRIGGER_TYPE_AFTER;
14308 : 4132 : fk_trigger->columns = NIL;
14309 : 4132 : fk_trigger->whenClause = NULL;
14310 : 4132 : fk_trigger->transitionRels = NIL;
14311 : 4132 : fk_trigger->deferrable = fkconstraint->deferrable;
14312 : 4132 : fk_trigger->initdeferred = fkconstraint->initdeferred;
14313 : 4132 : fk_trigger->constrrel = NULL;
14314 : :
14315 : 4132 : trigAddress = CreateTrigger(fk_trigger, NULL, myRelOid, refRelOid,
14316 : : constraintOid, indexOid, InvalidOid,
14317 : : parentTrigOid, NULL, true, false);
14318 : :
14319 : : /* Make changes-so-far visible */
14320 : 4132 : CommandCounterIncrement();
14321 : :
14322 : 4132 : return trigAddress.objectId;
14323 : : }
14324 : :
14325 : : /*
14326 : : * createForeignKeyActionTriggers
14327 : : * Create the referenced-side "action" triggers that implement a foreign
14328 : : * key.
14329 : : *
14330 : : * Returns the OIDs of the so created triggers in *deleteTrigOid and
14331 : : * *updateTrigOid.
14332 : : */
14333 : : static void
14334 : 2345 : createForeignKeyActionTriggers(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint,
14335 : : Oid constraintOid, Oid indexOid,
14336 : : Oid parentDelTrigger, Oid parentUpdTrigger,
14337 : : Oid *deleteTrigOid, Oid *updateTrigOid)
14338 : : {
14339 : : CreateTrigStmt *fk_trigger;
14340 : : ObjectAddress trigAddress;
14341 : :
14342 : : /*
14343 : : * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
14344 : : * DELETE action on the referenced table.
14345 : : */
14346 : 2345 : fk_trigger = makeNode(CreateTrigStmt);
14347 : 2345 : fk_trigger->replace = false;
14348 : 2345 : fk_trigger->isconstraint = true;
14349 : 2345 : fk_trigger->trigname = "RI_ConstraintTrigger_a";
14350 : 2345 : fk_trigger->relation = NULL;
14351 : 2345 : fk_trigger->args = NIL;
14352 : 2345 : fk_trigger->row = true;
14353 : 2345 : fk_trigger->timing = TRIGGER_TYPE_AFTER;
14354 : 2345 : fk_trigger->events = TRIGGER_TYPE_DELETE;
14355 : 2345 : fk_trigger->columns = NIL;
14356 : 2345 : fk_trigger->whenClause = NULL;
14357 : 2345 : fk_trigger->transitionRels = NIL;
14358 : 2345 : fk_trigger->constrrel = NULL;
14359 : :
14360 [ + + + + : 2345 : switch (fkconstraint->fk_del_action)
+ - ]
14361 : : {
14362 : 1916 : case FKCONSTR_ACTION_NOACTION:
14363 : 1916 : fk_trigger->deferrable = fkconstraint->deferrable;
14364 : 1916 : fk_trigger->initdeferred = fkconstraint->initdeferred;
14365 : 1916 : fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_del");
14366 : 1916 : break;
14367 : 20 : case FKCONSTR_ACTION_RESTRICT:
14368 : 20 : fk_trigger->deferrable = false;
14369 : 20 : fk_trigger->initdeferred = false;
14370 : 20 : fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_del");
14371 : 20 : break;
14372 : 306 : case FKCONSTR_ACTION_CASCADE:
14373 : 306 : fk_trigger->deferrable = false;
14374 : 306 : fk_trigger->initdeferred = false;
14375 : 306 : fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_del");
14376 : 306 : break;
14377 : 63 : case FKCONSTR_ACTION_SETNULL:
14378 : 63 : fk_trigger->deferrable = false;
14379 : 63 : fk_trigger->initdeferred = false;
14380 : 63 : fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_del");
14381 : 63 : break;
14382 : 40 : case FKCONSTR_ACTION_SETDEFAULT:
14383 : 40 : fk_trigger->deferrable = false;
14384 : 40 : fk_trigger->initdeferred = false;
14385 : 40 : fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_del");
14386 : 40 : break;
14387 : 0 : default:
14388 [ # # ]: 0 : elog(ERROR, "unrecognized FK action type: %d",
14389 : : (int) fkconstraint->fk_del_action);
14390 : : break;
14391 : : }
14392 : :
14393 : 2345 : trigAddress = CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid,
14394 : : constraintOid, indexOid, InvalidOid,
14395 : : parentDelTrigger, NULL, true, false);
14396 [ + - ]: 2345 : if (deleteTrigOid)
14397 : 2345 : *deleteTrigOid = trigAddress.objectId;
14398 : :
14399 : : /* Make changes-so-far visible */
14400 : 2345 : CommandCounterIncrement();
14401 : :
14402 : : /*
14403 : : * Build and execute a CREATE CONSTRAINT TRIGGER statement for the ON
14404 : : * UPDATE action on the referenced table.
14405 : : */
14406 : 2345 : fk_trigger = makeNode(CreateTrigStmt);
14407 : 2345 : fk_trigger->replace = false;
14408 : 2345 : fk_trigger->isconstraint = true;
14409 : 2345 : fk_trigger->trigname = "RI_ConstraintTrigger_a";
14410 : 2345 : fk_trigger->relation = NULL;
14411 : 2345 : fk_trigger->args = NIL;
14412 : 2345 : fk_trigger->row = true;
14413 : 2345 : fk_trigger->timing = TRIGGER_TYPE_AFTER;
14414 : 2345 : fk_trigger->events = TRIGGER_TYPE_UPDATE;
14415 : 2345 : fk_trigger->columns = NIL;
14416 : 2345 : fk_trigger->whenClause = NULL;
14417 : 2345 : fk_trigger->transitionRels = NIL;
14418 : 2345 : fk_trigger->constrrel = NULL;
14419 : :
14420 [ + + + + : 2345 : switch (fkconstraint->fk_upd_action)
+ - ]
14421 : : {
14422 : 2041 : case FKCONSTR_ACTION_NOACTION:
14423 : 2041 : fk_trigger->deferrable = fkconstraint->deferrable;
14424 : 2041 : fk_trigger->initdeferred = fkconstraint->initdeferred;
14425 : 2041 : fk_trigger->funcname = SystemFuncName("RI_FKey_noaction_upd");
14426 : 2041 : break;
14427 : 24 : case FKCONSTR_ACTION_RESTRICT:
14428 : 24 : fk_trigger->deferrable = false;
14429 : 24 : fk_trigger->initdeferred = false;
14430 : 24 : fk_trigger->funcname = SystemFuncName("RI_FKey_restrict_upd");
14431 : 24 : break;
14432 : 211 : case FKCONSTR_ACTION_CASCADE:
14433 : 211 : fk_trigger->deferrable = false;
14434 : 211 : fk_trigger->initdeferred = false;
14435 : 211 : fk_trigger->funcname = SystemFuncName("RI_FKey_cascade_upd");
14436 : 211 : break;
14437 : 41 : case FKCONSTR_ACTION_SETNULL:
14438 : 41 : fk_trigger->deferrable = false;
14439 : 41 : fk_trigger->initdeferred = false;
14440 : 41 : fk_trigger->funcname = SystemFuncName("RI_FKey_setnull_upd");
14441 : 41 : break;
14442 : 28 : case FKCONSTR_ACTION_SETDEFAULT:
14443 : 28 : fk_trigger->deferrable = false;
14444 : 28 : fk_trigger->initdeferred = false;
14445 : 28 : fk_trigger->funcname = SystemFuncName("RI_FKey_setdefault_upd");
14446 : 28 : break;
14447 : 0 : default:
14448 [ # # ]: 0 : elog(ERROR, "unrecognized FK action type: %d",
14449 : : (int) fkconstraint->fk_upd_action);
14450 : : break;
14451 : : }
14452 : :
14453 : 2345 : trigAddress = CreateTrigger(fk_trigger, NULL, refRelOid, myRelOid,
14454 : : constraintOid, indexOid, InvalidOid,
14455 : : parentUpdTrigger, NULL, true, false);
14456 [ + - ]: 2345 : if (updateTrigOid)
14457 : 2345 : *updateTrigOid = trigAddress.objectId;
14458 : 2345 : }
14459 : :
14460 : : /*
14461 : : * createForeignKeyCheckTriggers
14462 : : * Create the referencing-side "check" triggers that implement a foreign
14463 : : * key.
14464 : : *
14465 : : * Returns the OIDs of the so created triggers in *insertTrigOid and
14466 : : * *updateTrigOid.
14467 : : */
14468 : : static void
14469 : 2066 : createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid,
14470 : : Constraint *fkconstraint, Oid constraintOid,
14471 : : Oid indexOid,
14472 : : Oid parentInsTrigger, Oid parentUpdTrigger,
14473 : : Oid *insertTrigOid, Oid *updateTrigOid)
14474 : : {
14475 : 2066 : *insertTrigOid = CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
14476 : : constraintOid, indexOid,
14477 : : parentInsTrigger, true);
14478 : 2066 : *updateTrigOid = CreateFKCheckTrigger(myRelOid, refRelOid, fkconstraint,
14479 : : constraintOid, indexOid,
14480 : : parentUpdTrigger, false);
14481 : 2066 : }
14482 : :
14483 : : /*
14484 : : * ALTER TABLE DROP CONSTRAINT
14485 : : *
14486 : : * Like DROP COLUMN, we can't use the normal ALTER TABLE recursion mechanism.
14487 : : */
14488 : : static void
14489 : 555 : ATExecDropConstraint(Relation rel, const char *constrName,
14490 : : DropBehavior behavior, bool recurse,
14491 : : bool missing_ok, LOCKMODE lockmode)
14492 : : {
14493 : : Relation conrel;
14494 : : SysScanDesc scan;
14495 : : ScanKeyData skey[3];
14496 : : HeapTuple tuple;
14497 : 555 : bool found = false;
14498 : :
14499 : 555 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
14500 : :
14501 : : /*
14502 : : * Find and drop the target constraint
14503 : : */
14504 : 555 : ScanKeyInit(&skey[0],
14505 : : Anum_pg_constraint_conrelid,
14506 : : BTEqualStrategyNumber, F_OIDEQ,
14507 : : ObjectIdGetDatum(RelationGetRelid(rel)));
14508 : 555 : ScanKeyInit(&skey[1],
14509 : : Anum_pg_constraint_contypid,
14510 : : BTEqualStrategyNumber, F_OIDEQ,
14511 : : ObjectIdGetDatum(InvalidOid));
14512 : 555 : ScanKeyInit(&skey[2],
14513 : : Anum_pg_constraint_conname,
14514 : : BTEqualStrategyNumber, F_NAMEEQ,
14515 : : CStringGetDatum(constrName));
14516 : 555 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
14517 : : true, NULL, 3, skey);
14518 : :
14519 : : /* There can be at most one matching row */
14520 [ + + ]: 555 : if (HeapTupleIsValid(tuple = systable_getnext(scan)))
14521 : : {
14522 : 531 : dropconstraint_internal(rel, tuple, behavior, recurse, false,
14523 : : missing_ok, lockmode);
14524 : 407 : found = true;
14525 : : }
14526 : :
14527 : 431 : systable_endscan(scan);
14528 : :
14529 [ + + ]: 431 : if (!found)
14530 : : {
14531 [ + + ]: 24 : if (!missing_ok)
14532 [ + - ]: 16 : ereport(ERROR,
14533 : : errcode(ERRCODE_UNDEFINED_OBJECT),
14534 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
14535 : : constrName, RelationGetRelationName(rel)));
14536 : : else
14537 [ + - ]: 8 : ereport(NOTICE,
14538 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist, skipping",
14539 : : constrName, RelationGetRelationName(rel)));
14540 : : }
14541 : :
14542 : 415 : table_close(conrel, RowExclusiveLock);
14543 : 415 : }
14544 : :
14545 : : /*
14546 : : * Remove a constraint, using its pg_constraint tuple
14547 : : *
14548 : : * Implementation for ALTER TABLE DROP CONSTRAINT and ALTER TABLE ALTER COLUMN
14549 : : * DROP NOT NULL.
14550 : : *
14551 : : * Returns the address of the constraint being removed.
14552 : : */
14553 : : static ObjectAddress
14554 : 835 : dropconstraint_internal(Relation rel, HeapTuple constraintTup, DropBehavior behavior,
14555 : : bool recurse, bool recursing, bool missing_ok,
14556 : : LOCKMODE lockmode)
14557 : : {
14558 : : Relation conrel;
14559 : : Form_pg_constraint con;
14560 : : ObjectAddress conobj;
14561 : : List *children;
14562 : 835 : bool is_no_inherit_constraint = false;
14563 : : char *constrName;
14564 : 835 : char *colname = NULL;
14565 : :
14566 : : /* Guard against stack overflow due to overly deep inheritance tree. */
14567 : 835 : check_stack_depth();
14568 : :
14569 : : /* At top level, permission check was done in ATPrepCmd, else do it */
14570 [ + + ]: 835 : if (recursing)
14571 : 159 : ATSimplePermissions(AT_DropConstraint, rel,
14572 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
14573 : :
14574 : 831 : conrel = table_open(ConstraintRelationId, RowExclusiveLock);
14575 : :
14576 : 831 : con = (Form_pg_constraint) GETSTRUCT(constraintTup);
14577 : 831 : constrName = NameStr(con->conname);
14578 : :
14579 : : /* Don't allow drop of inherited constraints */
14580 [ + + + + ]: 831 : if (con->coninhcount > 0 && !recursing)
14581 [ + - ]: 104 : ereport(ERROR,
14582 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14583 : : errmsg("cannot drop inherited constraint \"%s\" of relation \"%s\"",
14584 : : constrName, RelationGetRelationName(rel))));
14585 : :
14586 : : /*
14587 : : * Reset pg_constraint.attnotnull, if this is a not-null constraint.
14588 : : *
14589 : : * While doing that, we're in a good position to disallow dropping a not-
14590 : : * null constraint underneath a primary key, a replica identity index, or
14591 : : * a generated identity column.
14592 : : */
14593 [ + + ]: 727 : if (con->contype == CONSTRAINT_NOTNULL)
14594 : : {
14595 : 207 : Relation attrel = table_open(AttributeRelationId, RowExclusiveLock);
14596 : 207 : AttrNumber attnum = extractNotNullColumn(constraintTup);
14597 : : Bitmapset *pkattrs;
14598 : : Bitmapset *irattrs;
14599 : : HeapTuple atttup;
14600 : : Form_pg_attribute attForm;
14601 : :
14602 : : /* save column name for recursion step */
14603 : 207 : colname = get_attname(RelationGetRelid(rel), attnum, false);
14604 : :
14605 : : /*
14606 : : * Disallow if it's in the primary key. For partitioned tables we
14607 : : * cannot rely solely on RelationGetIndexAttrBitmap, because it'll
14608 : : * return NULL if the primary key is invalid; but we still need to
14609 : : * protect not-null constraints under such a constraint, so check the
14610 : : * slow way.
14611 : : */
14612 : 207 : pkattrs = RelationGetIndexAttrBitmap(rel, INDEX_ATTR_BITMAP_PRIMARY_KEY);
14613 : :
14614 [ + + ]: 207 : if (pkattrs == NULL &&
14615 [ + + ]: 187 : rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
14616 : : {
14617 : 12 : Oid pkindex = RelationGetPrimaryKeyIndex(rel, true);
14618 : :
14619 [ - + ]: 12 : if (OidIsValid(pkindex))
14620 : : {
14621 : 0 : Relation pk = relation_open(pkindex, AccessShareLock);
14622 : :
14623 : 0 : pkattrs = NULL;
14624 [ # # ]: 0 : for (int i = 0; i < pk->rd_index->indnkeyatts; i++)
14625 : 0 : pkattrs = bms_add_member(pkattrs, pk->rd_index->indkey.values[i]);
14626 : :
14627 : 0 : relation_close(pk, AccessShareLock);
14628 : : }
14629 : : }
14630 : :
14631 [ + + + + ]: 227 : if (pkattrs &&
14632 : 20 : bms_is_member(attnum - FirstLowInvalidHeapAttributeNumber, pkattrs))
14633 [ + - ]: 16 : ereport(ERROR,
14634 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14635 : : errmsg("column \"%s\" is in a primary key",
14636 : : get_attname(RelationGetRelid(rel), attnum, false)));
14637 : :
14638 : : /* Disallow if it's in the replica identity */
14639 : 191 : irattrs = RelationGetIndexAttrBitmap(rel, INDEX_ATTR_BITMAP_IDENTITY_KEY);
14640 [ + + ]: 191 : if (bms_is_member(attnum - FirstLowInvalidHeapAttributeNumber, irattrs))
14641 [ + - ]: 8 : ereport(ERROR,
14642 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14643 : : errmsg("column \"%s\" is in index used as replica identity",
14644 : : get_attname(RelationGetRelid(rel), attnum, false)));
14645 : :
14646 : : /* Disallow if it's a GENERATED AS IDENTITY column */
14647 : 183 : atttup = SearchSysCacheCopyAttNum(RelationGetRelid(rel), attnum);
14648 [ - + ]: 183 : if (!HeapTupleIsValid(atttup))
14649 [ # # ]: 0 : elog(ERROR, "cache lookup failed for attribute %d of relation %u",
14650 : : attnum, RelationGetRelid(rel));
14651 : 183 : attForm = (Form_pg_attribute) GETSTRUCT(atttup);
14652 [ - + ]: 183 : if (attForm->attidentity != '\0')
14653 [ # # ]: 0 : ereport(ERROR,
14654 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
14655 : : errmsg("column \"%s\" of relation \"%s\" is an identity column",
14656 : : get_attname(RelationGetRelid(rel), attnum,
14657 : : false),
14658 : : RelationGetRelationName(rel)));
14659 : :
14660 : : /* All good -- reset attnotnull if needed */
14661 [ + - ]: 183 : if (attForm->attnotnull)
14662 : : {
14663 : 183 : attForm->attnotnull = false;
14664 : 183 : CatalogTupleUpdate(attrel, &atttup->t_self, atttup);
14665 : : }
14666 : :
14667 : 183 : table_close(attrel, RowExclusiveLock);
14668 : : }
14669 : :
14670 : 703 : is_no_inherit_constraint = con->connoinherit;
14671 : :
14672 : : /*
14673 : : * If it's a foreign-key constraint, we'd better lock the referenced table
14674 : : * and check that that's not in use, just as we've already done for the
14675 : : * constrained table (else we might, eg, be dropping a trigger that has
14676 : : * unfired events). But we can/must skip that in the self-referential
14677 : : * case.
14678 : : */
14679 [ + + ]: 703 : if (con->contype == CONSTRAINT_FOREIGN &&
14680 [ + - ]: 112 : con->confrelid != RelationGetRelid(rel))
14681 : : {
14682 : : Relation frel;
14683 : :
14684 : : /* Must match lock taken by RemoveTriggerById: */
14685 : 112 : frel = table_open(con->confrelid, AccessExclusiveLock);
14686 : 112 : CheckAlterTableIsSafe(frel);
14687 : 108 : table_close(frel, NoLock);
14688 : : }
14689 : :
14690 : : /*
14691 : : * Perform the actual constraint deletion
14692 : : */
14693 : 699 : ObjectAddressSet(conobj, ConstraintRelationId, con->oid);
14694 : 699 : performDeletion(&conobj, behavior, 0);
14695 : :
14696 : : /*
14697 : : * For partitioned tables, non-CHECK, non-NOT-NULL inherited constraints
14698 : : * are dropped via the dependency mechanism, so we're done here.
14699 : : */
14700 [ + + ]: 675 : if (con->contype != CONSTRAINT_CHECK &&
14701 [ + + ]: 422 : con->contype != CONSTRAINT_NOTNULL &&
14702 [ + + ]: 239 : rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
14703 : : {
14704 : 52 : table_close(conrel, RowExclusiveLock);
14705 : 52 : return conobj;
14706 : : }
14707 : :
14708 : : /*
14709 : : * Propagate to children as appropriate. Unlike most other ALTER
14710 : : * routines, we have to do this one level of recursion at a time; we can't
14711 : : * use find_all_inheritors to do it in one pass.
14712 : : */
14713 [ + + ]: 623 : if (!is_no_inherit_constraint)
14714 : 428 : children = find_inheritance_children(RelationGetRelid(rel), lockmode);
14715 : : else
14716 : 195 : children = NIL;
14717 : :
14718 [ + + + + : 1521 : foreach_oid(childrelid, children)
+ + ]
14719 : : {
14720 : : Relation childrel;
14721 : : HeapTuple tuple;
14722 : : Form_pg_constraint childcon;
14723 : :
14724 : : /* find_inheritance_children already got lock */
14725 : 283 : childrel = table_open(childrelid, NoLock);
14726 : 283 : CheckAlterTableIsSafe(childrel);
14727 : :
14728 : : /*
14729 : : * We search for not-null constraints by column name, and others by
14730 : : * constraint name.
14731 : : */
14732 [ + + ]: 283 : if (con->contype == CONSTRAINT_NOTNULL)
14733 : : {
14734 : 98 : tuple = findNotNullConstraint(childrelid, colname);
14735 [ - + ]: 98 : if (!HeapTupleIsValid(tuple))
14736 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation %u",
14737 : : colname, RelationGetRelid(childrel));
14738 : : }
14739 : : else
14740 : : {
14741 : : SysScanDesc scan;
14742 : : ScanKeyData skey[3];
14743 : :
14744 : 185 : ScanKeyInit(&skey[0],
14745 : : Anum_pg_constraint_conrelid,
14746 : : BTEqualStrategyNumber, F_OIDEQ,
14747 : : ObjectIdGetDatum(childrelid));
14748 : 185 : ScanKeyInit(&skey[1],
14749 : : Anum_pg_constraint_contypid,
14750 : : BTEqualStrategyNumber, F_OIDEQ,
14751 : : ObjectIdGetDatum(InvalidOid));
14752 : 185 : ScanKeyInit(&skey[2],
14753 : : Anum_pg_constraint_conname,
14754 : : BTEqualStrategyNumber, F_NAMEEQ,
14755 : : CStringGetDatum(constrName));
14756 : 185 : scan = systable_beginscan(conrel, ConstraintRelidTypidNameIndexId,
14757 : : true, NULL, 3, skey);
14758 : : /* There can only be one, so no need to loop */
14759 : 185 : tuple = systable_getnext(scan);
14760 [ - + ]: 185 : if (!HeapTupleIsValid(tuple))
14761 [ # # ]: 0 : ereport(ERROR,
14762 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
14763 : : errmsg("constraint \"%s\" of relation \"%s\" does not exist",
14764 : : constrName,
14765 : : RelationGetRelationName(childrel))));
14766 : 185 : tuple = heap_copytuple(tuple);
14767 : 185 : systable_endscan(scan);
14768 : : }
14769 : :
14770 : 283 : childcon = (Form_pg_constraint) GETSTRUCT(tuple);
14771 : :
14772 : : /* Right now only CHECK and not-null constraints can be inherited */
14773 [ + + ]: 283 : if (childcon->contype != CONSTRAINT_CHECK &&
14774 [ - + ]: 98 : childcon->contype != CONSTRAINT_NOTNULL)
14775 [ # # ]: 0 : elog(ERROR, "inherited constraint is not a CHECK or not-null constraint");
14776 : :
14777 [ - + ]: 283 : if (childcon->coninhcount <= 0) /* shouldn't happen */
14778 [ # # ]: 0 : elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
14779 : : childrelid, NameStr(childcon->conname));
14780 : :
14781 [ + + ]: 283 : if (recurse)
14782 : : {
14783 : : /*
14784 : : * If the child constraint has other definition sources, just
14785 : : * decrement its inheritance count; if not, recurse to delete it.
14786 : : */
14787 [ + + + + ]: 215 : if (childcon->coninhcount == 1 && !childcon->conislocal)
14788 : : {
14789 : : /* Time to delete this child constraint, too */
14790 : 159 : dropconstraint_internal(childrel, tuple, behavior,
14791 : : recurse, true, missing_ok,
14792 : : lockmode);
14793 : : }
14794 : : else
14795 : : {
14796 : : /* Child constraint must survive my deletion */
14797 : 56 : childcon->coninhcount--;
14798 : 56 : CatalogTupleUpdate(conrel, &tuple->t_self, tuple);
14799 : :
14800 : : /* Make update visible */
14801 : 56 : CommandCounterIncrement();
14802 : : }
14803 : : }
14804 : : else
14805 : : {
14806 : : /*
14807 : : * If we were told to drop ONLY in this table (no recursion) and
14808 : : * there are no further parents for this constraint, we need to
14809 : : * mark the inheritors' constraints as locally defined rather than
14810 : : * inherited.
14811 : : */
14812 : 68 : childcon->coninhcount--;
14813 [ + - ]: 68 : if (childcon->coninhcount == 0)
14814 : 68 : childcon->conislocal = true;
14815 : :
14816 : 68 : CatalogTupleUpdate(conrel, &tuple->t_self, tuple);
14817 : :
14818 : : /* Make update visible */
14819 : 68 : CommandCounterIncrement();
14820 : : }
14821 : :
14822 : 279 : heap_freetuple(tuple);
14823 : :
14824 : 279 : table_close(childrel, NoLock);
14825 : : }
14826 : :
14827 : 619 : table_close(conrel, RowExclusiveLock);
14828 : :
14829 : 619 : return conobj;
14830 : : }
14831 : :
14832 : : /*
14833 : : * ALTER COLUMN TYPE
14834 : : *
14835 : : * Unlike other subcommand types, we do parse transformation for ALTER COLUMN
14836 : : * TYPE during phase 1 --- the AlterTableCmd passed in here is already
14837 : : * transformed (and must be, because we rely on some transformed fields).
14838 : : *
14839 : : * The point of this is that the execution of all ALTER COLUMN TYPEs for a
14840 : : * table will be done "in parallel" during phase 3, so all the USING
14841 : : * expressions should be parsed assuming the original column types. Also,
14842 : : * this allows a USING expression to refer to a field that will be dropped.
14843 : : *
14844 : : * To make this work safely, AT_PASS_DROP then AT_PASS_ALTER_TYPE must be
14845 : : * the first two execution steps in phase 2; they must not see the effects
14846 : : * of any other subcommand types, since the USING expressions are parsed
14847 : : * against the unmodified table's state.
14848 : : */
14849 : : static void
14850 : 959 : ATPrepAlterColumnType(List **wqueue,
14851 : : AlteredTableInfo *tab, Relation rel,
14852 : : bool recurse, bool recursing,
14853 : : AlterTableCmd *cmd, LOCKMODE lockmode,
14854 : : AlterTableUtilityContext *context)
14855 : : {
14856 : 959 : char *colName = cmd->name;
14857 : 959 : ColumnDef *def = (ColumnDef *) cmd->def;
14858 : 959 : TypeName *typeName = def->typeName;
14859 : 959 : Node *transform = def->cooked_default;
14860 : : HeapTuple tuple;
14861 : : Form_pg_attribute attTup;
14862 : : AttrNumber attnum;
14863 : : Oid targettype;
14864 : : int32 targettypmod;
14865 : : Oid targetcollid;
14866 : : NewColumnValue *newval;
14867 : 959 : ParseState *pstate = make_parsestate(NULL);
14868 : : AclResult aclresult;
14869 : : bool is_expr;
14870 : :
14871 : 959 : pstate->p_sourcetext = context->queryString;
14872 : :
14873 [ + + + + ]: 959 : if (rel->rd_rel->reloftype && !recursing)
14874 [ + - ]: 4 : ereport(ERROR,
14875 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
14876 : : errmsg("cannot alter column type of typed table"),
14877 : : parser_errposition(pstate, def->location)));
14878 : :
14879 : : /* lookup the attribute so we can check inheritance status */
14880 : 955 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
14881 [ - + ]: 955 : if (!HeapTupleIsValid(tuple))
14882 [ # # ]: 0 : ereport(ERROR,
14883 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
14884 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
14885 : : colName, RelationGetRelationName(rel)),
14886 : : parser_errposition(pstate, def->location)));
14887 : 955 : attTup = (Form_pg_attribute) GETSTRUCT(tuple);
14888 : 955 : attnum = attTup->attnum;
14889 : :
14890 : : /* Can't alter a system attribute */
14891 [ + + ]: 955 : if (attnum <= 0)
14892 [ + - ]: 4 : ereport(ERROR,
14893 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14894 : : errmsg("cannot alter system column \"%s\"", colName),
14895 : : parser_errposition(pstate, def->location)));
14896 : :
14897 : : /*
14898 : : * Cannot specify USING when altering type of a generated column, because
14899 : : * that would violate the generation expression.
14900 : : */
14901 [ + + + + ]: 951 : if (attTup->attgenerated && def->cooked_default)
14902 [ + - ]: 8 : ereport(ERROR,
14903 : : (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
14904 : : errmsg("cannot specify USING when altering type of generated column"),
14905 : : errdetail("Column \"%s\" is a generated column.", colName),
14906 : : parser_errposition(pstate, def->location)));
14907 : :
14908 : : /*
14909 : : * Don't alter inherited columns. At outer level, there had better not be
14910 : : * any inherited definition; when recursing, we assume this was checked at
14911 : : * the parent level (see below).
14912 : : */
14913 [ + + + + ]: 943 : if (attTup->attinhcount > 0 && !recursing)
14914 [ + - ]: 4 : ereport(ERROR,
14915 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14916 : : errmsg("cannot alter inherited column \"%s\"", colName),
14917 : : parser_errposition(pstate, def->location)));
14918 : :
14919 : : /* Don't alter columns used in the partition key */
14920 [ + + ]: 939 : if (has_partition_attrs(rel,
14921 : : bms_make_singleton(attnum - FirstLowInvalidHeapAttributeNumber),
14922 : : &is_expr))
14923 [ + - ]: 12 : ereport(ERROR,
14924 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
14925 : : errmsg("cannot alter column \"%s\" because it is part of the partition key of relation \"%s\"",
14926 : : colName, RelationGetRelationName(rel)),
14927 : : parser_errposition(pstate, def->location)));
14928 : :
14929 : : /* Look up the target type */
14930 : 927 : typenameTypeIdAndMod(pstate, typeName, &targettype, &targettypmod);
14931 : :
14932 : 923 : aclresult = object_aclcheck(TypeRelationId, targettype, GetUserId(), ACL_USAGE);
14933 [ + + ]: 923 : if (aclresult != ACLCHECK_OK)
14934 : 8 : aclcheck_error_type(aclresult, targettype);
14935 : :
14936 : : /* And the collation */
14937 : 915 : targetcollid = GetColumnDefCollation(pstate, def, targettype);
14938 : :
14939 : : /* make sure datatype is legal for a column */
14940 : 1822 : CheckAttributeType(colName, targettype, targetcollid,
14941 : 911 : list_make1_oid(rel->rd_rel->reltype),
14942 [ + + ]: 911 : (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL ? CHKATYPE_IS_VIRTUAL : 0));
14943 : :
14944 [ + + ]: 903 : if (attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
14945 : : {
14946 : : /* do nothing */
14947 : : }
14948 [ + + ]: 879 : else if (tab->relkind == RELKIND_RELATION ||
14949 [ + + ]: 137 : tab->relkind == RELKIND_PARTITIONED_TABLE)
14950 : : {
14951 : : /*
14952 : : * Set up an expression to transform the old data value to the new
14953 : : * type. If a USING option was given, use the expression as
14954 : : * transformed by transformAlterTableStmt, else just take the old
14955 : : * value and try to coerce it. We do this first so that type
14956 : : * incompatibility can be detected before we waste effort, and because
14957 : : * we need the expression to be parsed against the original table row
14958 : : * type.
14959 : : */
14960 [ + + ]: 786 : if (!transform)
14961 : : {
14962 : 635 : transform = (Node *) makeVar(1, attnum,
14963 : : attTup->atttypid, attTup->atttypmod,
14964 : : attTup->attcollation,
14965 : : 0);
14966 : : }
14967 : :
14968 : 786 : transform = coerce_to_target_type(pstate,
14969 : : transform, exprType(transform),
14970 : : targettype, targettypmod,
14971 : : COERCION_ASSIGNMENT,
14972 : : COERCE_IMPLICIT_CAST,
14973 : : -1);
14974 [ + + ]: 786 : if (transform == NULL)
14975 : : {
14976 : : /* error text depends on whether USING was specified or not */
14977 [ + + ]: 15 : if (def->cooked_default != NULL)
14978 [ + - ]: 4 : ereport(ERROR,
14979 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
14980 : : errmsg("result of USING clause for column \"%s\""
14981 : : " cannot be cast automatically to type %s",
14982 : : colName, format_type_be(targettype)),
14983 : : errhint("You might need to add an explicit cast.")));
14984 : : else
14985 [ + - + - ]: 11 : ereport(ERROR,
14986 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
14987 : : errmsg("column \"%s\" cannot be cast automatically to type %s",
14988 : : colName, format_type_be(targettype)),
14989 : : !attTup->attgenerated ?
14990 : : /* translator: USING is SQL, don't translate it */
14991 : : errhint("You might need to specify \"USING %s::%s\".",
14992 : : quote_identifier(colName),
14993 : : format_type_with_typemod(targettype,
14994 : : targettypmod)) : 0));
14995 : : }
14996 : :
14997 : : /* Fix collations after all else */
14998 : 771 : assign_expr_collations(pstate, transform);
14999 : :
15000 : : /* Expand virtual generated columns in the expr. */
15001 : 771 : transform = expand_generated_columns_in_expr(transform, rel, 1);
15002 : :
15003 : : /* Plan the expr now so we can accurately assess the need to rewrite. */
15004 : 771 : transform = (Node *) expression_planner((Expr *) transform);
15005 : :
15006 : : /*
15007 : : * Add a work queue item to make ATRewriteTable update the column
15008 : : * contents.
15009 : : */
15010 : 771 : newval = palloc0_object(NewColumnValue);
15011 : 771 : newval->attnum = attnum;
15012 : 771 : newval->expr = (Expr *) transform;
15013 : 771 : newval->is_generated = false;
15014 : :
15015 : 771 : tab->newvals = lappend(tab->newvals, newval);
15016 [ + + ]: 1410 : if (ATColumnChangeRequiresRewrite(transform, attnum))
15017 : 639 : tab->rewrite |= AT_REWRITE_COLUMN_REWRITE;
15018 : : }
15019 [ + + ]: 93 : else if (transform)
15020 [ + - ]: 8 : ereport(ERROR,
15021 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
15022 : : errmsg("\"%s\" is not a table",
15023 : : RelationGetRelationName(rel))));
15024 : :
15025 [ + + + - : 880 : if (!RELKIND_HAS_STORAGE(tab->relkind) || attTup->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
+ - + - -
+ + + ]
15026 : : {
15027 : : /*
15028 : : * For relations or columns without storage, do this check now.
15029 : : * Regular tables will check it later when the table is being
15030 : : * rewritten.
15031 : : */
15032 : 153 : find_composite_type_dependencies(rel->rd_rel->reltype, rel, NULL);
15033 : : }
15034 : :
15035 : 848 : ReleaseSysCache(tuple);
15036 : :
15037 : : /*
15038 : : * Recurse manually by queueing a new command for each child, if
15039 : : * necessary. We cannot apply ATSimpleRecursion here because we need to
15040 : : * remap attribute numbers in the USING expression, if any.
15041 : : *
15042 : : * If we are told not to recurse, there had better not be any child
15043 : : * tables; else the alter would put them out of step.
15044 : : */
15045 [ + + ]: 848 : if (recurse)
15046 : : {
15047 : 673 : Oid relid = RelationGetRelid(rel);
15048 : : List *child_oids,
15049 : : *child_numparents;
15050 : : ListCell *lo,
15051 : : *li;
15052 : :
15053 : 673 : child_oids = find_all_inheritors(relid, lockmode,
15054 : : &child_numparents);
15055 : :
15056 : : /*
15057 : : * find_all_inheritors does the recursive search of the inheritance
15058 : : * hierarchy, so all we have to do is process all of the relids in the
15059 : : * list that it returns.
15060 : : */
15061 [ + - + + : 1484 : forboth(lo, child_oids, li, child_numparents)
+ - + + +
+ + - +
+ ]
15062 : : {
15063 : 827 : Oid childrelid = lfirst_oid(lo);
15064 : 827 : int numparents = lfirst_int(li);
15065 : : Relation childrel;
15066 : : HeapTuple childtuple;
15067 : : Form_pg_attribute childattTup;
15068 : :
15069 [ + + ]: 827 : if (childrelid == relid)
15070 : 673 : continue;
15071 : :
15072 : : /* find_all_inheritors already got lock */
15073 : 154 : childrel = relation_open(childrelid, NoLock);
15074 : 154 : CheckAlterTableIsSafe(childrel);
15075 : :
15076 : : /*
15077 : : * Verify that the child doesn't have any inherited definitions of
15078 : : * this column that came from outside this inheritance hierarchy.
15079 : : * (renameatt makes a similar test, though in a different way
15080 : : * because of its different recursion mechanism.)
15081 : : */
15082 : 154 : childtuple = SearchSysCacheAttName(RelationGetRelid(childrel),
15083 : : colName);
15084 [ - + ]: 154 : if (!HeapTupleIsValid(childtuple))
15085 [ # # ]: 0 : ereport(ERROR,
15086 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
15087 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
15088 : : colName, RelationGetRelationName(childrel))));
15089 : 154 : childattTup = (Form_pg_attribute) GETSTRUCT(childtuple);
15090 : :
15091 [ + + ]: 154 : if (childattTup->attinhcount > numparents)
15092 [ + - ]: 4 : ereport(ERROR,
15093 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
15094 : : errmsg("cannot alter inherited column \"%s\" of relation \"%s\"",
15095 : : colName, RelationGetRelationName(childrel))));
15096 : :
15097 : 150 : ReleaseSysCache(childtuple);
15098 : :
15099 : : /*
15100 : : * Remap the attribute numbers. If no USING expression was
15101 : : * specified, there is no need for this step.
15102 : : */
15103 [ + + ]: 150 : if (def->cooked_default)
15104 : : {
15105 : : AttrMap *attmap;
15106 : : bool found_whole_row;
15107 : :
15108 : : /* create a copy to scribble on */
15109 : 52 : cmd = copyObject(cmd);
15110 : :
15111 : 52 : attmap = build_attrmap_by_name(RelationGetDescr(childrel),
15112 : : RelationGetDescr(rel),
15113 : : false);
15114 : 104 : ((ColumnDef *) cmd->def)->cooked_default =
15115 : 52 : map_variable_attnos(def->cooked_default,
15116 : : 1, 0,
15117 : : attmap,
15118 : : InvalidOid, &found_whole_row);
15119 [ + + ]: 52 : if (found_whole_row)
15120 [ + - ]: 4 : ereport(ERROR,
15121 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15122 : : errmsg("cannot convert whole-row table reference"),
15123 : : errdetail("USING expression contains a whole-row table reference.")));
15124 : 48 : pfree(attmap);
15125 : : }
15126 : 146 : ATPrepCmd(wqueue, childrel, cmd, false, true, lockmode, context);
15127 : 138 : relation_close(childrel, NoLock);
15128 : : }
15129 : : }
15130 [ + + - + ]: 212 : else if (!recursing &&
15131 : 37 : find_inheritance_children(RelationGetRelid(rel), NoLock) != NIL)
15132 [ # # ]: 0 : ereport(ERROR,
15133 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
15134 : : errmsg("type of inherited column \"%s\" must be changed in child tables too",
15135 : : colName)));
15136 : :
15137 [ + + ]: 832 : if (tab->relkind == RELKIND_COMPOSITE_TYPE)
15138 : 37 : ATTypedTableRecursion(wqueue, rel, cmd, lockmode, context);
15139 : 828 : }
15140 : :
15141 : : /*
15142 : : * When the data type of a column is changed, a rewrite might not be required
15143 : : * if the new type is sufficiently identical to the old one, and the USING
15144 : : * clause isn't trying to insert some other value. It's safe to skip the
15145 : : * rewrite in these cases:
15146 : : *
15147 : : * - the old type is binary coercible to the new type
15148 : : * - the new type is an unconstrained domain over the old type
15149 : : * - {NEW,OLD} or {OLD,NEW} is {timestamptz,timestamp} and the timezone is UTC
15150 : : *
15151 : : * In the case of a constrained domain, we could get by with scanning the
15152 : : * table and checking the constraint rather than actually rewriting it, but we
15153 : : * don't currently try to do that.
15154 : : */
15155 : : static bool
15156 : 771 : ATColumnChangeRequiresRewrite(Node *expr, AttrNumber varattno)
15157 : : {
15158 : : Assert(expr != NULL);
15159 : :
15160 : : for (;;)
15161 : : {
15162 : : /* only one varno, so no need to check that */
15163 [ + + + - ]: 847 : if (IsA(expr, Var) && ((Var *) expr)->varattno == varattno)
15164 : 132 : return false;
15165 [ + + ]: 715 : else if (IsA(expr, RelabelType))
15166 : 68 : expr = (Node *) ((RelabelType *) expr)->arg;
15167 [ + + ]: 647 : else if (IsA(expr, CoerceToDomain))
15168 : : {
15169 : 4 : CoerceToDomain *d = (CoerceToDomain *) expr;
15170 : :
15171 [ + - ]: 4 : if (DomainHasConstraints(d->resulttype, NULL))
15172 : 4 : return true;
15173 : 0 : expr = (Node *) d->arg;
15174 : : }
15175 [ + + ]: 643 : else if (IsA(expr, FuncExpr))
15176 : : {
15177 : 510 : FuncExpr *f = (FuncExpr *) expr;
15178 : :
15179 [ + + ]: 510 : switch (f->funcid)
15180 : : {
15181 : 12 : case F_TIMESTAMPTZ_TIMESTAMP:
15182 : : case F_TIMESTAMP_TIMESTAMPTZ:
15183 [ + + ]: 12 : if (TimestampTimestampTzRequiresRewrite())
15184 : 4 : return true;
15185 : : else
15186 : 8 : expr = linitial(f->args);
15187 : 8 : break;
15188 : 498 : default:
15189 : 498 : return true;
15190 : : }
15191 : : }
15192 : : else
15193 : 133 : return true;
15194 : : }
15195 : : }
15196 : :
15197 : : /*
15198 : : * ALTER COLUMN .. SET DATA TYPE
15199 : : *
15200 : : * Return the address of the modified column.
15201 : : */
15202 : : static ObjectAddress
15203 : 804 : ATExecAlterColumnType(AlteredTableInfo *tab, Relation rel,
15204 : : AlterTableCmd *cmd, LOCKMODE lockmode)
15205 : : {
15206 : 804 : char *colName = cmd->name;
15207 : 804 : ColumnDef *def = (ColumnDef *) cmd->def;
15208 : 804 : TypeName *typeName = def->typeName;
15209 : : HeapTuple heapTup;
15210 : : Form_pg_attribute attTup,
15211 : : attOldTup;
15212 : : AttrNumber attnum;
15213 : : HeapTuple typeTuple;
15214 : : Form_pg_type tform;
15215 : : Oid targettype;
15216 : : int32 targettypmod;
15217 : : Oid targetcollid;
15218 : : Node *defaultexpr;
15219 : : Relation attrelation;
15220 : : Relation depRel;
15221 : : ScanKeyData key[3];
15222 : : SysScanDesc scan;
15223 : : HeapTuple depTup;
15224 : : ObjectAddress address;
15225 : :
15226 : : /*
15227 : : * Clear all the missing values if we're rewriting the table, since this
15228 : : * renders them pointless.
15229 : : */
15230 [ + + ]: 804 : if (tab->rewrite)
15231 : : {
15232 : : Relation newrel;
15233 : :
15234 : 599 : newrel = table_open(RelationGetRelid(rel), NoLock);
15235 : 599 : RelationClearMissing(newrel);
15236 : 599 : relation_close(newrel, NoLock);
15237 : : /* make sure we don't conflict with later attribute modifications */
15238 : 599 : CommandCounterIncrement();
15239 : : }
15240 : :
15241 : 804 : attrelation = table_open(AttributeRelationId, RowExclusiveLock);
15242 : :
15243 : : /* Look up the target column */
15244 : 804 : heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
15245 [ - + ]: 804 : if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
15246 [ # # ]: 0 : ereport(ERROR,
15247 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
15248 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
15249 : : colName, RelationGetRelationName(rel))));
15250 : 804 : attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
15251 : 804 : attnum = attTup->attnum;
15252 : 804 : attOldTup = TupleDescAttr(tab->oldDesc, attnum - 1);
15253 : :
15254 : : /* Check for multiple ALTER TYPE on same column --- can't cope */
15255 [ + - ]: 804 : if (attTup->atttypid != attOldTup->atttypid ||
15256 [ - + ]: 804 : attTup->atttypmod != attOldTup->atttypmod)
15257 [ # # ]: 0 : ereport(ERROR,
15258 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15259 : : errmsg("cannot alter type of column \"%s\" twice",
15260 : : colName)));
15261 : :
15262 : : /* Look up the target type (should not fail, since prep found it) */
15263 : 804 : typeTuple = typenameType(NULL, typeName, &targettypmod);
15264 : 804 : tform = (Form_pg_type) GETSTRUCT(typeTuple);
15265 : 804 : targettype = tform->oid;
15266 : : /* And the collation */
15267 : 804 : targetcollid = GetColumnDefCollation(NULL, def, targettype);
15268 : :
15269 : : /*
15270 : : * If there is a default expression for the column, get it and ensure we
15271 : : * can coerce it to the new datatype. (We must do this before changing
15272 : : * the column type, because build_column_default itself will try to
15273 : : * coerce, and will not issue the error message we want if it fails.)
15274 : : *
15275 : : * We remove any implicit coercion steps at the top level of the old
15276 : : * default expression; this has been agreed to satisfy the principle of
15277 : : * least surprise. (The conversion to the new column type should act like
15278 : : * it started from what the user sees as the stored expression, and the
15279 : : * implicit coercions aren't going to be shown.)
15280 : : */
15281 [ + + ]: 804 : if (attTup->atthasdef)
15282 : : {
15283 : 68 : defaultexpr = build_column_default(rel, attnum);
15284 : : Assert(defaultexpr);
15285 : 68 : defaultexpr = strip_implicit_coercions(defaultexpr);
15286 : 68 : defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
15287 : : defaultexpr, exprType(defaultexpr),
15288 : : targettype, targettypmod,
15289 : : COERCION_ASSIGNMENT,
15290 : : COERCE_IMPLICIT_CAST,
15291 : : -1);
15292 [ + + ]: 68 : if (defaultexpr == NULL)
15293 : : {
15294 [ - + ]: 4 : if (attTup->attgenerated)
15295 [ # # ]: 0 : ereport(ERROR,
15296 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
15297 : : errmsg("generation expression for column \"%s\" cannot be cast automatically to type %s",
15298 : : colName, format_type_be(targettype))));
15299 : : else
15300 [ + - ]: 4 : ereport(ERROR,
15301 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
15302 : : errmsg("default for column \"%s\" cannot be cast automatically to type %s",
15303 : : colName, format_type_be(targettype))));
15304 : : }
15305 : : }
15306 : : else
15307 : 736 : defaultexpr = NULL;
15308 : :
15309 : : /*
15310 : : * Find everything that depends on the column (constraints, indexes, etc),
15311 : : * and record enough information to let us recreate the objects.
15312 : : *
15313 : : * The actual recreation does not happen here, but only after we have
15314 : : * performed all the individual ALTER TYPE operations. We have to save
15315 : : * the info before executing ALTER TYPE, though, else the deparser will
15316 : : * get confused.
15317 : : */
15318 : 800 : RememberAllDependentForRebuilding(tab, AT_AlterColumnType, rel, attnum, colName);
15319 : :
15320 : : /*
15321 : : * Now scan for dependencies of this column on other things. The only
15322 : : * things we should find are the dependency on the column datatype and
15323 : : * possibly a collation dependency. Those can be removed.
15324 : : */
15325 : 776 : depRel = table_open(DependRelationId, RowExclusiveLock);
15326 : :
15327 : 776 : ScanKeyInit(&key[0],
15328 : : Anum_pg_depend_classid,
15329 : : BTEqualStrategyNumber, F_OIDEQ,
15330 : : ObjectIdGetDatum(RelationRelationId));
15331 : 776 : ScanKeyInit(&key[1],
15332 : : Anum_pg_depend_objid,
15333 : : BTEqualStrategyNumber, F_OIDEQ,
15334 : : ObjectIdGetDatum(RelationGetRelid(rel)));
15335 : 776 : ScanKeyInit(&key[2],
15336 : : Anum_pg_depend_objsubid,
15337 : : BTEqualStrategyNumber, F_INT4EQ,
15338 : : Int32GetDatum((int32) attnum));
15339 : :
15340 : 776 : scan = systable_beginscan(depRel, DependDependerIndexId, true,
15341 : : NULL, 3, key);
15342 : :
15343 [ + + ]: 778 : while (HeapTupleIsValid(depTup = systable_getnext(scan)))
15344 : : {
15345 : 2 : Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
15346 : : ObjectAddress foundObject;
15347 : :
15348 : 2 : foundObject.classId = foundDep->refclassid;
15349 : 2 : foundObject.objectId = foundDep->refobjid;
15350 : 2 : foundObject.objectSubId = foundDep->refobjsubid;
15351 : :
15352 [ - + ]: 2 : if (foundDep->deptype != DEPENDENCY_NORMAL)
15353 [ # # ]: 0 : elog(ERROR, "found unexpected dependency type '%c'",
15354 : : foundDep->deptype);
15355 [ + - ]: 2 : if (!(foundDep->refclassid == TypeRelationId &&
15356 [ - + ]: 2 : foundDep->refobjid == attTup->atttypid) &&
15357 [ # # ]: 0 : !(foundDep->refclassid == CollationRelationId &&
15358 [ # # ]: 0 : foundDep->refobjid == attTup->attcollation))
15359 [ # # ]: 0 : elog(ERROR, "found unexpected dependency for column: %s",
15360 : : getObjectDescription(&foundObject, false));
15361 : :
15362 : 2 : CatalogTupleDelete(depRel, &depTup->t_self);
15363 : : }
15364 : :
15365 : 776 : systable_endscan(scan);
15366 : :
15367 : 776 : table_close(depRel, RowExclusiveLock);
15368 : :
15369 : : /*
15370 : : * Here we go --- change the recorded column type and collation. (Note
15371 : : * heapTup is a copy of the syscache entry, so okay to scribble on.) First
15372 : : * fix up the missing value if any.
15373 : : */
15374 [ + + ]: 776 : if (attTup->atthasmissing)
15375 : : {
15376 : : Datum missingval;
15377 : : bool missingNull;
15378 : :
15379 : : /* if rewrite is true the missing value should already be cleared */
15380 : : Assert(tab->rewrite == 0);
15381 : :
15382 : : /* Get the missing value datum */
15383 : 4 : missingval = heap_getattr(heapTup,
15384 : : Anum_pg_attribute_attmissingval,
15385 : : attrelation->rd_att,
15386 : : &missingNull);
15387 : :
15388 : : /* if it's a null array there is nothing to do */
15389 : :
15390 [ + - ]: 4 : if (!missingNull)
15391 : : {
15392 : : /*
15393 : : * Get the datum out of the array and repack it in a new array
15394 : : * built with the new type data. We assume that since the table
15395 : : * doesn't need rewriting, the actual Datum doesn't need to be
15396 : : * changed, only the array metadata.
15397 : : */
15398 : :
15399 : 4 : int one = 1;
15400 : : bool isNull;
15401 : 4 : Datum valuesAtt[Natts_pg_attribute] = {0};
15402 : 4 : bool nullsAtt[Natts_pg_attribute] = {0};
15403 : 4 : bool replacesAtt[Natts_pg_attribute] = {0};
15404 : : HeapTuple newTup;
15405 : :
15406 : 8 : missingval = array_get_element(missingval,
15407 : : 1,
15408 : : &one,
15409 : : 0,
15410 : 4 : attTup->attlen,
15411 : 4 : attTup->attbyval,
15412 : 4 : attTup->attalign,
15413 : : &isNull);
15414 : 4 : missingval = PointerGetDatum(construct_array(&missingval,
15415 : : 1,
15416 : : targettype,
15417 : : tform->typlen,
15418 : : tform->typbyval,
15419 : : tform->typalign));
15420 : :
15421 : 4 : valuesAtt[Anum_pg_attribute_attmissingval - 1] = missingval;
15422 : 4 : replacesAtt[Anum_pg_attribute_attmissingval - 1] = true;
15423 : 4 : nullsAtt[Anum_pg_attribute_attmissingval - 1] = false;
15424 : :
15425 : 4 : newTup = heap_modify_tuple(heapTup, RelationGetDescr(attrelation),
15426 : : valuesAtt, nullsAtt, replacesAtt);
15427 : 4 : heap_freetuple(heapTup);
15428 : 4 : heapTup = newTup;
15429 : 4 : attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
15430 : : }
15431 : : }
15432 : :
15433 : 776 : attTup->atttypid = targettype;
15434 : 776 : attTup->atttypmod = targettypmod;
15435 : 776 : attTup->attcollation = targetcollid;
15436 [ - + ]: 776 : if (list_length(typeName->arrayBounds) > PG_INT16_MAX)
15437 [ # # ]: 0 : ereport(ERROR,
15438 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
15439 : : errmsg("too many array dimensions"));
15440 : 776 : attTup->attndims = list_length(typeName->arrayBounds);
15441 : 776 : attTup->attlen = tform->typlen;
15442 : 776 : attTup->attbyval = tform->typbyval;
15443 : 776 : attTup->attalign = tform->typalign;
15444 : 776 : attTup->attstorage = tform->typstorage;
15445 : 776 : attTup->attcompression = InvalidCompressionMethod;
15446 : :
15447 : 776 : ReleaseSysCache(typeTuple);
15448 : :
15449 : 776 : CatalogTupleUpdate(attrelation, &heapTup->t_self, heapTup);
15450 : :
15451 : 776 : table_close(attrelation, RowExclusiveLock);
15452 : :
15453 : : /* Install dependencies on new datatype and collation */
15454 : 776 : add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
15455 : 776 : add_column_collation_dependency(RelationGetRelid(rel), attnum, targetcollid);
15456 : :
15457 : : /*
15458 : : * Drop any pg_statistic entry for the column, since it's now wrong type
15459 : : */
15460 : 776 : RemoveStatistics(RelationGetRelid(rel), attnum);
15461 : :
15462 [ - + ]: 776 : InvokeObjectPostAlterHook(RelationRelationId,
15463 : : RelationGetRelid(rel), attnum);
15464 : :
15465 : : /*
15466 : : * Update the default, if present, by brute force --- remove and re-add
15467 : : * the default. Probably unsafe to take shortcuts, since the new version
15468 : : * may well have additional dependencies. (It's okay to do this now,
15469 : : * rather than after other ALTER TYPE commands, since the default won't
15470 : : * depend on other column types.)
15471 : : */
15472 [ + + ]: 776 : if (defaultexpr)
15473 : : {
15474 : : /*
15475 : : * If it's a GENERATED default, drop its dependency records, in
15476 : : * particular its INTERNAL dependency on the column, which would
15477 : : * otherwise cause dependency.c to refuse to perform the deletion.
15478 : : */
15479 [ + + ]: 64 : if (attTup->attgenerated)
15480 : : {
15481 : 28 : Oid attrdefoid = GetAttrDefaultOid(RelationGetRelid(rel), attnum);
15482 : :
15483 [ - + ]: 28 : if (!OidIsValid(attrdefoid))
15484 [ # # ]: 0 : elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
15485 : : RelationGetRelid(rel), attnum);
15486 : 28 : (void) deleteDependencyRecordsFor(AttrDefaultRelationId, attrdefoid, false);
15487 : : }
15488 : :
15489 : : /*
15490 : : * Make updates-so-far visible, particularly the new pg_attribute row
15491 : : * which will be updated again.
15492 : : */
15493 : 64 : CommandCounterIncrement();
15494 : :
15495 : : /*
15496 : : * We use RESTRICT here for safety, but at present we do not expect
15497 : : * anything to depend on the default.
15498 : : */
15499 : 64 : RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true,
15500 : : true);
15501 : :
15502 : 64 : (void) StoreAttrDefault(rel, attnum, defaultexpr, true);
15503 : : }
15504 : :
15505 : 776 : ObjectAddressSubSet(address, RelationRelationId,
15506 : : RelationGetRelid(rel), attnum);
15507 : :
15508 : : /* Cleanup */
15509 : 776 : heap_freetuple(heapTup);
15510 : :
15511 : 776 : return address;
15512 : : }
15513 : :
15514 : : /*
15515 : : * Subroutine for ATExecAlterColumnType and ATExecSetExpression: Find everything
15516 : : * that depends on the column (constraints, indexes, etc), and record enough
15517 : : * information to let us recreate the objects.
15518 : : */
15519 : : static void
15520 : 981 : RememberAllDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype,
15521 : : Relation rel, AttrNumber attnum, const char *colName)
15522 : : {
15523 : : Relation depRel;
15524 : : ScanKeyData key[3];
15525 : : SysScanDesc scan;
15526 : : HeapTuple depTup;
15527 : :
15528 : : Assert(subtype == AT_AlterColumnType || subtype == AT_SetExpression);
15529 : :
15530 : 981 : depRel = table_open(DependRelationId, RowExclusiveLock);
15531 : :
15532 : 981 : ScanKeyInit(&key[0],
15533 : : Anum_pg_depend_refclassid,
15534 : : BTEqualStrategyNumber, F_OIDEQ,
15535 : : ObjectIdGetDatum(RelationRelationId));
15536 : 981 : ScanKeyInit(&key[1],
15537 : : Anum_pg_depend_refobjid,
15538 : : BTEqualStrategyNumber, F_OIDEQ,
15539 : : ObjectIdGetDatum(RelationGetRelid(rel)));
15540 : 981 : ScanKeyInit(&key[2],
15541 : : Anum_pg_depend_refobjsubid,
15542 : : BTEqualStrategyNumber, F_INT4EQ,
15543 : : Int32GetDatum((int32) attnum));
15544 : :
15545 : 981 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
15546 : : NULL, 3, key);
15547 : :
15548 [ + + ]: 2003 : while (HeapTupleIsValid(depTup = systable_getnext(scan)))
15549 : : {
15550 : 1046 : Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
15551 : : ObjectAddress foundObject;
15552 : :
15553 : 1046 : foundObject.classId = foundDep->classid;
15554 : 1046 : foundObject.objectId = foundDep->objid;
15555 : 1046 : foundObject.objectSubId = foundDep->objsubid;
15556 : :
15557 [ + + - + : 1046 : switch (foundObject.classId)
- - + + -
- ]
15558 : : {
15559 : 192 : case RelationRelationId:
15560 : : {
15561 : 192 : char relKind = get_rel_relkind(foundObject.objectId);
15562 : :
15563 [ + + + + ]: 192 : if (relKind == RELKIND_INDEX ||
15564 : : relKind == RELKIND_PARTITIONED_INDEX)
15565 : : {
15566 : : Assert(foundObject.objectSubId == 0);
15567 : 167 : RememberIndexForRebuilding(foundObject.objectId, tab);
15568 : : }
15569 [ - + ]: 25 : else if (relKind == RELKIND_SEQUENCE)
15570 : : {
15571 : : /*
15572 : : * This must be a SERIAL column's sequence. We need
15573 : : * not do anything to it.
15574 : : */
15575 : : Assert(foundObject.objectSubId == 0);
15576 : : }
15577 : : else
15578 : : {
15579 : : /* Not expecting any other direct dependencies... */
15580 [ # # ]: 0 : elog(ERROR, "unexpected object depending on column: %s",
15581 : : getObjectDescription(&foundObject, false));
15582 : : }
15583 : 192 : break;
15584 : : }
15585 : :
15586 : 528 : case ConstraintRelationId:
15587 : : Assert(foundObject.objectSubId == 0);
15588 : 528 : RememberConstraintForRebuilding(foundObject.objectId, tab);
15589 : 528 : break;
15590 : :
15591 : 0 : case ProcedureRelationId:
15592 : :
15593 : : /*
15594 : : * A new-style SQL function can depend on a column, if that
15595 : : * column is referenced in the parsed function body. Ideally
15596 : : * we'd automatically update the function by deparsing and
15597 : : * reparsing it, but that's risky and might well fail anyhow.
15598 : : * FIXME someday.
15599 : : *
15600 : : * This is only a problem for AT_AlterColumnType, not
15601 : : * AT_SetExpression.
15602 : : */
15603 [ # # ]: 0 : if (subtype == AT_AlterColumnType)
15604 [ # # ]: 0 : ereport(ERROR,
15605 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15606 : : errmsg("cannot alter type of a column used by a function or procedure"),
15607 : : errdetail("%s depends on column \"%s\".",
15608 : : getObjectDescription(&foundObject, false),
15609 : : colName)));
15610 : 0 : break;
15611 : :
15612 : 8 : case RewriteRelationId:
15613 : :
15614 : : /*
15615 : : * View/rule bodies have pretty much the same issues as
15616 : : * function bodies. FIXME someday.
15617 : : */
15618 [ + - ]: 8 : if (subtype == AT_AlterColumnType)
15619 [ + - ]: 8 : ereport(ERROR,
15620 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15621 : : errmsg("cannot alter type of a column used by a view or rule"),
15622 : : errdetail("%s depends on column \"%s\".",
15623 : : getObjectDescription(&foundObject, false),
15624 : : colName)));
15625 : 0 : break;
15626 : :
15627 : 0 : case TriggerRelationId:
15628 : :
15629 : : /*
15630 : : * A trigger can depend on a column because the column is
15631 : : * specified as an update target, or because the column is
15632 : : * used in the trigger's WHEN condition. The first case would
15633 : : * not require any extra work, but the second case would
15634 : : * require updating the WHEN expression, which has the same
15635 : : * issues as above. Since we can't easily tell which case
15636 : : * applies, we punt for both. FIXME someday.
15637 : : */
15638 [ # # ]: 0 : if (subtype == AT_AlterColumnType)
15639 [ # # ]: 0 : ereport(ERROR,
15640 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15641 : : errmsg("cannot alter type of a column used in a trigger definition"),
15642 : : errdetail("%s depends on column \"%s\".",
15643 : : getObjectDescription(&foundObject, false),
15644 : : colName)));
15645 : 0 : break;
15646 : :
15647 : 0 : case PolicyRelationId:
15648 : :
15649 : : /*
15650 : : * A policy can depend on a column because the column is
15651 : : * specified in the policy's USING or WITH CHECK qual
15652 : : * expressions. It might be possible to rewrite and recheck
15653 : : * the policy expression, but punt for now. It's certainly
15654 : : * easy enough to remove and recreate the policy; still, FIXME
15655 : : * someday.
15656 : : */
15657 [ # # ]: 0 : if (subtype == AT_AlterColumnType)
15658 [ # # ]: 0 : ereport(ERROR,
15659 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15660 : : errmsg("cannot alter type of a column used in a policy definition"),
15661 : : errdetail("%s depends on column \"%s\".",
15662 : : getObjectDescription(&foundObject, false),
15663 : : colName)));
15664 : 0 : break;
15665 : :
15666 : 261 : case AttrDefaultRelationId:
15667 : : {
15668 : 261 : ObjectAddress col = GetAttrDefaultColumnAddress(foundObject.objectId);
15669 : :
15670 [ + - ]: 506 : if (col.objectId == RelationGetRelid(rel) &&
15671 [ + + ]: 261 : col.objectSubId == attnum)
15672 : : {
15673 : : /*
15674 : : * Ignore the column's own default expression. The
15675 : : * caller deals with it.
15676 : : */
15677 : : }
15678 : : else
15679 : : {
15680 : : /*
15681 : : * This must be a reference from the expression of a
15682 : : * generated column elsewhere in the same table.
15683 : : * Changing the type/generated expression of a column
15684 : : * that is used by a generated column is not allowed
15685 : : * by SQL standard, so just punt for now. It might be
15686 : : * doable with some thinking and effort.
15687 : : */
15688 [ + - ]: 16 : if (subtype == AT_AlterColumnType)
15689 [ + - ]: 16 : ereport(ERROR,
15690 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15691 : : errmsg("cannot alter type of a column used by a generated column"),
15692 : : errdetail("Column \"%s\" is used by generated column \"%s\".",
15693 : : colName,
15694 : : get_attname(col.objectId,
15695 : : col.objectSubId,
15696 : : false))));
15697 : : }
15698 : 245 : break;
15699 : : }
15700 : :
15701 : 57 : case StatisticExtRelationId:
15702 : :
15703 : : /*
15704 : : * Give the extended-stats machinery a chance to fix anything
15705 : : * that this column type change would break.
15706 : : */
15707 : 57 : RememberStatisticsForRebuilding(foundObject.objectId, tab);
15708 : 57 : break;
15709 : :
15710 : 0 : case PublicationRelRelationId:
15711 : :
15712 : : /*
15713 : : * Column reference in a PUBLICATION ... FOR TABLE ... WHERE
15714 : : * clause. Same issues as above. FIXME someday.
15715 : : */
15716 [ # # ]: 0 : if (subtype == AT_AlterColumnType)
15717 [ # # ]: 0 : ereport(ERROR,
15718 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15719 : : errmsg("cannot alter type of a column used by a publication WHERE clause"),
15720 : : errdetail("%s depends on column \"%s\".",
15721 : : getObjectDescription(&foundObject, false),
15722 : : colName)));
15723 : 0 : break;
15724 : :
15725 : 0 : default:
15726 : :
15727 : : /*
15728 : : * We don't expect any other sorts of objects to depend on a
15729 : : * column.
15730 : : */
15731 [ # # ]: 0 : elog(ERROR, "unexpected object depending on column: %s",
15732 : : getObjectDescription(&foundObject, false));
15733 : : break;
15734 : : }
15735 : : }
15736 : :
15737 : 957 : systable_endscan(scan);
15738 : 957 : table_close(depRel, NoLock);
15739 : 957 : }
15740 : :
15741 : : /*
15742 : : * Record information about dependencies between objects with whole-row Var
15743 : : * references (indexes, check constraints, etc.) and the relation.
15744 : : *
15745 : : * See also RememberAllDependentForRebuilding, which handles non-whole-row Var
15746 : : * references.
15747 : : *
15748 : : * This function currently applies only to ALTER COLUMN SET EXPRESSION.
15749 : : */
15750 : : static void
15751 : 181 : RememberWholeRowDependentForRebuilding(AlteredTableInfo *tab, AlterTableType subtype, Relation rel)
15752 : : {
15753 : : ScanKeyData skey;
15754 : : Relation pg_constraint;
15755 : : Relation pg_index;
15756 : : SysScanDesc conscan;
15757 : : SysScanDesc indscan;
15758 : : HeapTuple constrTuple;
15759 : : HeapTuple indexTuple;
15760 : : bool isnull;
15761 : :
15762 : : Assert(subtype == AT_SetExpression);
15763 : :
15764 : : /*
15765 : : * Check CHECK constraints with whole-row references first.
15766 : : */
15767 [ + - ]: 181 : if (RelationGetDescr(rel)->constr &&
15768 [ + + ]: 181 : RelationGetDescr(rel)->constr->num_check > 0)
15769 : : {
15770 : 28 : pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
15771 : :
15772 : 28 : ScanKeyInit(&skey,
15773 : : Anum_pg_constraint_conrelid,
15774 : : BTEqualStrategyNumber, F_OIDEQ,
15775 : : ObjectIdGetDatum(RelationGetRelid(rel)));
15776 : :
15777 : 28 : conscan = systable_beginscan(pg_constraint,
15778 : : ConstraintRelidTypidNameIndexId,
15779 : : true,
15780 : : NULL,
15781 : : 1,
15782 : : &skey);
15783 : :
15784 [ + + ]: 96 : while (HeapTupleIsValid(constrTuple = systable_getnext(conscan)))
15785 : : {
15786 : 68 : Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(constrTuple);
15787 : : Datum exprDatum;
15788 : :
15789 [ + + ]: 68 : if (conform->contype != CONSTRAINT_CHECK)
15790 : 40 : continue;
15791 : :
15792 : 28 : exprDatum = heap_getattr(constrTuple,
15793 : : Anum_pg_constraint_conbin,
15794 : : RelationGetDescr(pg_constraint),
15795 : : &isnull);
15796 [ - + ]: 28 : if (isnull)
15797 [ # # ]: 0 : elog(ERROR, "null conbin for relation \"%s\"",
15798 : : RelationGetRelationName(rel));
15799 : : else
15800 : : {
15801 : : char *exprString;
15802 : : Node *expr;
15803 : 28 : Bitmapset *expr_attrs = NULL;
15804 : :
15805 : 28 : exprString = TextDatumGetCString(exprDatum);
15806 : 28 : expr = stringToNode(exprString);
15807 : 28 : pfree(exprString);
15808 : :
15809 : : /* Find all attributes referenced */
15810 : 28 : pull_varattnos(expr, 1, &expr_attrs);
15811 : :
15812 : : /*
15813 : : * If the CHECK constraint contains whole-row reference then
15814 : : * remember it.
15815 : : */
15816 [ + + ]: 28 : if (bms_is_member(InvalidAttrNumber - FirstLowInvalidHeapAttributeNumber, expr_attrs))
15817 : : {
15818 : 8 : RememberConstraintForRebuilding(conform->oid, tab);
15819 : : }
15820 : : }
15821 : : }
15822 : 28 : systable_endscan(conscan);
15823 : 28 : table_close(pg_constraint, AccessShareLock);
15824 : : }
15825 : :
15826 : : /*
15827 : : * Now check indexes with whole-row references. Prepare to scan pg_index
15828 : : * for entries having indrelid matching this relation.
15829 : : */
15830 : 181 : ScanKeyInit(&skey,
15831 : : Anum_pg_index_indrelid,
15832 : : BTEqualStrategyNumber, F_OIDEQ,
15833 : : ObjectIdGetDatum(RelationGetRelid(rel)));
15834 : :
15835 : 181 : pg_index = table_open(IndexRelationId, AccessShareLock);
15836 : :
15837 : 181 : indscan = systable_beginscan(pg_index,
15838 : : IndexIndrelidIndexId,
15839 : : true,
15840 : : NULL,
15841 : : 1,
15842 : : &skey);
15843 : :
15844 [ + + ]: 261 : while (HeapTupleIsValid(indexTuple = systable_getnext(indscan)))
15845 : : {
15846 : 80 : Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
15847 : : Datum exprDatum;
15848 : :
15849 : 80 : exprDatum = heap_getattr(indexTuple,
15850 : : Anum_pg_index_indexprs,
15851 : : RelationGetDescr(pg_index),
15852 : : &isnull);
15853 [ + + ]: 80 : if (!isnull)
15854 : : {
15855 : : char *exprString;
15856 : : Node *expr;
15857 : 12 : Bitmapset *expr_attrs = NULL;
15858 : :
15859 : 12 : exprString = TextDatumGetCString(exprDatum);
15860 : 12 : expr = stringToNode(exprString);
15861 : 12 : pfree(exprString);
15862 : :
15863 : : /* Find all attributes referenced */
15864 : 12 : pull_varattnos(expr, 1, &expr_attrs);
15865 : :
15866 : : /*
15867 : : * If the index expression contains a whole-row reference then
15868 : : * remember it.
15869 : : */
15870 [ + + ]: 12 : if (bms_is_member(InvalidAttrNumber - FirstLowInvalidHeapAttributeNumber, expr_attrs))
15871 : : {
15872 : 8 : RememberIndexForRebuilding(index->indexrelid, tab);
15873 : 8 : continue;
15874 : : }
15875 : : }
15876 : :
15877 : 72 : exprDatum = heap_getattr(indexTuple,
15878 : : Anum_pg_index_indpred,
15879 : : RelationGetDescr(pg_index),
15880 : : &isnull);
15881 [ + + ]: 72 : if (!isnull)
15882 : : {
15883 : : char *exprString;
15884 : : Node *expr;
15885 : 20 : Bitmapset *expr_attrs = NULL;
15886 : :
15887 : 20 : exprString = TextDatumGetCString(exprDatum);
15888 : 20 : expr = stringToNode(exprString);
15889 : 20 : pfree(exprString);
15890 : :
15891 : : /* Find all attributes referenced */
15892 : 20 : pull_varattnos(expr, 1, &expr_attrs);
15893 : :
15894 : : /*
15895 : : * If the index predicate expression contains a whole-row
15896 : : * reference then remember it.
15897 : : */
15898 [ + + ]: 20 : if (bms_is_member(InvalidAttrNumber - FirstLowInvalidHeapAttributeNumber, expr_attrs))
15899 : : {
15900 : 16 : RememberIndexForRebuilding(index->indexrelid, tab);
15901 : : }
15902 : : }
15903 : : }
15904 : :
15905 : 181 : systable_endscan(indscan);
15906 : 181 : table_close(pg_index, AccessShareLock);
15907 : 181 : }
15908 : :
15909 : : /*
15910 : : * Subroutine for ATExecAlterColumnType: remember that a replica identity
15911 : : * needs to be reset.
15912 : : */
15913 : : static void
15914 : 330 : RememberReplicaIdentityForRebuilding(Oid indoid, AlteredTableInfo *tab)
15915 : : {
15916 [ + + ]: 330 : if (!get_index_isreplident(indoid))
15917 : 318 : return;
15918 : :
15919 [ - + ]: 12 : if (tab->replicaIdentityIndex)
15920 [ # # ]: 0 : elog(ERROR, "relation %u has multiple indexes marked as replica identity", tab->relid);
15921 : :
15922 : 12 : tab->replicaIdentityIndex = get_rel_name(indoid);
15923 : : }
15924 : :
15925 : : /*
15926 : : * Subroutine for ATExecAlterColumnType: remember any clustered index.
15927 : : */
15928 : : static void
15929 : 330 : RememberClusterOnForRebuilding(Oid indoid, AlteredTableInfo *tab)
15930 : : {
15931 [ + + ]: 330 : if (!get_index_isclustered(indoid))
15932 : 318 : return;
15933 : :
15934 [ - + ]: 12 : if (tab->clusterOnIndex)
15935 [ # # ]: 0 : elog(ERROR, "relation %u has multiple clustered indexes", tab->relid);
15936 : :
15937 : 12 : tab->clusterOnIndex = get_rel_name(indoid);
15938 : : }
15939 : :
15940 : : /*
15941 : : * Subroutine for ATExecAlterColumnType: remember that a constraint needs
15942 : : * to be rebuilt (which we might already know).
15943 : : */
15944 : : static void
15945 : 544 : RememberConstraintForRebuilding(Oid conoid, AlteredTableInfo *tab)
15946 : : {
15947 : : /*
15948 : : * This de-duplication check is critical for two independent reasons: we
15949 : : * mustn't try to recreate the same constraint twice, and if a constraint
15950 : : * depends on more than one column whose type is to be altered, we must
15951 : : * capture its definition string before applying any of the column type
15952 : : * changes. ruleutils.c will get confused if we ask again later.
15953 : : */
15954 [ + + ]: 544 : if (!list_member_oid(tab->changedConstraintOids, conoid))
15955 : : {
15956 : : /* OK, capture the constraint's existing definition string */
15957 : 468 : char *defstring = pg_get_constraintdef_command(conoid);
15958 : : Oid indoid;
15959 : :
15960 : : /*
15961 : : * It is critical to create not-null constraints ahead of primary key
15962 : : * indexes; otherwise, the not-null constraint would be created by the
15963 : : * primary key, and the constraint name would be wrong.
15964 : : */
15965 [ + + ]: 468 : if (get_constraint_type(conoid) == CONSTRAINT_NOTNULL)
15966 : : {
15967 : 163 : tab->changedConstraintOids = lcons_oid(conoid,
15968 : : tab->changedConstraintOids);
15969 : 163 : tab->changedConstraintDefs = lcons(defstring,
15970 : : tab->changedConstraintDefs);
15971 : : }
15972 : : else
15973 : : {
15974 : :
15975 : 305 : tab->changedConstraintOids = lappend_oid(tab->changedConstraintOids,
15976 : : conoid);
15977 : 305 : tab->changedConstraintDefs = lappend(tab->changedConstraintDefs,
15978 : : defstring);
15979 : : }
15980 : :
15981 : : /*
15982 : : * For the index of a constraint, if any, remember if it is used for
15983 : : * the table's replica identity or if it is a clustered index, so that
15984 : : * ATPostAlterTypeCleanup() can queue up commands necessary to restore
15985 : : * those properties.
15986 : : */
15987 : 468 : indoid = get_constraint_index(conoid);
15988 [ + + ]: 468 : if (OidIsValid(indoid))
15989 : : {
15990 : 152 : RememberReplicaIdentityForRebuilding(indoid, tab);
15991 : 152 : RememberClusterOnForRebuilding(indoid, tab);
15992 : : }
15993 : : }
15994 : 544 : }
15995 : :
15996 : : /*
15997 : : * Subroutine for ATExecAlterColumnType: remember that an index needs
15998 : : * to be rebuilt (which we might already know).
15999 : : */
16000 : : static void
16001 : 191 : RememberIndexForRebuilding(Oid indoid, AlteredTableInfo *tab)
16002 : : {
16003 : : /*
16004 : : * This de-duplication check is critical for two independent reasons: we
16005 : : * mustn't try to recreate the same index twice, and if an index depends
16006 : : * on more than one column whose type is to be altered, we must capture
16007 : : * its definition string before applying any of the column type changes.
16008 : : * ruleutils.c will get confused if we ask again later.
16009 : : */
16010 [ + + ]: 191 : if (!list_member_oid(tab->changedIndexOids, indoid))
16011 : : {
16012 : : /*
16013 : : * Before adding it as an index-to-rebuild, we'd better see if it
16014 : : * belongs to a constraint, and if so rebuild the constraint instead.
16015 : : * Typically this check fails, because constraint indexes normally
16016 : : * have only dependencies on their constraint. But it's possible for
16017 : : * such an index to also have direct dependencies on table columns,
16018 : : * for example with a partial exclusion constraint.
16019 : : */
16020 : 186 : Oid conoid = get_index_constraint(indoid);
16021 : :
16022 [ + + ]: 186 : if (OidIsValid(conoid))
16023 : : {
16024 : 8 : RememberConstraintForRebuilding(conoid, tab);
16025 : : }
16026 : : else
16027 : : {
16028 : : /* OK, capture the index's existing definition string */
16029 : 178 : char *defstring = pg_get_indexdef_string(indoid);
16030 : :
16031 : 178 : tab->changedIndexOids = lappend_oid(tab->changedIndexOids,
16032 : : indoid);
16033 : 178 : tab->changedIndexDefs = lappend(tab->changedIndexDefs,
16034 : : defstring);
16035 : :
16036 : : /*
16037 : : * Remember if this index is used for the table's replica identity
16038 : : * or if it is a clustered index, so that ATPostAlterTypeCleanup()
16039 : : * can queue up commands necessary to restore those properties.
16040 : : */
16041 : 178 : RememberReplicaIdentityForRebuilding(indoid, tab);
16042 : 178 : RememberClusterOnForRebuilding(indoid, tab);
16043 : : }
16044 : : }
16045 : 191 : }
16046 : :
16047 : : /*
16048 : : * Subroutine for ATExecAlterColumnType: remember that a statistics object
16049 : : * needs to be rebuilt (which we might already know).
16050 : : */
16051 : : static void
16052 : 57 : RememberStatisticsForRebuilding(Oid stxoid, AlteredTableInfo *tab)
16053 : : {
16054 : : /*
16055 : : * This de-duplication check is critical for two independent reasons: we
16056 : : * mustn't try to recreate the same statistics object twice, and if the
16057 : : * statistics object depends on more than one column whose type is to be
16058 : : * altered, we must capture its definition string before applying any of
16059 : : * the type changes. ruleutils.c will get confused if we ask again later.
16060 : : */
16061 [ + - ]: 57 : if (!list_member_oid(tab->changedStatisticsOids, stxoid))
16062 : : {
16063 : : /* OK, capture the statistics object's existing definition string */
16064 : 57 : char *defstring = pg_get_statisticsobjdef_string(stxoid);
16065 : : HeapTuple tup;
16066 : : Form_pg_statistic_ext statext;
16067 : :
16068 : 57 : tup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(stxoid));
16069 : :
16070 [ - + ]: 57 : if (!HeapTupleIsValid(tup)) /* should not happen */
16071 [ # # ]: 0 : elog(ERROR, "cache lookup failed for statistics object %u", stxoid);
16072 : :
16073 : 57 : statext = (Form_pg_statistic_ext) GETSTRUCT(tup);
16074 : :
16075 : 57 : tab->changedStatisticsOids = lappend_oid(tab->changedStatisticsOids,
16076 : : stxoid);
16077 : 57 : tab->changedStatisticsDefs = lappend(tab->changedStatisticsDefs,
16078 : : defstring);
16079 : :
16080 : 57 : tab->changedStatisticsOwners = lappend_oid(tab->changedStatisticsOwners,
16081 : : statext->stxowner);
16082 : :
16083 : 57 : ReleaseSysCache(tup);
16084 : : }
16085 : 57 : }
16086 : :
16087 : : /*
16088 : : * Cleanup after we've finished all the ALTER TYPE or SET EXPRESSION
16089 : : * operations for a particular relation. We have to drop and recreate all the
16090 : : * indexes and constraints that depend on the altered columns. We do the
16091 : : * actual dropping here, but re-creation is managed by adding work queue
16092 : : * entries to do those steps later.
16093 : : */
16094 : : static void
16095 : 925 : ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
16096 : : {
16097 : : ObjectAddress obj;
16098 : : ObjectAddresses *objects;
16099 : : ListCell *def_item;
16100 : : ListCell *oid_item;
16101 : : ListCell *owner_item;
16102 : :
16103 : : /*
16104 : : * Collect all the constraints and indexes to drop so we can process them
16105 : : * in a single call. That way we don't have to worry about dependencies
16106 : : * among them.
16107 : : */
16108 : 925 : objects = new_object_addresses();
16109 : :
16110 : : /*
16111 : : * Re-parse the index and constraint definitions, and attach them to the
16112 : : * appropriate work queue entries. We do this before dropping because in
16113 : : * the case of a constraint on another table, we might not yet have
16114 : : * exclusive lock on the table the constraint is attached to, and we need
16115 : : * to get that before reparsing/dropping. (That's possible at least for
16116 : : * FOREIGN KEY, CHECK, and EXCLUSION constraints; in non-FK cases it
16117 : : * requires a dependency on the target table's composite type in the other
16118 : : * table's constraint expressions.)
16119 : : *
16120 : : * We can't rely on the output of deparsing to tell us which relation to
16121 : : * operate on, because concurrent activity might have made the name
16122 : : * resolve differently. Instead, we've got to use the OID of the
16123 : : * constraint or index we're processing to figure out which relation to
16124 : : * operate on.
16125 : : */
16126 [ + + + + : 1393 : forboth(oid_item, tab->changedConstraintOids,
+ + + + +
+ + - +
+ ]
16127 : : def_item, tab->changedConstraintDefs)
16128 : : {
16129 : 468 : Oid oldId = lfirst_oid(oid_item);
16130 : : HeapTuple tup;
16131 : : Form_pg_constraint con;
16132 : : Oid relid;
16133 : : Oid confrelid;
16134 : : bool conislocal;
16135 : :
16136 : 468 : tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
16137 [ - + ]: 468 : if (!HeapTupleIsValid(tup)) /* should not happen */
16138 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", oldId);
16139 : 468 : con = (Form_pg_constraint) GETSTRUCT(tup);
16140 [ + + ]: 468 : if (OidIsValid(con->conrelid))
16141 : 455 : relid = con->conrelid;
16142 : : else
16143 : : {
16144 : : /* must be a domain constraint */
16145 : 13 : relid = get_typ_typrelid(getBaseType(con->contypid));
16146 [ - + ]: 13 : if (!OidIsValid(relid))
16147 [ # # ]: 0 : elog(ERROR, "could not identify relation associated with constraint %u", oldId);
16148 : : }
16149 : 468 : confrelid = con->confrelid;
16150 : 468 : conislocal = con->conislocal;
16151 : 468 : ReleaseSysCache(tup);
16152 : :
16153 : 468 : ObjectAddressSet(obj, ConstraintRelationId, oldId);
16154 : 468 : add_exact_object_address(&obj, objects);
16155 : :
16156 : : /*
16157 : : * If the constraint is inherited (only), we don't want to inject a
16158 : : * new definition here; it'll get recreated when
16159 : : * ATAddCheckNNConstraint recurses from adding the parent table's
16160 : : * constraint. But we had to carry the info this far so that we can
16161 : : * drop the constraint below.
16162 : : */
16163 [ + + ]: 468 : if (!conislocal)
16164 : 34 : continue;
16165 : :
16166 : : /*
16167 : : * When rebuilding another table's constraint that references the
16168 : : * table we're modifying, we might not yet have any lock on the other
16169 : : * table, so get one now. We'll need AccessExclusiveLock for the DROP
16170 : : * CONSTRAINT step, so there's no value in asking for anything weaker.
16171 : : */
16172 [ + + ]: 434 : if (relid != tab->relid)
16173 : 36 : LockRelationOid(relid, AccessExclusiveLock);
16174 : :
16175 : 434 : ATPostAlterTypeParse(oldId, relid, confrelid, InvalidOid,
16176 : 434 : (char *) lfirst(def_item),
16177 : 434 : wqueue, lockmode, tab->rewrite);
16178 : : }
16179 [ + + + + : 1103 : forboth(oid_item, tab->changedIndexOids,
+ + + + +
+ + - +
+ ]
16180 : : def_item, tab->changedIndexDefs)
16181 : : {
16182 : 178 : Oid oldId = lfirst_oid(oid_item);
16183 : : Oid relid;
16184 : :
16185 : 178 : relid = IndexGetRelation(oldId, false);
16186 : :
16187 : : /*
16188 : : * As above, make sure we have lock on the index's table if it's not
16189 : : * the same table.
16190 : : */
16191 [ + + ]: 178 : if (relid != tab->relid)
16192 : 12 : LockRelationOid(relid, AccessExclusiveLock);
16193 : :
16194 : 178 : ATPostAlterTypeParse(oldId, relid, InvalidOid, InvalidOid,
16195 : 178 : (char *) lfirst(def_item),
16196 : 178 : wqueue, lockmode, tab->rewrite);
16197 : :
16198 : 178 : ObjectAddressSet(obj, RelationRelationId, oldId);
16199 : 178 : add_exact_object_address(&obj, objects);
16200 : : }
16201 : :
16202 : : /* add dependencies for new statistics */
16203 [ + + + + : 982 : forthree(oid_item, tab->changedStatisticsOids,
+ + + + +
+ + + + +
+ - + - +
+ ]
16204 : : def_item, tab->changedStatisticsDefs,
16205 : : owner_item, tab->changedStatisticsOwners)
16206 : : {
16207 : 57 : Oid oldId = lfirst_oid(oid_item);
16208 : : Oid relid;
16209 : :
16210 : 57 : relid = StatisticsGetRelation(oldId, false);
16211 : :
16212 : : /*
16213 : : * As above, make sure we have lock on the statistics object's table
16214 : : * if it's not the same table. However, we take
16215 : : * ShareUpdateExclusiveLock here, aligning with the lock level used in
16216 : : * CreateStatistics and RemoveStatisticsById.
16217 : : *
16218 : : * CAUTION: this should be done after all cases that grab
16219 : : * AccessExclusiveLock, else we risk causing deadlock due to needing
16220 : : * to promote our table lock.
16221 : : */
16222 [ + + ]: 57 : if (relid != tab->relid)
16223 : 12 : LockRelationOid(relid, ShareUpdateExclusiveLock);
16224 : :
16225 : 57 : ATPostAlterTypeParse(oldId, relid, InvalidOid, lfirst_oid(owner_item),
16226 : 57 : (char *) lfirst(def_item),
16227 : 57 : wqueue, lockmode, tab->rewrite);
16228 : :
16229 : 57 : ObjectAddressSet(obj, StatisticExtRelationId, oldId);
16230 : 57 : add_exact_object_address(&obj, objects);
16231 : : }
16232 : :
16233 : : /*
16234 : : * Queue up command to restore replica identity index marking
16235 : : */
16236 [ + + ]: 925 : if (tab->replicaIdentityIndex)
16237 : : {
16238 : 12 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
16239 : 12 : ReplicaIdentityStmt *subcmd = makeNode(ReplicaIdentityStmt);
16240 : :
16241 : 12 : subcmd->identity_type = REPLICA_IDENTITY_INDEX;
16242 : 12 : subcmd->name = tab->replicaIdentityIndex;
16243 : 12 : cmd->subtype = AT_ReplicaIdentity;
16244 : 12 : cmd->def = (Node *) subcmd;
16245 : :
16246 : : /* do it after indexes and constraints */
16247 : 12 : tab->subcmds[AT_PASS_OLD_CONSTR] =
16248 : 12 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
16249 : : }
16250 : :
16251 : : /*
16252 : : * Queue up command to restore marking of index used for cluster.
16253 : : */
16254 [ + + ]: 925 : if (tab->clusterOnIndex)
16255 : : {
16256 : 12 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
16257 : :
16258 : 12 : cmd->subtype = AT_ClusterOn;
16259 : 12 : cmd->name = tab->clusterOnIndex;
16260 : :
16261 : : /* do it after indexes and constraints */
16262 : 12 : tab->subcmds[AT_PASS_OLD_CONSTR] =
16263 : 12 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
16264 : : }
16265 : :
16266 : : /*
16267 : : * It should be okay to use DROP_RESTRICT here, since nothing else should
16268 : : * be depending on these objects.
16269 : : */
16270 : 925 : performMultipleDeletions(objects, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
16271 : :
16272 : 925 : free_object_addresses(objects);
16273 : :
16274 : : /*
16275 : : * The objects will get recreated during subsequent passes over the work
16276 : : * queue.
16277 : : */
16278 : 925 : }
16279 : :
16280 : : /*
16281 : : * Parse the previously-saved definition string for a constraint, index or
16282 : : * statistics object against the newly-established column data type(s), and
16283 : : * queue up the resulting command parsetrees for execution.
16284 : : *
16285 : : * This might fail if, for example, you have a WHERE clause that uses an
16286 : : * operator that's not available for the new column type.
16287 : : */
16288 : : static void
16289 : 669 : ATPostAlterTypeParse(Oid oldId, Oid oldRelId, Oid refRelId, Oid ownerId,
16290 : : const char *cmdstring, List **wqueue, LOCKMODE lockmode,
16291 : : bool rewrite)
16292 : : {
16293 : : List *raw_parsetree_list;
16294 : : List *querytree_list;
16295 : : ListCell *list_item;
16296 : : Relation rel;
16297 : :
16298 : : /*
16299 : : * We expect that we will get only ALTER TABLE and CREATE INDEX
16300 : : * statements. Hence, there is no need to pass them through
16301 : : * parse_analyze_*() or the rewriter, but instead we need to pass them
16302 : : * through parse_utilcmd.c to make them ready for execution.
16303 : : */
16304 : 669 : raw_parsetree_list = raw_parser(cmdstring, RAW_PARSE_DEFAULT);
16305 : 669 : querytree_list = NIL;
16306 [ + - + + : 1338 : foreach(list_item, raw_parsetree_list)
+ + ]
16307 : : {
16308 : 669 : RawStmt *rs = lfirst_node(RawStmt, list_item);
16309 : 669 : Node *stmt = rs->stmt;
16310 : :
16311 [ + + ]: 669 : if (IsA(stmt, IndexStmt))
16312 : 178 : querytree_list = lappend(querytree_list,
16313 : 178 : transformIndexStmt(oldRelId,
16314 : : (IndexStmt *) stmt,
16315 : : cmdstring));
16316 [ + + ]: 491 : else if (IsA(stmt, AlterTableStmt))
16317 : : {
16318 : : List *beforeStmts;
16319 : : List *afterStmts;
16320 : :
16321 : 421 : stmt = (Node *) transformAlterTableStmt(oldRelId,
16322 : : (AlterTableStmt *) stmt,
16323 : : cmdstring,
16324 : : &beforeStmts,
16325 : : &afterStmts);
16326 : 421 : querytree_list = list_concat(querytree_list, beforeStmts);
16327 : 421 : querytree_list = lappend(querytree_list, stmt);
16328 : 421 : querytree_list = list_concat(querytree_list, afterStmts);
16329 : : }
16330 [ + + ]: 70 : else if (IsA(stmt, CreateStatsStmt))
16331 : : {
16332 : : CreateStatsStmt *csstmt;
16333 : :
16334 : 57 : csstmt = transformStatsStmt(oldRelId, (CreateStatsStmt *) stmt, cmdstring);
16335 : 57 : csstmt->owner = ownerId;
16336 : :
16337 : 57 : querytree_list = lappend(querytree_list, csstmt);
16338 : : }
16339 : : else
16340 : 13 : querytree_list = lappend(querytree_list, stmt);
16341 : : }
16342 : :
16343 : : /* Caller should already have acquired whatever lock we need. */
16344 : 669 : rel = relation_open(oldRelId, NoLock);
16345 : :
16346 : : /*
16347 : : * Attach each generated command to the proper place in the work queue.
16348 : : * Note this could result in creation of entirely new work-queue entries.
16349 : : *
16350 : : * Also note that we have to tweak the command subtypes, because it turns
16351 : : * out that re-creation of indexes and constraints has to act a bit
16352 : : * differently from initial creation.
16353 : : */
16354 [ + - + + : 1338 : foreach(list_item, querytree_list)
+ + ]
16355 : : {
16356 : 669 : Node *stm = (Node *) lfirst(list_item);
16357 : : AlteredTableInfo *tab;
16358 : :
16359 : 669 : tab = ATGetQueueEntry(wqueue, rel);
16360 : :
16361 [ + + ]: 669 : if (IsA(stm, IndexStmt))
16362 : : {
16363 : 178 : IndexStmt *stmt = (IndexStmt *) stm;
16364 : : AlterTableCmd *newcmd;
16365 : :
16366 [ + + ]: 178 : if (!rewrite)
16367 : 53 : TryReuseIndex(oldId, stmt);
16368 : 178 : stmt->reset_default_tblspc = true;
16369 : : /* keep the index's comment */
16370 : 178 : stmt->idxcomment = GetComment(oldId, RelationRelationId, 0);
16371 : :
16372 : 178 : newcmd = makeNode(AlterTableCmd);
16373 : 178 : newcmd->subtype = AT_ReAddIndex;
16374 : 178 : newcmd->def = (Node *) stmt;
16375 : 178 : tab->subcmds[AT_PASS_OLD_INDEX] =
16376 : 178 : lappend(tab->subcmds[AT_PASS_OLD_INDEX], newcmd);
16377 : : }
16378 [ + + ]: 491 : else if (IsA(stm, AlterTableStmt))
16379 : : {
16380 : 421 : AlterTableStmt *stmt = (AlterTableStmt *) stm;
16381 : : ListCell *lcmd;
16382 : :
16383 [ + - + + : 842 : foreach(lcmd, stmt->cmds)
+ + ]
16384 : : {
16385 : 421 : AlterTableCmd *cmd = lfirst_node(AlterTableCmd, lcmd);
16386 : :
16387 [ + + ]: 421 : if (cmd->subtype == AT_AddIndex)
16388 : : {
16389 : : IndexStmt *indstmt;
16390 : : Oid indoid;
16391 : :
16392 : 152 : indstmt = castNode(IndexStmt, cmd->def);
16393 : 152 : indoid = get_constraint_index(oldId);
16394 : :
16395 [ + + ]: 152 : if (!rewrite)
16396 : 32 : TryReuseIndex(indoid, indstmt);
16397 : : /* keep any comment on the index */
16398 : 152 : indstmt->idxcomment = GetComment(indoid,
16399 : : RelationRelationId, 0);
16400 : 152 : indstmt->reset_default_tblspc = true;
16401 : :
16402 : 152 : cmd->subtype = AT_ReAddIndex;
16403 : 152 : tab->subcmds[AT_PASS_OLD_INDEX] =
16404 : 152 : lappend(tab->subcmds[AT_PASS_OLD_INDEX], cmd);
16405 : :
16406 : : /* recreate any comment on the constraint */
16407 : 152 : RebuildConstraintComment(tab,
16408 : : AT_PASS_OLD_INDEX,
16409 : : oldId,
16410 : : rel,
16411 : : NIL,
16412 : 152 : indstmt->idxname);
16413 : : }
16414 [ + - ]: 269 : else if (cmd->subtype == AT_AddConstraint)
16415 : : {
16416 : 269 : Constraint *con = castNode(Constraint, cmd->def);
16417 : :
16418 : 269 : con->old_pktable_oid = refRelId;
16419 : : /* rewriting neither side of a FK */
16420 [ + + ]: 269 : if (con->contype == CONSTR_FOREIGN &&
16421 [ + + + - ]: 48 : !rewrite && tab->rewrite == 0)
16422 : 4 : TryReuseForeignKey(oldId, con);
16423 : 269 : con->reset_default_tblspc = true;
16424 : 269 : cmd->subtype = AT_ReAddConstraint;
16425 : 269 : tab->subcmds[AT_PASS_OLD_CONSTR] =
16426 : 269 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
16427 : :
16428 : : /*
16429 : : * Recreate any comment on the constraint. If we have
16430 : : * recreated a primary key, then transformTableConstraint
16431 : : * has added an unnamed not-null constraint here; skip
16432 : : * this in that case.
16433 : : */
16434 [ + - ]: 269 : if (con->conname)
16435 : 269 : RebuildConstraintComment(tab,
16436 : : AT_PASS_OLD_CONSTR,
16437 : : oldId,
16438 : : rel,
16439 : : NIL,
16440 : 269 : con->conname);
16441 : : else
16442 : : Assert(con->contype == CONSTR_NOTNULL);
16443 : : }
16444 : : else
16445 [ # # ]: 0 : elog(ERROR, "unexpected statement subtype: %d",
16446 : : (int) cmd->subtype);
16447 : : }
16448 : : }
16449 [ + + ]: 70 : else if (IsA(stm, AlterDomainStmt))
16450 : : {
16451 : 13 : AlterDomainStmt *stmt = (AlterDomainStmt *) stm;
16452 : :
16453 [ + - ]: 13 : if (stmt->subtype == AD_AddConstraint)
16454 : : {
16455 : 13 : Constraint *con = castNode(Constraint, stmt->def);
16456 : 13 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
16457 : :
16458 : 13 : cmd->subtype = AT_ReAddDomainConstraint;
16459 : 13 : cmd->def = (Node *) stmt;
16460 : 13 : tab->subcmds[AT_PASS_OLD_CONSTR] =
16461 : 13 : lappend(tab->subcmds[AT_PASS_OLD_CONSTR], cmd);
16462 : :
16463 : : /* recreate any comment on the constraint */
16464 : 13 : RebuildConstraintComment(tab,
16465 : : AT_PASS_OLD_CONSTR,
16466 : : oldId,
16467 : : NULL,
16468 : : stmt->typeName,
16469 : 13 : con->conname);
16470 : : }
16471 : : else
16472 [ # # ]: 0 : elog(ERROR, "unexpected statement subtype: %d",
16473 : : (int) stmt->subtype);
16474 : : }
16475 [ + - ]: 57 : else if (IsA(stm, CreateStatsStmt))
16476 : : {
16477 : 57 : CreateStatsStmt *stmt = (CreateStatsStmt *) stm;
16478 : : AlterTableCmd *newcmd;
16479 : :
16480 : : /* keep the statistics object's comment */
16481 : 57 : stmt->stxcomment = GetComment(oldId, StatisticExtRelationId, 0);
16482 : :
16483 : 57 : newcmd = makeNode(AlterTableCmd);
16484 : 57 : newcmd->subtype = AT_ReAddStatistics;
16485 : 57 : newcmd->def = (Node *) stmt;
16486 : 57 : tab->subcmds[AT_PASS_MISC] =
16487 : 57 : lappend(tab->subcmds[AT_PASS_MISC], newcmd);
16488 : : }
16489 : : else
16490 [ # # ]: 0 : elog(ERROR, "unexpected statement type: %d",
16491 : : (int) nodeTag(stm));
16492 : : }
16493 : :
16494 : 669 : relation_close(rel, NoLock);
16495 : 669 : }
16496 : :
16497 : : /*
16498 : : * Subroutine for ATPostAlterTypeParse() to recreate any existing comment
16499 : : * for a table or domain constraint that is being rebuilt.
16500 : : *
16501 : : * objid is the OID of the constraint.
16502 : : * Pass "rel" for a table constraint, or "domname" (domain's qualified name
16503 : : * as a string list) for a domain constraint.
16504 : : * (We could dig that info, as well as the conname, out of the pg_constraint
16505 : : * entry; but callers already have them so might as well pass them.)
16506 : : */
16507 : : static void
16508 : 434 : RebuildConstraintComment(AlteredTableInfo *tab, AlterTablePass pass, Oid objid,
16509 : : Relation rel, List *domname,
16510 : : const char *conname)
16511 : : {
16512 : : CommentStmt *cmd;
16513 : : char *comment_str;
16514 : : AlterTableCmd *newcmd;
16515 : :
16516 : : /* Look for comment for object wanted, and leave if none */
16517 : 434 : comment_str = GetComment(objid, ConstraintRelationId, 0);
16518 [ + + ]: 434 : if (comment_str == NULL)
16519 : 374 : return;
16520 : :
16521 : : /* Build CommentStmt node, copying all input data for safety */
16522 : 60 : cmd = makeNode(CommentStmt);
16523 [ + + ]: 60 : if (rel)
16524 : : {
16525 : 52 : cmd->objtype = OBJECT_TABCONSTRAINT;
16526 : 52 : cmd->object = (Node *)
16527 : 52 : list_make3(makeString(get_namespace_name(RelationGetNamespace(rel))),
16528 : : makeString(pstrdup(RelationGetRelationName(rel))),
16529 : : makeString(pstrdup(conname)));
16530 : : }
16531 : : else
16532 : : {
16533 : 8 : cmd->objtype = OBJECT_DOMCONSTRAINT;
16534 : 8 : cmd->object = (Node *)
16535 : 8 : list_make2(makeTypeNameFromNameList(copyObject(domname)),
16536 : : makeString(pstrdup(conname)));
16537 : : }
16538 : 60 : cmd->comment = comment_str;
16539 : :
16540 : : /* Append it to list of commands */
16541 : 60 : newcmd = makeNode(AlterTableCmd);
16542 : 60 : newcmd->subtype = AT_ReAddComment;
16543 : 60 : newcmd->def = (Node *) cmd;
16544 : 60 : tab->subcmds[pass] = lappend(tab->subcmds[pass], newcmd);
16545 : : }
16546 : :
16547 : : /*
16548 : : * Subroutine for ATPostAlterTypeParse(). Calls out to CheckIndexCompatible()
16549 : : * for the real analysis, then mutates the IndexStmt based on that verdict.
16550 : : */
16551 : : static void
16552 : 85 : TryReuseIndex(Oid oldId, IndexStmt *stmt)
16553 : : {
16554 [ + + ]: 85 : if (CheckIndexCompatible(oldId,
16555 : 85 : stmt->accessMethod,
16556 : 85 : stmt->indexParams,
16557 : 85 : stmt->excludeOpNames,
16558 : 85 : stmt->iswithoutoverlaps))
16559 : : {
16560 : 69 : Relation irel = index_open(oldId, NoLock);
16561 : :
16562 : : /* If it's a partitioned index, there is no storage to share. */
16563 [ + + ]: 69 : if (irel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
16564 : : {
16565 : 49 : stmt->oldNumber = irel->rd_locator.relNumber;
16566 : 49 : stmt->oldCreateSubid = irel->rd_createSubid;
16567 : 49 : stmt->oldFirstRelfilelocatorSubid = irel->rd_firstRelfilelocatorSubid;
16568 : : }
16569 : 69 : index_close(irel, NoLock);
16570 : : }
16571 : 85 : }
16572 : :
16573 : : /*
16574 : : * Subroutine for ATPostAlterTypeParse().
16575 : : *
16576 : : * Stash the old P-F equality operator into the Constraint node, for possible
16577 : : * use by ATAddForeignKeyConstraint() in determining whether revalidation of
16578 : : * this constraint can be skipped.
16579 : : */
16580 : : static void
16581 : 4 : TryReuseForeignKey(Oid oldId, Constraint *con)
16582 : : {
16583 : : HeapTuple tup;
16584 : : Datum adatum;
16585 : : ArrayType *arr;
16586 : : Oid *rawarr;
16587 : : int numkeys;
16588 : : int i;
16589 : :
16590 : : Assert(con->contype == CONSTR_FOREIGN);
16591 : : Assert(con->old_conpfeqop == NIL); /* already prepared this node */
16592 : :
16593 : 4 : tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(oldId));
16594 [ - + ]: 4 : if (!HeapTupleIsValid(tup)) /* should not happen */
16595 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", oldId);
16596 : :
16597 : 4 : adatum = SysCacheGetAttrNotNull(CONSTROID, tup,
16598 : : Anum_pg_constraint_conpfeqop);
16599 : 4 : arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
16600 : 4 : numkeys = ARR_DIMS(arr)[0];
16601 : : /* test follows the one in ri_FetchConstraintInfo() */
16602 [ + - ]: 4 : if (ARR_NDIM(arr) != 1 ||
16603 [ + - ]: 4 : ARR_HASNULL(arr) ||
16604 [ - + ]: 4 : ARR_ELEMTYPE(arr) != OIDOID)
16605 [ # # ]: 0 : elog(ERROR, "conpfeqop is not a 1-D Oid array");
16606 [ - + ]: 4 : rawarr = (Oid *) ARR_DATA_PTR(arr);
16607 : :
16608 : : /* stash a List of the operator Oids in our Constraint node */
16609 [ + + ]: 8 : for (i = 0; i < numkeys; i++)
16610 : 4 : con->old_conpfeqop = lappend_oid(con->old_conpfeqop, rawarr[i]);
16611 : :
16612 : 4 : ReleaseSysCache(tup);
16613 : 4 : }
16614 : :
16615 : : /*
16616 : : * ALTER COLUMN .. OPTIONS ( ... )
16617 : : *
16618 : : * Returns the address of the modified column
16619 : : */
16620 : : static ObjectAddress
16621 : 94 : ATExecAlterColumnGenericOptions(Relation rel,
16622 : : const char *colName,
16623 : : List *options,
16624 : : LOCKMODE lockmode)
16625 : : {
16626 : : Relation ftrel;
16627 : : Relation attrel;
16628 : : ForeignServer *server;
16629 : : ForeignDataWrapper *fdw;
16630 : : HeapTuple tuple;
16631 : : HeapTuple newtuple;
16632 : : bool isnull;
16633 : : Datum repl_val[Natts_pg_attribute];
16634 : : bool repl_null[Natts_pg_attribute];
16635 : : bool repl_repl[Natts_pg_attribute];
16636 : : Datum datum;
16637 : : Form_pg_foreign_table fttableform;
16638 : : Form_pg_attribute atttableform;
16639 : : AttrNumber attnum;
16640 : : ObjectAddress address;
16641 : :
16642 [ - + ]: 94 : if (options == NIL)
16643 : 0 : return InvalidObjectAddress;
16644 : :
16645 : : /* First, determine FDW validator associated to the foreign table. */
16646 : 94 : ftrel = table_open(ForeignTableRelationId, AccessShareLock);
16647 : 94 : tuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(rel->rd_id));
16648 [ - + ]: 94 : if (!HeapTupleIsValid(tuple))
16649 [ # # ]: 0 : ereport(ERROR,
16650 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
16651 : : errmsg("foreign table \"%s\" does not exist",
16652 : : RelationGetRelationName(rel))));
16653 : 94 : fttableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
16654 : 94 : server = GetForeignServer(fttableform->ftserver);
16655 : 94 : fdw = GetForeignDataWrapper(server->fdwid);
16656 : :
16657 : 94 : table_close(ftrel, AccessShareLock);
16658 : 94 : ReleaseSysCache(tuple);
16659 : :
16660 : 94 : attrel = table_open(AttributeRelationId, RowExclusiveLock);
16661 : 94 : tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
16662 [ - + ]: 94 : if (!HeapTupleIsValid(tuple))
16663 [ # # ]: 0 : ereport(ERROR,
16664 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
16665 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
16666 : : colName, RelationGetRelationName(rel))));
16667 : :
16668 : : /* Prevent them from altering a system attribute */
16669 : 94 : atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
16670 : 94 : attnum = atttableform->attnum;
16671 [ + + ]: 94 : if (attnum <= 0)
16672 [ + - ]: 4 : ereport(ERROR,
16673 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16674 : : errmsg("cannot alter system column \"%s\"", colName)));
16675 : :
16676 : :
16677 : : /* Initialize buffers for new tuple values */
16678 : 90 : memset(repl_val, 0, sizeof(repl_val));
16679 : 90 : memset(repl_null, false, sizeof(repl_null));
16680 : 90 : memset(repl_repl, false, sizeof(repl_repl));
16681 : :
16682 : : /* Extract the current options */
16683 : 90 : datum = SysCacheGetAttr(ATTNAME,
16684 : : tuple,
16685 : : Anum_pg_attribute_attfdwoptions,
16686 : : &isnull);
16687 [ + + ]: 90 : if (isnull)
16688 : 84 : datum = PointerGetDatum(NULL);
16689 : :
16690 : : /* Transform the options */
16691 : 90 : datum = transformGenericOptions(AttributeRelationId,
16692 : : datum,
16693 : : options,
16694 : : fdw->fdwvalidator);
16695 : :
16696 [ + - ]: 90 : if (DatumGetPointer(datum) != NULL)
16697 : 90 : repl_val[Anum_pg_attribute_attfdwoptions - 1] = datum;
16698 : : else
16699 : 0 : repl_null[Anum_pg_attribute_attfdwoptions - 1] = true;
16700 : :
16701 : 90 : repl_repl[Anum_pg_attribute_attfdwoptions - 1] = true;
16702 : :
16703 : : /* Everything looks good - update the tuple */
16704 : :
16705 : 90 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrel),
16706 : : repl_val, repl_null, repl_repl);
16707 : :
16708 : 90 : CatalogTupleUpdate(attrel, &newtuple->t_self, newtuple);
16709 : :
16710 [ - + ]: 90 : InvokeObjectPostAlterHook(RelationRelationId,
16711 : : RelationGetRelid(rel),
16712 : : atttableform->attnum);
16713 : 90 : ObjectAddressSubSet(address, RelationRelationId,
16714 : : RelationGetRelid(rel), attnum);
16715 : :
16716 : 90 : ReleaseSysCache(tuple);
16717 : :
16718 : 90 : table_close(attrel, RowExclusiveLock);
16719 : :
16720 : 90 : heap_freetuple(newtuple);
16721 : :
16722 : 90 : return address;
16723 : : }
16724 : :
16725 : : /*
16726 : : * ALTER TABLE OWNER
16727 : : *
16728 : : * recursing is true if we are recursing from a table to its indexes,
16729 : : * sequences, or toast table. We don't allow the ownership of those things to
16730 : : * be changed separately from the parent table. Also, we can skip permission
16731 : : * checks (this is necessary not just an optimization, else we'd fail to
16732 : : * handle toast tables properly).
16733 : : *
16734 : : * recursing is also true if ALTER TYPE OWNER is calling us to fix up a
16735 : : * free-standing composite type.
16736 : : */
16737 : : void
16738 : 1346 : ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
16739 : : {
16740 : : Relation target_rel;
16741 : : Relation class_rel;
16742 : : HeapTuple tuple;
16743 : : Form_pg_class tuple_class;
16744 : :
16745 : : /*
16746 : : * Get exclusive lock till end of transaction on the target table. Use
16747 : : * relation_open so that we can work on indexes and sequences.
16748 : : */
16749 : 1346 : target_rel = relation_open(relationOid, lockmode);
16750 : :
16751 : : /* Get its pg_class tuple, too */
16752 : 1346 : class_rel = table_open(RelationRelationId, RowExclusiveLock);
16753 : :
16754 : 1346 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
16755 [ - + ]: 1346 : if (!HeapTupleIsValid(tuple))
16756 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relationOid);
16757 : 1346 : tuple_class = (Form_pg_class) GETSTRUCT(tuple);
16758 : :
16759 : : /* Can we change the ownership of this tuple? */
16760 [ + + + + : 1346 : switch (tuple_class->relkind)
+ + - ]
16761 : : {
16762 : 1096 : case RELKIND_RELATION:
16763 : : case RELKIND_VIEW:
16764 : : case RELKIND_MATVIEW:
16765 : : case RELKIND_FOREIGN_TABLE:
16766 : : case RELKIND_PARTITIONED_TABLE:
16767 : : /* ok to change owner */
16768 : 1096 : break;
16769 : 107 : case RELKIND_INDEX:
16770 [ - + ]: 107 : if (!recursing)
16771 : : {
16772 : : /*
16773 : : * Because ALTER INDEX OWNER used to be allowed, and in fact
16774 : : * is generated by old versions of pg_dump, we give a warning
16775 : : * and do nothing rather than erroring out. Also, to avoid
16776 : : * unnecessary chatter while restoring those old dumps, say
16777 : : * nothing at all if the command would be a no-op anyway.
16778 : : */
16779 [ # # ]: 0 : if (tuple_class->relowner != newOwnerId)
16780 [ # # ]: 0 : ereport(WARNING,
16781 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16782 : : errmsg("cannot change owner of index \"%s\"",
16783 : : NameStr(tuple_class->relname)),
16784 : : errhint("Change the ownership of the index's table instead.")));
16785 : : /* quick hack to exit via the no-op path */
16786 : 0 : newOwnerId = tuple_class->relowner;
16787 : : }
16788 : 107 : break;
16789 : 22 : case RELKIND_PARTITIONED_INDEX:
16790 [ + - ]: 22 : if (recursing)
16791 : 22 : break;
16792 [ # # ]: 0 : ereport(ERROR,
16793 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16794 : : errmsg("cannot change owner of index \"%s\"",
16795 : : NameStr(tuple_class->relname)),
16796 : : errhint("Change the ownership of the index's table instead.")));
16797 : : break;
16798 : 65 : case RELKIND_SEQUENCE:
16799 [ + + ]: 65 : if (!recursing &&
16800 [ - + ]: 35 : tuple_class->relowner != newOwnerId)
16801 : : {
16802 : : /* if it's an owned sequence, disallow changing it by itself */
16803 : : Oid tableId;
16804 : : int32 colId;
16805 : :
16806 [ # # # # ]: 0 : if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
16807 : 0 : sequenceIsOwned(relationOid, DEPENDENCY_INTERNAL, &tableId, &colId))
16808 [ # # ]: 0 : ereport(ERROR,
16809 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
16810 : : errmsg("cannot change owner of sequence \"%s\"",
16811 : : NameStr(tuple_class->relname)),
16812 : : errdetail("Sequence \"%s\" is linked to table \"%s\".",
16813 : : NameStr(tuple_class->relname),
16814 : : get_rel_name(tableId))));
16815 : : }
16816 : 65 : break;
16817 : 5 : case RELKIND_COMPOSITE_TYPE:
16818 [ + - ]: 5 : if (recursing)
16819 : 5 : break;
16820 [ # # ]: 0 : ereport(ERROR,
16821 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16822 : : errmsg("\"%s\" is a composite type",
16823 : : NameStr(tuple_class->relname)),
16824 : : /* translator: %s is an SQL ALTER command */
16825 : : errhint("Use %s instead.",
16826 : : "ALTER TYPE")));
16827 : : break;
16828 : 51 : case RELKIND_TOASTVALUE:
16829 [ + - ]: 51 : if (recursing)
16830 : 51 : break;
16831 : : pg_fallthrough;
16832 : : default:
16833 [ # # ]: 0 : ereport(ERROR,
16834 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16835 : : errmsg("cannot change owner of relation \"%s\"",
16836 : : NameStr(tuple_class->relname)),
16837 : : errdetail_relkind_not_supported(tuple_class->relkind)));
16838 : : }
16839 : :
16840 : : /*
16841 : : * If the new owner is the same as the existing owner, consider the
16842 : : * command to have succeeded. This is for dump restoration purposes.
16843 : : */
16844 [ + + ]: 1346 : if (tuple_class->relowner != newOwnerId)
16845 : : {
16846 : : Datum repl_val[Natts_pg_class];
16847 : : bool repl_null[Natts_pg_class];
16848 : : bool repl_repl[Natts_pg_class];
16849 : : Acl *newAcl;
16850 : : Datum aclDatum;
16851 : : bool isNull;
16852 : : HeapTuple newtuple;
16853 : :
16854 : : /* skip permission checks when recursing to index or toast table */
16855 [ + + ]: 457 : if (!recursing)
16856 : : {
16857 : : /* Superusers can always do it */
16858 [ + + ]: 232 : if (!superuser())
16859 : : {
16860 : 28 : Oid namespaceOid = tuple_class->relnamespace;
16861 : : AclResult aclresult;
16862 : :
16863 : : /* Otherwise, must be owner of the existing object */
16864 [ - + ]: 28 : if (!object_ownercheck(RelationRelationId, relationOid, GetUserId()))
16865 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relationOid)),
16866 : 0 : RelationGetRelationName(target_rel));
16867 : :
16868 : : /* Must be able to become new owner */
16869 : 28 : check_can_set_role(GetUserId(), newOwnerId);
16870 : :
16871 : : /* New owner must have CREATE privilege on namespace */
16872 : 20 : aclresult = object_aclcheck(NamespaceRelationId, namespaceOid, newOwnerId,
16873 : : ACL_CREATE);
16874 [ - + ]: 20 : if (aclresult != ACLCHECK_OK)
16875 : 0 : aclcheck_error(aclresult, OBJECT_SCHEMA,
16876 : 0 : get_namespace_name(namespaceOid));
16877 : : }
16878 : : }
16879 : :
16880 : 449 : memset(repl_null, false, sizeof(repl_null));
16881 : 449 : memset(repl_repl, false, sizeof(repl_repl));
16882 : :
16883 : 449 : repl_repl[Anum_pg_class_relowner - 1] = true;
16884 : 449 : repl_val[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(newOwnerId);
16885 : :
16886 : : /*
16887 : : * Determine the modified ACL for the new owner. This is only
16888 : : * necessary when the ACL is non-null.
16889 : : */
16890 : 449 : aclDatum = SysCacheGetAttr(RELOID, tuple,
16891 : : Anum_pg_class_relacl,
16892 : : &isNull);
16893 [ + + ]: 449 : if (!isNull)
16894 : : {
16895 : 36 : newAcl = aclnewowner(DatumGetAclP(aclDatum),
16896 : : tuple_class->relowner, newOwnerId);
16897 : 36 : repl_repl[Anum_pg_class_relacl - 1] = true;
16898 : 36 : repl_val[Anum_pg_class_relacl - 1] = PointerGetDatum(newAcl);
16899 : : }
16900 : :
16901 : 449 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(class_rel), repl_val, repl_null, repl_repl);
16902 : :
16903 : 449 : CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
16904 : :
16905 : 449 : heap_freetuple(newtuple);
16906 : :
16907 : : /*
16908 : : * We must similarly update any per-column ACLs to reflect the new
16909 : : * owner; for neatness reasons that's split out as a subroutine.
16910 : : */
16911 : 449 : change_owner_fix_column_acls(relationOid,
16912 : : tuple_class->relowner,
16913 : : newOwnerId);
16914 : :
16915 : : /*
16916 : : * Update owner dependency reference, if any. A composite type has
16917 : : * none, because it's tracked for the pg_type entry instead of here;
16918 : : * indexes and TOAST tables don't have their own entries either.
16919 : : */
16920 [ + + ]: 449 : if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
16921 [ + + ]: 444 : tuple_class->relkind != RELKIND_INDEX &&
16922 [ + + ]: 337 : tuple_class->relkind != RELKIND_PARTITIONED_INDEX &&
16923 [ + + ]: 315 : tuple_class->relkind != RELKIND_TOASTVALUE)
16924 : 264 : changeDependencyOnOwner(RelationRelationId, relationOid,
16925 : : newOwnerId);
16926 : :
16927 : : /*
16928 : : * Also change the ownership of the table's row type, if it has one
16929 : : */
16930 [ + + ]: 449 : if (OidIsValid(tuple_class->reltype))
16931 : 248 : AlterTypeOwnerInternal(tuple_class->reltype, newOwnerId);
16932 : :
16933 : : /*
16934 : : * If we are operating on a table or materialized view, also change
16935 : : * the ownership of any indexes and sequences that belong to the
16936 : : * relation, as well as its toast table (if it has one).
16937 : : */
16938 [ + + ]: 449 : if (tuple_class->relkind == RELKIND_RELATION ||
16939 [ + + ]: 253 : tuple_class->relkind == RELKIND_PARTITIONED_TABLE ||
16940 [ + - ]: 220 : tuple_class->relkind == RELKIND_MATVIEW ||
16941 [ + + ]: 220 : tuple_class->relkind == RELKIND_TOASTVALUE)
16942 : : {
16943 : : List *index_oid_list;
16944 : : ListCell *i;
16945 : :
16946 : : /* Find all the indexes belonging to this relation */
16947 : 280 : index_oid_list = RelationGetIndexList(target_rel);
16948 : :
16949 : : /* For each index, recursively change its ownership */
16950 [ + + + + : 409 : foreach(i, index_oid_list)
+ + ]
16951 : 129 : ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
16952 : :
16953 : 280 : list_free(index_oid_list);
16954 : : }
16955 : :
16956 : : /* If it has a toast table, recurse to change its ownership */
16957 [ + + ]: 449 : if (tuple_class->reltoastrelid != InvalidOid)
16958 : 51 : ATExecChangeOwner(tuple_class->reltoastrelid, newOwnerId,
16959 : : true, lockmode);
16960 : :
16961 : : /* If it has dependent sequences, recurse to change them too */
16962 : 449 : change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
16963 : : }
16964 : :
16965 [ - + ]: 1338 : InvokeObjectPostAlterHook(RelationRelationId, relationOid, 0);
16966 : :
16967 : 1338 : ReleaseSysCache(tuple);
16968 : 1338 : table_close(class_rel, RowExclusiveLock);
16969 : 1338 : relation_close(target_rel, NoLock);
16970 : 1338 : }
16971 : :
16972 : : /*
16973 : : * change_owner_fix_column_acls
16974 : : *
16975 : : * Helper function for ATExecChangeOwner. Scan the columns of the table
16976 : : * and fix any non-null column ACLs to reflect the new owner.
16977 : : */
16978 : : static void
16979 : 449 : change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
16980 : : {
16981 : : Relation attRelation;
16982 : : SysScanDesc scan;
16983 : : ScanKeyData key[1];
16984 : : HeapTuple attributeTuple;
16985 : :
16986 : 449 : attRelation = table_open(AttributeRelationId, RowExclusiveLock);
16987 : 449 : ScanKeyInit(&key[0],
16988 : : Anum_pg_attribute_attrelid,
16989 : : BTEqualStrategyNumber, F_OIDEQ,
16990 : : ObjectIdGetDatum(relationOid));
16991 : 449 : scan = systable_beginscan(attRelation, AttributeRelidNumIndexId,
16992 : : true, NULL, 1, key);
16993 [ + + ]: 3145 : while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
16994 : : {
16995 : 2696 : Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
16996 : : Datum repl_val[Natts_pg_attribute];
16997 : : bool repl_null[Natts_pg_attribute];
16998 : : bool repl_repl[Natts_pg_attribute];
16999 : : Acl *newAcl;
17000 : : Datum aclDatum;
17001 : : bool isNull;
17002 : : HeapTuple newtuple;
17003 : :
17004 : : /* Ignore dropped columns */
17005 [ - + ]: 2696 : if (att->attisdropped)
17006 : 2695 : continue;
17007 : :
17008 : 2696 : aclDatum = heap_getattr(attributeTuple,
17009 : : Anum_pg_attribute_attacl,
17010 : : RelationGetDescr(attRelation),
17011 : : &isNull);
17012 : : /* Null ACLs do not require changes */
17013 [ + + ]: 2696 : if (isNull)
17014 : 2695 : continue;
17015 : :
17016 : 1 : memset(repl_null, false, sizeof(repl_null));
17017 : 1 : memset(repl_repl, false, sizeof(repl_repl));
17018 : :
17019 : 1 : newAcl = aclnewowner(DatumGetAclP(aclDatum),
17020 : : oldOwnerId, newOwnerId);
17021 : 1 : repl_repl[Anum_pg_attribute_attacl - 1] = true;
17022 : 1 : repl_val[Anum_pg_attribute_attacl - 1] = PointerGetDatum(newAcl);
17023 : :
17024 : 1 : newtuple = heap_modify_tuple(attributeTuple,
17025 : : RelationGetDescr(attRelation),
17026 : : repl_val, repl_null, repl_repl);
17027 : :
17028 : 1 : CatalogTupleUpdate(attRelation, &newtuple->t_self, newtuple);
17029 : :
17030 : 1 : heap_freetuple(newtuple);
17031 : : }
17032 : 449 : systable_endscan(scan);
17033 : 449 : table_close(attRelation, RowExclusiveLock);
17034 : 449 : }
17035 : :
17036 : : /*
17037 : : * change_owner_recurse_to_sequences
17038 : : *
17039 : : * Helper function for ATExecChangeOwner. Examines pg_depend searching
17040 : : * for sequences that are dependent on serial columns, and changes their
17041 : : * ownership.
17042 : : */
17043 : : static void
17044 : 449 : change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
17045 : : {
17046 : : Relation depRel;
17047 : : SysScanDesc scan;
17048 : : ScanKeyData key[2];
17049 : : HeapTuple tup;
17050 : :
17051 : : /*
17052 : : * SERIAL sequences are those having an auto dependency on one of the
17053 : : * table's columns (we don't care *which* column, exactly).
17054 : : */
17055 : 449 : depRel = table_open(DependRelationId, AccessShareLock);
17056 : :
17057 : 449 : ScanKeyInit(&key[0],
17058 : : Anum_pg_depend_refclassid,
17059 : : BTEqualStrategyNumber, F_OIDEQ,
17060 : : ObjectIdGetDatum(RelationRelationId));
17061 : 449 : ScanKeyInit(&key[1],
17062 : : Anum_pg_depend_refobjid,
17063 : : BTEqualStrategyNumber, F_OIDEQ,
17064 : : ObjectIdGetDatum(relationOid));
17065 : : /* we leave refobjsubid unspecified */
17066 : :
17067 : 449 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
17068 : : NULL, 2, key);
17069 : :
17070 [ + + ]: 1295 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
17071 : : {
17072 : 846 : Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
17073 : : Relation seqRel;
17074 : :
17075 : : /* skip dependencies other than auto dependencies on columns */
17076 [ + + ]: 846 : if (depForm->refobjsubid == 0 ||
17077 [ + + ]: 380 : depForm->classid != RelationRelationId ||
17078 [ + - ]: 147 : depForm->objsubid != 0 ||
17079 [ + + - + ]: 147 : !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
17080 : 699 : continue;
17081 : :
17082 : : /* Use relation_open just in case it's an index */
17083 : 147 : seqRel = relation_open(depForm->objid, lockmode);
17084 : :
17085 : : /* skip non-sequence relations */
17086 [ + + ]: 147 : if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
17087 : : {
17088 : : /* No need to keep the lock */
17089 : 130 : relation_close(seqRel, lockmode);
17090 : 130 : continue;
17091 : : }
17092 : :
17093 : : /* We don't need to close the sequence while we alter it. */
17094 : 17 : ATExecChangeOwner(depForm->objid, newOwnerId, true, lockmode);
17095 : :
17096 : : /* Now we can close it. Keep the lock till end of transaction. */
17097 : 17 : relation_close(seqRel, NoLock);
17098 : : }
17099 : :
17100 : 449 : systable_endscan(scan);
17101 : :
17102 : 449 : relation_close(depRel, AccessShareLock);
17103 : 449 : }
17104 : :
17105 : : /*
17106 : : * ALTER TABLE CLUSTER ON
17107 : : *
17108 : : * The only thing we have to do is to change the indisclustered bits.
17109 : : *
17110 : : * Return the address of the new clustering index.
17111 : : */
17112 : : static ObjectAddress
17113 : 39 : ATExecClusterOn(Relation rel, const char *indexName, LOCKMODE lockmode)
17114 : : {
17115 : : Oid indexOid;
17116 : : ObjectAddress address;
17117 : :
17118 : 39 : indexOid = get_relname_relid(indexName, rel->rd_rel->relnamespace);
17119 : :
17120 [ - + ]: 39 : if (!OidIsValid(indexOid))
17121 [ # # ]: 0 : ereport(ERROR,
17122 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
17123 : : errmsg("index \"%s\" for table \"%s\" does not exist",
17124 : : indexName, RelationGetRelationName(rel))));
17125 : :
17126 : : /* Check index is valid to cluster on */
17127 : 39 : check_index_is_clusterable(rel, indexOid, lockmode);
17128 : :
17129 : : /* And do the work */
17130 : 39 : mark_index_clustered(rel, indexOid, false);
17131 : :
17132 : 39 : ObjectAddressSet(address,
17133 : : RelationRelationId, indexOid);
17134 : :
17135 : 39 : return address;
17136 : : }
17137 : :
17138 : : /*
17139 : : * ALTER TABLE SET WITHOUT CLUSTER
17140 : : *
17141 : : * We have to find any indexes on the table that have indisclustered bit
17142 : : * set and turn it off.
17143 : : */
17144 : : static void
17145 : 8 : ATExecDropCluster(Relation rel, LOCKMODE lockmode)
17146 : : {
17147 : 8 : mark_index_clustered(rel, InvalidOid, false);
17148 : 8 : }
17149 : :
17150 : : /*
17151 : : * Preparation phase for SET ACCESS METHOD
17152 : : *
17153 : : * Check that the access method exists and determine whether a change is
17154 : : * actually needed.
17155 : : */
17156 : : static void
17157 : 73 : ATPrepSetAccessMethod(AlteredTableInfo *tab, Relation rel, const char *amname)
17158 : : {
17159 : : Oid amoid;
17160 : :
17161 : : /*
17162 : : * Look up the access method name and check that it differs from the
17163 : : * table's current AM. If DEFAULT was specified for a partitioned table
17164 : : * (amname is NULL), set it to InvalidOid to reset the catalogued AM.
17165 : : */
17166 [ + + ]: 73 : if (amname != NULL)
17167 : 49 : amoid = get_table_am_oid(amname, false);
17168 [ + + ]: 24 : else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
17169 : 12 : amoid = InvalidOid;
17170 : : else
17171 : 12 : amoid = get_table_am_oid(default_table_access_method, false);
17172 : :
17173 : : /* if it's a match, phase 3 doesn't need to do anything */
17174 [ + + ]: 73 : if (rel->rd_rel->relam == amoid)
17175 : 8 : return;
17176 : :
17177 : : /* Save info for Phase 3 to do the real work */
17178 : 65 : tab->rewrite |= AT_REWRITE_ACCESS_METHOD;
17179 : 65 : tab->newAccessMethod = amoid;
17180 : 65 : tab->chgAccessMethod = true;
17181 : : }
17182 : :
17183 : : /*
17184 : : * Special handling of ALTER TABLE SET ACCESS METHOD for relations with no
17185 : : * storage that have an interest in preserving AM.
17186 : : *
17187 : : * Since these have no storage, setting the access method is a catalog only
17188 : : * operation.
17189 : : */
17190 : : static void
17191 : 29 : ATExecSetAccessMethodNoStorage(Relation rel, Oid newAccessMethodId)
17192 : : {
17193 : : Relation pg_class;
17194 : : Oid oldAccessMethodId;
17195 : : HeapTuple tuple;
17196 : : Form_pg_class rd_rel;
17197 : 29 : Oid reloid = RelationGetRelid(rel);
17198 : :
17199 : : /*
17200 : : * Shouldn't be called on relations having storage; these are processed in
17201 : : * phase 3.
17202 : : */
17203 : : Assert(!RELKIND_HAS_STORAGE(rel->rd_rel->relkind));
17204 : :
17205 : : /* Get a modifiable copy of the relation's pg_class row. */
17206 : 29 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
17207 : :
17208 : 29 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(reloid));
17209 [ - + ]: 29 : if (!HeapTupleIsValid(tuple))
17210 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", reloid);
17211 : 29 : rd_rel = (Form_pg_class) GETSTRUCT(tuple);
17212 : :
17213 : : /* Update the pg_class row. */
17214 : 29 : oldAccessMethodId = rd_rel->relam;
17215 : 29 : rd_rel->relam = newAccessMethodId;
17216 : :
17217 : : /* Leave if no update required */
17218 [ - + ]: 29 : if (rd_rel->relam == oldAccessMethodId)
17219 : : {
17220 : 0 : heap_freetuple(tuple);
17221 : 0 : table_close(pg_class, RowExclusiveLock);
17222 : 0 : return;
17223 : : }
17224 : :
17225 : 29 : CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
17226 : :
17227 : : /*
17228 : : * Update the dependency on the new access method. No dependency is added
17229 : : * if the new access method is InvalidOid (default case). Be very careful
17230 : : * that this has to compare the previous value stored in pg_class with the
17231 : : * new one.
17232 : : */
17233 [ + + + - ]: 29 : if (!OidIsValid(oldAccessMethodId) && OidIsValid(rd_rel->relam))
17234 : 13 : {
17235 : : ObjectAddress relobj,
17236 : : referenced;
17237 : :
17238 : : /*
17239 : : * New access method is defined and there was no dependency
17240 : : * previously, so record a new one.
17241 : : */
17242 : 13 : ObjectAddressSet(relobj, RelationRelationId, reloid);
17243 : 13 : ObjectAddressSet(referenced, AccessMethodRelationId, rd_rel->relam);
17244 : 13 : recordDependencyOn(&relobj, &referenced, DEPENDENCY_NORMAL);
17245 : : }
17246 [ + - ]: 16 : else if (OidIsValid(oldAccessMethodId) &&
17247 [ + + ]: 16 : !OidIsValid(rd_rel->relam))
17248 : : {
17249 : : /*
17250 : : * There was an access method defined, and no new one, so just remove
17251 : : * the existing dependency.
17252 : : */
17253 : 8 : deleteDependencyRecordsForClass(RelationRelationId, reloid,
17254 : : AccessMethodRelationId,
17255 : : DEPENDENCY_NORMAL);
17256 : : }
17257 : : else
17258 : : {
17259 : : Assert(OidIsValid(oldAccessMethodId) &&
17260 : : OidIsValid(rd_rel->relam));
17261 : :
17262 : : /* Both are valid, so update the dependency */
17263 : 8 : changeDependencyFor(RelationRelationId, reloid,
17264 : : AccessMethodRelationId,
17265 : : oldAccessMethodId, rd_rel->relam);
17266 : : }
17267 : :
17268 : : /* make the relam and dependency changes visible */
17269 : 29 : CommandCounterIncrement();
17270 : :
17271 [ - + ]: 29 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
17272 : :
17273 : 29 : heap_freetuple(tuple);
17274 : 29 : table_close(pg_class, RowExclusiveLock);
17275 : : }
17276 : :
17277 : : /*
17278 : : * ALTER TABLE SET TABLESPACE
17279 : : */
17280 : : static void
17281 : 104 : ATPrepSetTableSpace(AlteredTableInfo *tab, Relation rel, const char *tablespacename, LOCKMODE lockmode)
17282 : : {
17283 : : Oid tablespaceId;
17284 : :
17285 : : /* Check that the tablespace exists */
17286 : 104 : tablespaceId = get_tablespace_oid(tablespacename, false);
17287 : :
17288 : : /* Check permissions except when moving to database's default */
17289 [ + - + + ]: 104 : if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
17290 : : {
17291 : : AclResult aclresult;
17292 : :
17293 : 49 : aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, GetUserId(), ACL_CREATE);
17294 [ - + ]: 49 : if (aclresult != ACLCHECK_OK)
17295 : 0 : aclcheck_error(aclresult, OBJECT_TABLESPACE, tablespacename);
17296 : : }
17297 : :
17298 : : /* Save info for Phase 3 to do the real work */
17299 [ - + ]: 104 : if (OidIsValid(tab->newTableSpace))
17300 [ # # ]: 0 : ereport(ERROR,
17301 : : (errcode(ERRCODE_SYNTAX_ERROR),
17302 : : errmsg("cannot have multiple SET TABLESPACE subcommands")));
17303 : :
17304 : 104 : tab->newTableSpace = tablespaceId;
17305 : 104 : }
17306 : :
17307 : : /*
17308 : : * Set, reset, or replace reloptions.
17309 : : */
17310 : : static void
17311 : 674 : ATExecSetRelOptions(Relation rel, List *defList, AlterTableType operation,
17312 : : LOCKMODE lockmode)
17313 : : {
17314 : : Oid relid;
17315 : : Relation pgclass;
17316 : : HeapTuple tuple;
17317 : : HeapTuple newtuple;
17318 : : Datum datum;
17319 : : Datum newOptions;
17320 : : Datum repl_val[Natts_pg_class];
17321 : : bool repl_null[Natts_pg_class];
17322 : : bool repl_repl[Natts_pg_class];
17323 : 674 : const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
17324 : :
17325 [ + + - + ]: 674 : if (defList == NIL && operation != AT_ReplaceRelOptions)
17326 : 0 : return; /* nothing to do */
17327 : :
17328 : 674 : pgclass = table_open(RelationRelationId, RowExclusiveLock);
17329 : :
17330 : : /* Fetch heap tuple */
17331 : 674 : relid = RelationGetRelid(rel);
17332 : 674 : tuple = SearchSysCacheLocked1(RELOID, ObjectIdGetDatum(relid));
17333 [ - + ]: 674 : if (!HeapTupleIsValid(tuple))
17334 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
17335 : :
17336 [ + + ]: 674 : if (operation == AT_ReplaceRelOptions)
17337 : : {
17338 : : /*
17339 : : * If we're supposed to replace the reloptions list, we just pretend
17340 : : * there were none before.
17341 : : */
17342 : 137 : datum = (Datum) 0;
17343 : : }
17344 : : else
17345 : : {
17346 : : bool isnull;
17347 : :
17348 : : /* Get the old reloptions */
17349 : 537 : datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
17350 : : &isnull);
17351 [ + + ]: 537 : if (isnull)
17352 : 301 : datum = (Datum) 0;
17353 : : }
17354 : :
17355 : : /* Generate new proposed reloptions (text array) */
17356 : 674 : newOptions = transformRelOptions(datum, defList, NULL, validnsps, false,
17357 : : operation == AT_ResetRelOptions);
17358 : :
17359 : : /* Validate */
17360 [ + + + + : 670 : switch (rel->rd_rel->relkind)
- ]
17361 : : {
17362 : 390 : case RELKIND_RELATION:
17363 : : case RELKIND_MATVIEW:
17364 : 390 : (void) heap_reloptions(rel->rd_rel->relkind, newOptions, true);
17365 : 390 : break;
17366 : 4 : case RELKIND_PARTITIONED_TABLE:
17367 : 4 : (void) partitioned_table_reloptions(newOptions, true);
17368 : 0 : break;
17369 : 205 : case RELKIND_VIEW:
17370 : 205 : (void) view_reloptions(newOptions, true);
17371 : 193 : break;
17372 : 71 : case RELKIND_INDEX:
17373 : : case RELKIND_PARTITIONED_INDEX:
17374 : 71 : (void) index_reloptions(rel->rd_indam->amoptions, newOptions, true);
17375 : 57 : break;
17376 : 0 : case RELKIND_TOASTVALUE:
17377 : : /* fall through to error -- shouldn't ever get here */
17378 : : default:
17379 [ # # ]: 0 : ereport(ERROR,
17380 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17381 : : errmsg("cannot set options for relation \"%s\"",
17382 : : RelationGetRelationName(rel)),
17383 : : errdetail_relkind_not_supported(rel->rd_rel->relkind)));
17384 : : break;
17385 : : }
17386 : :
17387 : : /* Special-case validation of view options */
17388 [ + + ]: 640 : if (rel->rd_rel->relkind == RELKIND_VIEW)
17389 : : {
17390 : 193 : Query *view_query = get_view_query(rel);
17391 : 193 : List *view_options = untransformRelOptions(newOptions);
17392 : : ListCell *cell;
17393 : 193 : bool check_option = false;
17394 : :
17395 [ + + + + : 261 : foreach(cell, view_options)
+ + ]
17396 : : {
17397 : 68 : DefElem *defel = (DefElem *) lfirst(cell);
17398 : :
17399 [ + + ]: 68 : if (strcmp(defel->defname, "check_option") == 0)
17400 : 16 : check_option = true;
17401 : : }
17402 : :
17403 : : /*
17404 : : * If the check option is specified, look to see if the view is
17405 : : * actually auto-updatable or not.
17406 : : */
17407 [ + + ]: 193 : if (check_option)
17408 : : {
17409 : : const char *view_updatable_error =
17410 : 16 : view_query_is_auto_updatable(view_query, true);
17411 : :
17412 [ - + ]: 16 : if (view_updatable_error)
17413 [ # # ]: 0 : ereport(ERROR,
17414 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
17415 : : errmsg("WITH CHECK OPTION is supported only on automatically updatable views"),
17416 : : errhint("%s", _(view_updatable_error))));
17417 : : }
17418 : : }
17419 : :
17420 : : /*
17421 : : * All we need do here is update the pg_class row; the new options will be
17422 : : * propagated into relcaches during post-commit cache inval.
17423 : : */
17424 : 640 : memset(repl_val, 0, sizeof(repl_val));
17425 : 640 : memset(repl_null, false, sizeof(repl_null));
17426 : 640 : memset(repl_repl, false, sizeof(repl_repl));
17427 : :
17428 [ + + ]: 640 : if (newOptions != (Datum) 0)
17429 : 426 : repl_val[Anum_pg_class_reloptions - 1] = newOptions;
17430 : : else
17431 : 214 : repl_null[Anum_pg_class_reloptions - 1] = true;
17432 : :
17433 : 640 : repl_repl[Anum_pg_class_reloptions - 1] = true;
17434 : :
17435 : 640 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
17436 : : repl_val, repl_null, repl_repl);
17437 : :
17438 : 640 : CatalogTupleUpdate(pgclass, &newtuple->t_self, newtuple);
17439 : 640 : UnlockTuple(pgclass, &tuple->t_self, InplaceUpdateTupleLock);
17440 : :
17441 [ - + ]: 640 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
17442 : :
17443 : 640 : heap_freetuple(newtuple);
17444 : :
17445 : 640 : ReleaseSysCache(tuple);
17446 : :
17447 : : /* repeat the whole exercise for the toast table, if there's one */
17448 [ + + ]: 640 : if (OidIsValid(rel->rd_rel->reltoastrelid))
17449 : : {
17450 : : Relation toastrel;
17451 : 221 : Oid toastid = rel->rd_rel->reltoastrelid;
17452 : :
17453 : 221 : toastrel = table_open(toastid, lockmode);
17454 : :
17455 : : /* Fetch heap tuple */
17456 : 221 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(toastid));
17457 [ - + ]: 221 : if (!HeapTupleIsValid(tuple))
17458 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", toastid);
17459 : :
17460 [ - + ]: 221 : if (operation == AT_ReplaceRelOptions)
17461 : : {
17462 : : /*
17463 : : * If we're supposed to replace the reloptions list, we just
17464 : : * pretend there were none before.
17465 : : */
17466 : 0 : datum = (Datum) 0;
17467 : : }
17468 : : else
17469 : : {
17470 : : bool isnull;
17471 : :
17472 : : /* Get the old reloptions */
17473 : 221 : datum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
17474 : : &isnull);
17475 [ + + ]: 221 : if (isnull)
17476 : 197 : datum = (Datum) 0;
17477 : : }
17478 : :
17479 : 221 : newOptions = transformRelOptions(datum, defList, "toast", validnsps,
17480 : : false, operation == AT_ResetRelOptions);
17481 : :
17482 : 221 : (void) heap_reloptions(RELKIND_TOASTVALUE, newOptions, true);
17483 : :
17484 : 221 : memset(repl_val, 0, sizeof(repl_val));
17485 : 221 : memset(repl_null, false, sizeof(repl_null));
17486 : 221 : memset(repl_repl, false, sizeof(repl_repl));
17487 : :
17488 [ + + ]: 221 : if (newOptions != (Datum) 0)
17489 : 28 : repl_val[Anum_pg_class_reloptions - 1] = newOptions;
17490 : : else
17491 : 193 : repl_null[Anum_pg_class_reloptions - 1] = true;
17492 : :
17493 : 221 : repl_repl[Anum_pg_class_reloptions - 1] = true;
17494 : :
17495 : 221 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(pgclass),
17496 : : repl_val, repl_null, repl_repl);
17497 : :
17498 : 221 : CatalogTupleUpdate(pgclass, &newtuple->t_self, newtuple);
17499 : :
17500 [ - + ]: 221 : InvokeObjectPostAlterHookArg(RelationRelationId,
17501 : : RelationGetRelid(toastrel), 0,
17502 : : InvalidOid, true);
17503 : :
17504 : 221 : heap_freetuple(newtuple);
17505 : :
17506 : 221 : ReleaseSysCache(tuple);
17507 : :
17508 : 221 : table_close(toastrel, NoLock);
17509 : : }
17510 : :
17511 : 640 : table_close(pgclass, RowExclusiveLock);
17512 : : }
17513 : :
17514 : : /*
17515 : : * Execute ALTER TABLE SET TABLESPACE for cases where there is no tuple
17516 : : * rewriting to be done, so we just want to copy the data as fast as possible.
17517 : : */
17518 : : static void
17519 : 114 : ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
17520 : : {
17521 : : Relation rel;
17522 : : Oid reltoastrelid;
17523 : : RelFileNumber newrelfilenumber;
17524 : : RelFileLocator newrlocator;
17525 : 114 : List *reltoastidxids = NIL;
17526 : : ListCell *lc;
17527 : :
17528 : : /*
17529 : : * Need lock here in case we are recursing to toast table or index
17530 : : */
17531 : 114 : rel = relation_open(tableOid, lockmode);
17532 : :
17533 : : /* Check first if relation can be moved to new tablespace */
17534 [ + + ]: 114 : if (!CheckRelationTableSpaceMove(rel, newTableSpace))
17535 : : {
17536 [ - + ]: 5 : InvokeObjectPostAlterHook(RelationRelationId,
17537 : : RelationGetRelid(rel), 0);
17538 : 5 : relation_close(rel, NoLock);
17539 : 5 : return;
17540 : : }
17541 : :
17542 : 109 : reltoastrelid = rel->rd_rel->reltoastrelid;
17543 : : /* Fetch the list of indexes on toast relation if necessary */
17544 [ + + ]: 109 : if (OidIsValid(reltoastrelid))
17545 : : {
17546 : 17 : Relation toastRel = relation_open(reltoastrelid, lockmode);
17547 : :
17548 : 17 : reltoastidxids = RelationGetIndexList(toastRel);
17549 : 17 : relation_close(toastRel, lockmode);
17550 : : }
17551 : :
17552 : : /*
17553 : : * Relfilenumbers are not unique in databases across tablespaces, so we
17554 : : * need to allocate a new one in the new tablespace.
17555 : : */
17556 : 109 : newrelfilenumber = GetNewRelFileNumber(newTableSpace, NULL,
17557 : 109 : rel->rd_rel->relpersistence);
17558 : :
17559 : : /* Open old and new relation */
17560 : 109 : newrlocator = rel->rd_locator;
17561 : 109 : newrlocator.relNumber = newrelfilenumber;
17562 : 109 : newrlocator.spcOid = newTableSpace;
17563 : :
17564 : : /* hand off to AM to actually create new rel storage and copy the data */
17565 [ + + ]: 109 : if (rel->rd_rel->relkind == RELKIND_INDEX)
17566 : : {
17567 : 40 : index_copy_data(rel, newrlocator);
17568 : : }
17569 : : else
17570 : : {
17571 : : Assert(RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind));
17572 : 69 : table_relation_copy_data(rel, &newrlocator);
17573 : : }
17574 : :
17575 : : /*
17576 : : * Update the pg_class row.
17577 : : *
17578 : : * NB: This wouldn't work if ATExecSetTableSpace() were allowed to be
17579 : : * executed on pg_class or its indexes (the above copy wouldn't contain
17580 : : * the updated pg_class entry), but that's forbidden with
17581 : : * CheckRelationTableSpaceMove().
17582 : : */
17583 : 109 : SetRelationTableSpace(rel, newTableSpace, newrelfilenumber);
17584 : :
17585 [ - + ]: 109 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
17586 : :
17587 : 109 : RelationAssumeNewRelfilelocator(rel);
17588 : :
17589 : 109 : relation_close(rel, NoLock);
17590 : :
17591 : : /* Make sure the reltablespace change is visible */
17592 : 109 : CommandCounterIncrement();
17593 : :
17594 : : /* Move associated toast relation and/or indexes, too */
17595 [ + + ]: 109 : if (OidIsValid(reltoastrelid))
17596 : 17 : ATExecSetTableSpace(reltoastrelid, newTableSpace, lockmode);
17597 [ + + + + : 126 : foreach(lc, reltoastidxids)
+ + ]
17598 : 17 : ATExecSetTableSpace(lfirst_oid(lc), newTableSpace, lockmode);
17599 : :
17600 : : /* Clean up */
17601 : 109 : list_free(reltoastidxids);
17602 : : }
17603 : :
17604 : : /*
17605 : : * Special handling of ALTER TABLE SET TABLESPACE for relations with no
17606 : : * storage that have an interest in preserving tablespace.
17607 : : *
17608 : : * Since these have no storage the tablespace can be updated with a simple
17609 : : * metadata only operation to update the tablespace.
17610 : : */
17611 : : static void
17612 : 24 : ATExecSetTableSpaceNoStorage(Relation rel, Oid newTableSpace)
17613 : : {
17614 : : /*
17615 : : * Shouldn't be called on relations having storage; these are processed in
17616 : : * phase 3.
17617 : : */
17618 : : Assert(!RELKIND_HAS_STORAGE(rel->rd_rel->relkind));
17619 : :
17620 : : /* check if relation can be moved to its new tablespace */
17621 [ - + ]: 24 : if (!CheckRelationTableSpaceMove(rel, newTableSpace))
17622 : : {
17623 [ # # ]: 0 : InvokeObjectPostAlterHook(RelationRelationId,
17624 : : RelationGetRelid(rel),
17625 : : 0);
17626 : 0 : return;
17627 : : }
17628 : :
17629 : : /* Update can be done, so change reltablespace */
17630 : 20 : SetRelationTableSpace(rel, newTableSpace, InvalidOid);
17631 : :
17632 [ - + ]: 20 : InvokeObjectPostAlterHook(RelationRelationId, RelationGetRelid(rel), 0);
17633 : :
17634 : : /* Make sure the reltablespace change is visible */
17635 : 20 : CommandCounterIncrement();
17636 : : }
17637 : :
17638 : : /*
17639 : : * Alter Table ALL ... SET TABLESPACE
17640 : : *
17641 : : * Allows a user to move all objects of some type in a given tablespace in the
17642 : : * current database to another tablespace. Objects can be chosen based on the
17643 : : * owner of the object also, to allow users to move only their objects.
17644 : : * The user must have CREATE rights on the new tablespace, as usual. The main
17645 : : * permissions handling is done by the lower-level table move function.
17646 : : *
17647 : : * All to-be-moved objects are locked first. If NOWAIT is specified and the
17648 : : * lock can't be acquired then we ereport(ERROR).
17649 : : */
17650 : : Oid
17651 : 16 : AlterTableMoveAll(AlterTableMoveAllStmt *stmt)
17652 : : {
17653 : 16 : List *relations = NIL;
17654 : : ListCell *l;
17655 : : ScanKeyData key[1];
17656 : : Relation rel;
17657 : : TableScanDesc scan;
17658 : : HeapTuple tuple;
17659 : : Oid orig_tablespaceoid;
17660 : : Oid new_tablespaceoid;
17661 : 16 : List *role_oids = roleSpecsToIds(stmt->roles);
17662 : :
17663 : : /* Ensure we were not asked to move something we can't */
17664 [ + + + + ]: 16 : if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
17665 [ - + ]: 6 : stmt->objtype != OBJECT_MATVIEW)
17666 [ # # ]: 0 : ereport(ERROR,
17667 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
17668 : : errmsg("only tables, indexes, and materialized views exist in tablespaces")));
17669 : :
17670 : : /* Get the orig and new tablespace OIDs */
17671 : 16 : orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
17672 : 16 : new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
17673 : :
17674 : : /* Can't move shared relations in to or out of pg_global */
17675 : : /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
17676 [ + - - + ]: 16 : if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
17677 : : new_tablespaceoid == GLOBALTABLESPACE_OID)
17678 [ # # ]: 0 : ereport(ERROR,
17679 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
17680 : : errmsg("cannot move relations in to or out of pg_global tablespace")));
17681 : :
17682 : : /*
17683 : : * Must have CREATE rights on the new tablespace, unless it is the
17684 : : * database default tablespace (which all users implicitly have CREATE
17685 : : * rights on).
17686 : : */
17687 [ + - + + ]: 16 : if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
17688 : : {
17689 : : AclResult aclresult;
17690 : :
17691 : 1 : aclresult = object_aclcheck(TableSpaceRelationId, new_tablespaceoid, GetUserId(),
17692 : : ACL_CREATE);
17693 [ - + ]: 1 : if (aclresult != ACLCHECK_OK)
17694 : 0 : aclcheck_error(aclresult, OBJECT_TABLESPACE,
17695 : 0 : get_tablespace_name(new_tablespaceoid));
17696 : : }
17697 : :
17698 : : /*
17699 : : * Now that the checks are done, check if we should set either to
17700 : : * InvalidOid because it is our database's default tablespace.
17701 : : */
17702 [ + + ]: 16 : if (orig_tablespaceoid == MyDatabaseTableSpace)
17703 : 1 : orig_tablespaceoid = InvalidOid;
17704 : :
17705 [ + + ]: 16 : if (new_tablespaceoid == MyDatabaseTableSpace)
17706 : 15 : new_tablespaceoid = InvalidOid;
17707 : :
17708 : : /* no-op */
17709 [ - + ]: 16 : if (orig_tablespaceoid == new_tablespaceoid)
17710 : 0 : return new_tablespaceoid;
17711 : :
17712 : : /*
17713 : : * Walk the list of objects in the tablespace and move them. This will
17714 : : * only find objects in our database, of course.
17715 : : */
17716 : 16 : ScanKeyInit(&key[0],
17717 : : Anum_pg_class_reltablespace,
17718 : : BTEqualStrategyNumber, F_OIDEQ,
17719 : : ObjectIdGetDatum(orig_tablespaceoid));
17720 : :
17721 : 16 : rel = table_open(RelationRelationId, AccessShareLock);
17722 : 16 : scan = table_beginscan_catalog(rel, 1, key);
17723 [ + + ]: 448 : while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
17724 : : {
17725 : 432 : Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
17726 : 432 : Oid relOid = relForm->oid;
17727 : :
17728 : : /*
17729 : : * Do not move objects in pg_catalog as part of this, if an admin
17730 : : * really wishes to do so, they can issue the individual ALTER
17731 : : * commands directly.
17732 : : *
17733 : : * Also, explicitly avoid any shared tables, temp tables, TOAST (TOAST
17734 : : * will be moved with the main table).
17735 : : *
17736 : : * Conflict log tables are system-managed for logical replication and
17737 : : * cannot be altered directly, so skip them as well; otherwise a
17738 : : * single such table in the source tablespace would abort the whole
17739 : : * bulk move.
17740 : : */
17741 [ + + ]: 432 : if (IsCatalogNamespace(relForm->relnamespace) ||
17742 [ + - + - ]: 376 : relForm->relisshared ||
17743 [ + + ]: 376 : isAnyTempNamespace(relForm->relnamespace) ||
17744 [ + + ]: 310 : IsToastNamespace(relForm->relnamespace) ||
17745 : 122 : IsConflictLogTableNamespace(relForm->relnamespace))
17746 : 311 : continue;
17747 : :
17748 : : /* Only move the object type requested */
17749 [ + + ]: 121 : if ((stmt->objtype == OBJECT_TABLE &&
17750 [ + + ]: 100 : relForm->relkind != RELKIND_RELATION &&
17751 [ - + ]: 83 : relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
17752 [ + + ]: 38 : (stmt->objtype == OBJECT_INDEX &&
17753 [ + + ]: 18 : relForm->relkind != RELKIND_INDEX &&
17754 [ - + ]: 3 : relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
17755 [ + + ]: 35 : (stmt->objtype == OBJECT_MATVIEW &&
17756 [ - + ]: 3 : relForm->relkind != RELKIND_MATVIEW))
17757 : 86 : continue;
17758 : :
17759 : : /* Check if we are only moving objects owned by certain roles */
17760 [ - + - - ]: 35 : if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
17761 : 0 : continue;
17762 : :
17763 : : /*
17764 : : * Handle permissions-checking here since we are locking the tables
17765 : : * and also to avoid doing a bunch of work only to fail part-way. Note
17766 : : * that permissions will also be checked by AlterTableInternal().
17767 : : *
17768 : : * Caller must be considered an owner on the table to move it.
17769 : : */
17770 [ - + ]: 35 : if (!object_ownercheck(RelationRelationId, relOid, GetUserId()))
17771 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relOid)),
17772 : 0 : NameStr(relForm->relname));
17773 : :
17774 [ - + ]: 35 : if (stmt->nowait &&
17775 [ # # ]: 0 : !ConditionalLockRelationOid(relOid, AccessExclusiveLock))
17776 [ # # ]: 0 : ereport(ERROR,
17777 : : (errcode(ERRCODE_OBJECT_IN_USE),
17778 : : errmsg("aborting because lock on relation \"%s.%s\" is not available",
17779 : : get_namespace_name(relForm->relnamespace),
17780 : : NameStr(relForm->relname))));
17781 : : else
17782 : 35 : LockRelationOid(relOid, AccessExclusiveLock);
17783 : :
17784 : : /* Add to our list of objects to move */
17785 : 35 : relations = lappend_oid(relations, relOid);
17786 : : }
17787 : :
17788 : 16 : table_endscan(scan);
17789 : 16 : table_close(rel, AccessShareLock);
17790 : :
17791 [ + + ]: 16 : if (relations == NIL)
17792 [ + - + - ]: 6 : ereport(NOTICE,
17793 : : (errcode(ERRCODE_NO_DATA_FOUND),
17794 : : errmsg("no matching relations in tablespace \"%s\" found",
17795 : : orig_tablespaceoid == InvalidOid ? "(database default)" :
17796 : : get_tablespace_name(orig_tablespaceoid))));
17797 : :
17798 : : /* Everything is locked, loop through and move all of the relations. */
17799 [ + + + + : 51 : foreach(l, relations)
+ + ]
17800 : : {
17801 : 35 : List *cmds = NIL;
17802 : 35 : AlterTableCmd *cmd = makeNode(AlterTableCmd);
17803 : :
17804 : 35 : cmd->subtype = AT_SetTableSpace;
17805 : 35 : cmd->name = stmt->new_tablespacename;
17806 : :
17807 : 35 : cmds = lappend(cmds, cmd);
17808 : :
17809 : 35 : EventTriggerAlterTableStart((Node *) stmt);
17810 : : /* OID is set by AlterTableInternal */
17811 : 35 : AlterTableInternal(lfirst_oid(l), cmds, false);
17812 : 35 : EventTriggerAlterTableEnd();
17813 : : }
17814 : :
17815 : 16 : return new_tablespaceoid;
17816 : : }
17817 : :
17818 : : static void
17819 : 40 : index_copy_data(Relation rel, RelFileLocator newrlocator)
17820 : : {
17821 : : SMgrRelation dstrel;
17822 : :
17823 : : /*
17824 : : * Since we copy the file directly without looking at the shared buffers,
17825 : : * we'd better first flush out any pages of the source relation that are
17826 : : * in shared buffers. We assume no new changes will be made while we are
17827 : : * holding exclusive lock on the rel.
17828 : : */
17829 : 40 : FlushRelationBuffers(rel);
17830 : :
17831 : : /*
17832 : : * Create and copy all forks of the relation, and schedule unlinking of
17833 : : * old physical files.
17834 : : *
17835 : : * NOTE: any conflict in relfilenumber value will be caught in
17836 : : * RelationCreateStorage().
17837 : : */
17838 : 40 : dstrel = RelationCreateStorage(newrlocator, rel->rd_rel->relpersistence, true);
17839 : :
17840 : : /* copy main fork */
17841 : 40 : RelationCopyStorage(RelationGetSmgr(rel), dstrel, MAIN_FORKNUM,
17842 : 40 : rel->rd_rel->relpersistence);
17843 : :
17844 : : /* copy those extra forks that exist */
17845 : 40 : for (ForkNumber forkNum = MAIN_FORKNUM + 1;
17846 [ + + ]: 160 : forkNum <= MAX_FORKNUM; forkNum++)
17847 : : {
17848 [ - + ]: 120 : if (smgrexists(RelationGetSmgr(rel), forkNum))
17849 : : {
17850 : 0 : smgrcreate(dstrel, forkNum, false);
17851 : :
17852 : : /*
17853 : : * WAL log creation if the relation is persistent, or this is the
17854 : : * init fork of an unlogged relation.
17855 : : */
17856 [ # # ]: 0 : if (RelationIsPermanent(rel) ||
17857 [ # # # # ]: 0 : (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
17858 : : forkNum == INIT_FORKNUM))
17859 : 0 : log_smgrcreate(&newrlocator, forkNum);
17860 : 0 : RelationCopyStorage(RelationGetSmgr(rel), dstrel, forkNum,
17861 : 0 : rel->rd_rel->relpersistence);
17862 : : }
17863 : : }
17864 : :
17865 : : /* drop old relation, and close new one */
17866 : 40 : RelationDropStorage(rel);
17867 : 40 : smgrclose(dstrel);
17868 : 40 : }
17869 : :
17870 : : /*
17871 : : * ALTER TABLE ENABLE/DISABLE TRIGGER
17872 : : *
17873 : : * We just pass this off to trigger.c.
17874 : : */
17875 : : static void
17876 : 191 : ATExecEnableDisableTrigger(Relation rel, const char *trigname,
17877 : : char fires_when, bool skip_system, bool recurse,
17878 : : LOCKMODE lockmode)
17879 : : {
17880 : 191 : EnableDisableTrigger(rel, trigname, InvalidOid,
17881 : : fires_when, skip_system, recurse,
17882 : : lockmode);
17883 : :
17884 [ + + ]: 191 : InvokeObjectPostAlterHook(RelationRelationId,
17885 : : RelationGetRelid(rel), 0);
17886 : 191 : }
17887 : :
17888 : : /*
17889 : : * ALTER TABLE ENABLE/DISABLE RULE
17890 : : *
17891 : : * We just pass this off to rewriteDefine.c.
17892 : : */
17893 : : static void
17894 : 29 : ATExecEnableDisableRule(Relation rel, const char *rulename,
17895 : : char fires_when, LOCKMODE lockmode)
17896 : : {
17897 : 29 : EnableDisableRule(rel, rulename, fires_when);
17898 : :
17899 [ + + ]: 29 : InvokeObjectPostAlterHook(RelationRelationId,
17900 : : RelationGetRelid(rel), 0);
17901 : 29 : }
17902 : :
17903 : : /*
17904 : : * Preparation phase of [NO] INHERIT
17905 : : *
17906 : : * Check the relation defined as a child.
17907 : : */
17908 : : static void
17909 : 366 : ATPrepChangeInherit(Relation child_rel)
17910 : : {
17911 [ + + ]: 366 : if (child_rel->rd_rel->reloftype)
17912 [ + - ]: 8 : ereport(ERROR,
17913 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17914 : : errmsg("cannot change inheritance of typed table")));
17915 : :
17916 [ + + ]: 358 : if (child_rel->rd_rel->relispartition)
17917 [ + - ]: 12 : ereport(ERROR,
17918 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17919 : : errmsg("cannot change inheritance of a partition")));
17920 : 346 : }
17921 : :
17922 : : /*
17923 : : * ALTER TABLE INHERIT
17924 : : *
17925 : : * Return the address of the new parent relation.
17926 : : */
17927 : : static ObjectAddress
17928 : 285 : ATExecAddInherit(Relation child_rel, RangeVar *parent, LOCKMODE lockmode)
17929 : : {
17930 : : Relation parent_rel;
17931 : : List *children;
17932 : : ObjectAddress address;
17933 : : const char *trigger_name;
17934 : :
17935 : : /*
17936 : : * A self-exclusive lock is needed here. See the similar case in
17937 : : * MergeAttributes() for a full explanation.
17938 : : */
17939 : 285 : parent_rel = table_openrv(parent, ShareUpdateExclusiveLock);
17940 : :
17941 : : /*
17942 : : * Must be owner of both parent and child -- child was checked by
17943 : : * ATSimplePermissions call in ATPrepCmd
17944 : : */
17945 : 285 : ATSimplePermissions(AT_AddInherit, parent_rel,
17946 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
17947 : :
17948 : : /* Permanent rels cannot inherit from temporary ones */
17949 [ + + ]: 285 : if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
17950 [ - + ]: 4 : child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
17951 [ # # ]: 0 : ereport(ERROR,
17952 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17953 : : errmsg("cannot inherit from temporary relation \"%s\"",
17954 : : RelationGetRelationName(parent_rel))));
17955 : :
17956 : : /* If parent rel is temp, it must belong to this session */
17957 [ + + - + ]: 285 : if (RELATION_IS_OTHER_TEMP(parent_rel))
17958 [ # # ]: 0 : ereport(ERROR,
17959 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17960 : : errmsg("cannot inherit from temporary relation of another session")));
17961 : :
17962 : : /* Ditto for the child */
17963 [ + + - + ]: 285 : if (RELATION_IS_OTHER_TEMP(child_rel))
17964 [ # # ]: 0 : ereport(ERROR,
17965 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17966 : : errmsg("cannot inherit to temporary relation of another session")));
17967 : :
17968 : : /* Prevent partitioned tables from becoming inheritance parents */
17969 [ + + ]: 285 : if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
17970 [ + - ]: 4 : ereport(ERROR,
17971 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17972 : : errmsg("cannot inherit from partitioned table \"%s\"",
17973 : : parent->relname)));
17974 : :
17975 : : /* Likewise for partitions */
17976 [ + + ]: 281 : if (parent_rel->rd_rel->relispartition)
17977 [ + - ]: 4 : ereport(ERROR,
17978 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
17979 : : errmsg("cannot inherit from a partition")));
17980 : :
17981 : : /*
17982 : : * Prevent circularity by seeing if proposed parent inherits from child.
17983 : : * (In particular, this disallows making a rel inherit from itself.)
17984 : : *
17985 : : * This is not completely bulletproof because of race conditions: in
17986 : : * multi-level inheritance trees, someone else could concurrently be
17987 : : * making another inheritance link that closes the loop but does not join
17988 : : * either of the rels we have locked. Preventing that seems to require
17989 : : * exclusive locks on the entire inheritance tree, which is a cure worse
17990 : : * than the disease. find_all_inheritors() will cope with circularity
17991 : : * anyway, so don't sweat it too much.
17992 : : *
17993 : : * We use weakest lock we can on child's children, namely AccessShareLock.
17994 : : */
17995 : 277 : children = find_all_inheritors(RelationGetRelid(child_rel),
17996 : : AccessShareLock, NULL);
17997 : :
17998 [ + + ]: 277 : if (list_member_oid(children, RelationGetRelid(parent_rel)))
17999 [ + - ]: 8 : ereport(ERROR,
18000 : : (errcode(ERRCODE_DUPLICATE_TABLE),
18001 : : errmsg("circular inheritance not allowed"),
18002 : : errdetail("\"%s\" is already a child of \"%s\".",
18003 : : parent->relname,
18004 : : RelationGetRelationName(child_rel))));
18005 : :
18006 : : /*
18007 : : * If child_rel has row-level triggers with transition tables, we
18008 : : * currently don't allow it to become an inheritance child. See also
18009 : : * prohibitions in ATExecAttachPartition() and CreateTrigger().
18010 : : */
18011 : 269 : trigger_name = FindTriggerIncompatibleWithInheritance(child_rel->trigdesc);
18012 [ + + ]: 269 : if (trigger_name != NULL)
18013 [ + - ]: 4 : ereport(ERROR,
18014 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18015 : : errmsg("trigger \"%s\" prevents table \"%s\" from becoming an inheritance child",
18016 : : trigger_name, RelationGetRelationName(child_rel)),
18017 : : errdetail("ROW triggers with transition tables are not supported in inheritance hierarchies.")));
18018 : :
18019 : : /* OK to create inheritance */
18020 : 265 : CreateInheritance(child_rel, parent_rel, false);
18021 : :
18022 : 205 : ObjectAddressSet(address, RelationRelationId,
18023 : : RelationGetRelid(parent_rel));
18024 : :
18025 : : /* keep our lock on the parent relation until commit */
18026 : 205 : table_close(parent_rel, NoLock);
18027 : :
18028 : 205 : return address;
18029 : : }
18030 : :
18031 : : /*
18032 : : * CreateInheritance
18033 : : * Catalog manipulation portion of creating inheritance between a child
18034 : : * table and a parent table.
18035 : : *
18036 : : * This verifies that all the columns and check constraints of the parent
18037 : : * appear in the child and that they have the same data types and expressions.
18038 : : *
18039 : : * Common to ATExecAddInherit() and ATExecAttachPartition().
18040 : : */
18041 : : static void
18042 : 1690 : CreateInheritance(Relation child_rel, Relation parent_rel, bool ispartition)
18043 : : {
18044 : : Relation catalogRelation;
18045 : : SysScanDesc scan;
18046 : : ScanKeyData key;
18047 : : HeapTuple inheritsTuple;
18048 : : int32 inhseqno;
18049 : :
18050 : : /* Note: get RowExclusiveLock because we will write pg_inherits below. */
18051 : 1690 : catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
18052 : :
18053 : : /*
18054 : : * Check for duplicates in the list of parents, and determine the highest
18055 : : * inhseqno already present; we'll use the next one for the new parent.
18056 : : * Also, if proposed child is a partition, it cannot already be
18057 : : * inheriting.
18058 : : *
18059 : : * Note: we do not reject the case where the child already inherits from
18060 : : * the parent indirectly; CREATE TABLE doesn't reject comparable cases.
18061 : : */
18062 : 1690 : ScanKeyInit(&key,
18063 : : Anum_pg_inherits_inhrelid,
18064 : : BTEqualStrategyNumber, F_OIDEQ,
18065 : : ObjectIdGetDatum(RelationGetRelid(child_rel)));
18066 : 1690 : scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
18067 : : true, NULL, 1, &key);
18068 : :
18069 : : /* inhseqno sequences start at 1 */
18070 : 1690 : inhseqno = 0;
18071 [ + + ]: 1741 : while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
18072 : : {
18073 : 55 : Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
18074 : :
18075 [ + + ]: 55 : if (inh->inhparent == RelationGetRelid(parent_rel))
18076 [ + - ]: 4 : ereport(ERROR,
18077 : : (errcode(ERRCODE_DUPLICATE_TABLE),
18078 : : errmsg("relation \"%s\" would be inherited from more than once",
18079 : : RelationGetRelationName(parent_rel))));
18080 : :
18081 [ + - ]: 51 : if (inh->inhseqno > inhseqno)
18082 : 51 : inhseqno = inh->inhseqno;
18083 : : }
18084 : 1686 : systable_endscan(scan);
18085 : :
18086 : : /* Match up the columns and bump attinhcount as needed */
18087 : 1686 : MergeAttributesIntoExisting(child_rel, parent_rel, ispartition);
18088 : :
18089 : : /* Match up the constraints and bump coninhcount as needed */
18090 : 1598 : MergeConstraintsIntoExisting(child_rel, parent_rel);
18091 : :
18092 : : /*
18093 : : * OK, it looks valid. Make the catalog entries that show inheritance.
18094 : : */
18095 : 1558 : StoreCatalogInheritance1(RelationGetRelid(child_rel),
18096 : : RelationGetRelid(parent_rel),
18097 : : inhseqno + 1,
18098 : : catalogRelation,
18099 : 1558 : parent_rel->rd_rel->relkind ==
18100 : : RELKIND_PARTITIONED_TABLE);
18101 : :
18102 : : /* Now we're done with pg_inherits */
18103 : 1558 : table_close(catalogRelation, RowExclusiveLock);
18104 : 1558 : }
18105 : :
18106 : : /*
18107 : : * Obtain the source-text form of the constraint expression for a check
18108 : : * constraint, given its pg_constraint tuple
18109 : : */
18110 : : static char *
18111 : 464 : decompile_conbin(HeapTuple contup, TupleDesc tupdesc)
18112 : : {
18113 : : Form_pg_constraint con;
18114 : : bool isnull;
18115 : : Datum attr;
18116 : : Datum expr;
18117 : :
18118 : 464 : con = (Form_pg_constraint) GETSTRUCT(contup);
18119 : 464 : attr = heap_getattr(contup, Anum_pg_constraint_conbin, tupdesc, &isnull);
18120 [ - + ]: 464 : if (isnull)
18121 [ # # ]: 0 : elog(ERROR, "null conbin for constraint %u", con->oid);
18122 : :
18123 : 464 : expr = DirectFunctionCall2(pg_get_expr, attr,
18124 : : ObjectIdGetDatum(con->conrelid));
18125 : 464 : return TextDatumGetCString(expr);
18126 : : }
18127 : :
18128 : : /*
18129 : : * Determine whether two check constraints are functionally equivalent
18130 : : *
18131 : : * The test we apply is to see whether they reverse-compile to the same
18132 : : * source string. This insulates us from issues like whether attributes
18133 : : * have the same physical column numbers in parent and child relations.
18134 : : *
18135 : : * Note that we ignore enforceability as there are cases where constraints
18136 : : * with differing enforceability are allowed.
18137 : : */
18138 : : static bool
18139 : 232 : constraints_equivalent(HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
18140 : : {
18141 : 232 : Form_pg_constraint acon = (Form_pg_constraint) GETSTRUCT(a);
18142 : 232 : Form_pg_constraint bcon = (Form_pg_constraint) GETSTRUCT(b);
18143 : :
18144 [ + - ]: 232 : if (acon->condeferrable != bcon->condeferrable ||
18145 [ + - ]: 232 : acon->condeferred != bcon->condeferred ||
18146 [ + + ]: 232 : strcmp(decompile_conbin(a, tupleDesc),
18147 : 232 : decompile_conbin(b, tupleDesc)) != 0)
18148 : 4 : return false;
18149 : : else
18150 : 228 : return true;
18151 : : }
18152 : :
18153 : : /*
18154 : : * Check columns in child table match up with columns in parent, and increment
18155 : : * their attinhcount.
18156 : : *
18157 : : * Called by CreateInheritance
18158 : : *
18159 : : * Currently all parent columns must be found in child. Missing columns are an
18160 : : * error. One day we might consider creating new columns like CREATE TABLE
18161 : : * does. However, that is widely unpopular --- in the common use case of
18162 : : * partitioned tables it's a foot-gun.
18163 : : *
18164 : : * The data type must match exactly. If the parent column is NOT NULL then
18165 : : * the child must be as well. Defaults are not compared, however.
18166 : : */
18167 : : static void
18168 : 1686 : MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispartition)
18169 : : {
18170 : : Relation attrrel;
18171 : : TupleDesc parent_desc;
18172 : :
18173 : 1686 : attrrel = table_open(AttributeRelationId, RowExclusiveLock);
18174 : 1686 : parent_desc = RelationGetDescr(parent_rel);
18175 : :
18176 [ + + ]: 5353 : for (AttrNumber parent_attno = 1; parent_attno <= parent_desc->natts; parent_attno++)
18177 : : {
18178 : 3755 : Form_pg_attribute parent_att = TupleDescAttr(parent_desc, parent_attno - 1);
18179 : 3755 : char *parent_attname = NameStr(parent_att->attname);
18180 : : HeapTuple tuple;
18181 : :
18182 : : /* Ignore dropped columns in the parent. */
18183 [ + + ]: 3755 : if (parent_att->attisdropped)
18184 : 180 : continue;
18185 : :
18186 : : /* Find same column in child (matching on column name). */
18187 : 3575 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(child_rel), parent_attname);
18188 [ + + ]: 3575 : if (HeapTupleIsValid(tuple))
18189 : : {
18190 : 3567 : Form_pg_attribute child_att = (Form_pg_attribute) GETSTRUCT(tuple);
18191 : :
18192 [ + + ]: 3567 : if (parent_att->atttypid != child_att->atttypid ||
18193 [ + + ]: 3563 : parent_att->atttypmod != child_att->atttypmod)
18194 [ + - ]: 8 : ereport(ERROR,
18195 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18196 : : errmsg("child table \"%s\" has different type for column \"%s\"",
18197 : : RelationGetRelationName(child_rel), parent_attname)));
18198 : :
18199 [ + + ]: 3559 : if (parent_att->attcollation != child_att->attcollation)
18200 [ + - ]: 4 : ereport(ERROR,
18201 : : (errcode(ERRCODE_COLLATION_MISMATCH),
18202 : : errmsg("child table \"%s\" has different collation for column \"%s\"",
18203 : : RelationGetRelationName(child_rel), parent_attname)));
18204 : :
18205 : : /*
18206 : : * If the parent has a not-null constraint that's not NO INHERIT,
18207 : : * make sure the child has one too.
18208 : : *
18209 : : * Other constraints are checked elsewhere.
18210 : : */
18211 [ + + + + ]: 3555 : if (parent_att->attnotnull && !child_att->attnotnull)
18212 : : {
18213 : : HeapTuple contup;
18214 : :
18215 : 32 : contup = findNotNullConstraintAttnum(RelationGetRelid(parent_rel),
18216 : 32 : parent_att->attnum);
18217 [ + - ]: 32 : if (HeapTupleIsValid(contup) &&
18218 [ + + ]: 32 : !((Form_pg_constraint) GETSTRUCT(contup))->connoinherit)
18219 [ + - ]: 20 : ereport(ERROR,
18220 : : errcode(ERRCODE_DATATYPE_MISMATCH),
18221 : : errmsg("column \"%s\" in child table \"%s\" must be marked NOT NULL",
18222 : : parent_attname, RelationGetRelationName(child_rel)));
18223 : : }
18224 : :
18225 : : /*
18226 : : * Child column must be generated if and only if parent column is.
18227 : : */
18228 [ + + + + ]: 3535 : if (parent_att->attgenerated && !child_att->attgenerated)
18229 [ + - ]: 24 : ereport(ERROR,
18230 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18231 : : errmsg("column \"%s\" in child table must be a generated column", parent_attname)));
18232 [ + + + + ]: 3511 : if (child_att->attgenerated && !parent_att->attgenerated)
18233 [ + - ]: 16 : ereport(ERROR,
18234 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18235 : : errmsg("column \"%s\" in child table must not be a generated column", parent_attname)));
18236 : :
18237 [ + + + - : 3495 : if (parent_att->attgenerated && child_att->attgenerated && child_att->attgenerated != parent_att->attgenerated)
+ + ]
18238 [ + - + + : 8 : ereport(ERROR,
+ + ]
18239 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18240 : : errmsg("column \"%s\" inherits from generated column of different kind", parent_attname),
18241 : : errdetail("Parent column is %s, child column is %s.",
18242 : : parent_att->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL",
18243 : : child_att->attgenerated == ATTRIBUTE_GENERATED_STORED ? "STORED" : "VIRTUAL")));
18244 : :
18245 : : /*
18246 : : * Regular inheritance children are independent enough not to
18247 : : * inherit identity columns. But partitions are integral part of
18248 : : * a partitioned table and inherit identity column.
18249 : : */
18250 [ + + ]: 3487 : if (ispartition)
18251 : 3038 : child_att->attidentity = parent_att->attidentity;
18252 : :
18253 : : /*
18254 : : * OK, bump the child column's inheritance count. (If we fail
18255 : : * later on, this change will just roll back.)
18256 : : */
18257 [ - + ]: 3487 : if (pg_add_s16_overflow(child_att->attinhcount, 1,
18258 : : &child_att->attinhcount))
18259 [ # # ]: 0 : ereport(ERROR,
18260 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
18261 : : errmsg("too many inheritance parents"));
18262 : :
18263 : : /*
18264 : : * In case of partitions, we must enforce that value of attislocal
18265 : : * is same in all partitions. (Note: there are only inherited
18266 : : * attributes in partitions)
18267 : : */
18268 [ + + ]: 3487 : if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
18269 : : {
18270 : : Assert(child_att->attinhcount == 1);
18271 : 3038 : child_att->attislocal = false;
18272 : : }
18273 : :
18274 : 3487 : CatalogTupleUpdate(attrrel, &tuple->t_self, tuple);
18275 : 3487 : heap_freetuple(tuple);
18276 : : }
18277 : : else
18278 : : {
18279 [ + - ]: 8 : ereport(ERROR,
18280 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18281 : : errmsg("child table is missing column \"%s\"", parent_attname)));
18282 : : }
18283 : : }
18284 : :
18285 : 1598 : table_close(attrrel, RowExclusiveLock);
18286 : 1598 : }
18287 : :
18288 : : /*
18289 : : * Check constraints in child table match up with constraints in parent,
18290 : : * and increment their coninhcount.
18291 : : *
18292 : : * Constraints that are marked ONLY in the parent are ignored.
18293 : : *
18294 : : * Called by CreateInheritance
18295 : : *
18296 : : * Currently all constraints in parent must be present in the child. One day we
18297 : : * may consider adding new constraints like CREATE TABLE does.
18298 : : *
18299 : : * XXX This is O(N^2) which may be an issue with tables with hundreds of
18300 : : * constraints. As long as tables have more like 10 constraints it shouldn't be
18301 : : * a problem though. Even 100 constraints ought not be the end of the world.
18302 : : *
18303 : : * XXX See MergeWithExistingConstraint too if you change this code.
18304 : : */
18305 : : static void
18306 : 1598 : MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
18307 : : {
18308 : : Relation constraintrel;
18309 : : SysScanDesc parent_scan;
18310 : : ScanKeyData parent_key;
18311 : : HeapTuple parent_tuple;
18312 : 1598 : Oid parent_relid = RelationGetRelid(parent_rel);
18313 : : AttrMap *attmap;
18314 : :
18315 : 1598 : constraintrel = table_open(ConstraintRelationId, RowExclusiveLock);
18316 : :
18317 : : /* Outer loop scans through the parent's constraint definitions */
18318 : 1598 : ScanKeyInit(&parent_key,
18319 : : Anum_pg_constraint_conrelid,
18320 : : BTEqualStrategyNumber, F_OIDEQ,
18321 : : ObjectIdGetDatum(parent_relid));
18322 : 1598 : parent_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
18323 : : true, NULL, 1, &parent_key);
18324 : :
18325 : 1598 : attmap = build_attrmap_by_name(RelationGetDescr(parent_rel),
18326 : : RelationGetDescr(child_rel),
18327 : : true);
18328 : :
18329 [ + + ]: 2873 : while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
18330 : : {
18331 : 1315 : Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
18332 : : SysScanDesc child_scan;
18333 : : ScanKeyData child_key;
18334 : : HeapTuple child_tuple;
18335 : : AttrNumber parent_attno;
18336 : 1315 : bool found = false;
18337 : :
18338 [ + + ]: 1315 : if (parent_con->contype != CONSTRAINT_CHECK &&
18339 [ + + ]: 1207 : parent_con->contype != CONSTRAINT_NOTNULL)
18340 : 650 : continue;
18341 : :
18342 : : /* if the parent's constraint is marked NO INHERIT, it's not inherited */
18343 [ + + ]: 697 : if (parent_con->connoinherit)
18344 : 32 : continue;
18345 : :
18346 [ + + ]: 665 : if (parent_con->contype == CONSTRAINT_NOTNULL)
18347 : 573 : parent_attno = extractNotNullColumn(parent_tuple);
18348 : : else
18349 : 92 : parent_attno = InvalidAttrNumber;
18350 : :
18351 : : /* Search for a child constraint matching this one */
18352 : 665 : ScanKeyInit(&child_key,
18353 : : Anum_pg_constraint_conrelid,
18354 : : BTEqualStrategyNumber, F_OIDEQ,
18355 : : ObjectIdGetDatum(RelationGetRelid(child_rel)));
18356 : 665 : child_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
18357 : : true, NULL, 1, &child_key);
18358 : :
18359 [ + + ]: 1052 : while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
18360 : : {
18361 : 1036 : Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
18362 : : HeapTuple child_copy;
18363 : :
18364 [ + + ]: 1036 : if (child_con->contype != parent_con->contype)
18365 : 186 : continue;
18366 : :
18367 : : /*
18368 : : * CHECK constraint are matched by constraint name, NOT NULL ones
18369 : : * by attribute number.
18370 : : */
18371 [ + + ]: 850 : if (child_con->contype == CONSTRAINT_CHECK)
18372 : : {
18373 : 122 : if (strcmp(NameStr(parent_con->conname),
18374 [ + + ]: 99 : NameStr(child_con->conname)) != 0)
18375 : 23 : continue;
18376 : : }
18377 [ + - ]: 751 : else if (child_con->contype == CONSTRAINT_NOTNULL)
18378 : : {
18379 : : Form_pg_attribute parent_attr;
18380 : : Form_pg_attribute child_attr;
18381 : : AttrNumber child_attno;
18382 : :
18383 : 751 : parent_attr = TupleDescAttr(parent_rel->rd_att, parent_attno - 1);
18384 : 751 : child_attno = extractNotNullColumn(child_tuple);
18385 [ + + ]: 751 : if (parent_attno != attmap->attnums[child_attno - 1])
18386 : 178 : continue;
18387 : :
18388 : 573 : child_attr = TupleDescAttr(child_rel->rd_att, child_attno - 1);
18389 : : /* there shouldn't be constraints on dropped columns */
18390 [ + - - + ]: 573 : if (parent_attr->attisdropped || child_attr->attisdropped)
18391 [ # # ]: 0 : elog(ERROR, "found not-null constraint on dropped columns");
18392 : : }
18393 : :
18394 [ + + ]: 649 : if (child_con->contype == CONSTRAINT_CHECK &&
18395 [ + + ]: 76 : !constraints_equivalent(parent_tuple, child_tuple, RelationGetDescr(constraintrel)))
18396 [ + - ]: 4 : ereport(ERROR,
18397 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18398 : : errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
18399 : : RelationGetRelationName(child_rel), NameStr(parent_con->conname))));
18400 : :
18401 : : /*
18402 : : * If the child constraint is "no inherit" then cannot merge
18403 : : */
18404 [ + + ]: 645 : if (child_con->connoinherit)
18405 [ + - ]: 8 : ereport(ERROR,
18406 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
18407 : : errmsg("constraint \"%s\" conflicts with non-inherited constraint on child table \"%s\"",
18408 : : NameStr(child_con->conname), RelationGetRelationName(child_rel))));
18409 : :
18410 : : /*
18411 : : * If the child constraint is "not valid" then cannot merge with a
18412 : : * valid parent constraint
18413 : : */
18414 [ + + + + ]: 637 : if (parent_con->convalidated && child_con->conenforced &&
18415 [ + + ]: 593 : !child_con->convalidated)
18416 [ + - ]: 8 : ereport(ERROR,
18417 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
18418 : : errmsg("constraint \"%s\" conflicts with NOT VALID constraint on child table \"%s\"",
18419 : : NameStr(child_con->conname), RelationGetRelationName(child_rel))));
18420 : :
18421 : : /*
18422 : : * A NOT ENFORCED child constraint cannot be merged with an
18423 : : * ENFORCED parent constraint. However, the reverse is allowed,
18424 : : * where the child constraint is ENFORCED.
18425 : : */
18426 [ + + + + ]: 629 : if (parent_con->conenforced && !child_con->conenforced)
18427 [ + - ]: 4 : ereport(ERROR,
18428 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
18429 : : errmsg("constraint \"%s\" conflicts with NOT ENFORCED constraint on child table \"%s\"",
18430 : : NameStr(child_con->conname), RelationGetRelationName(child_rel))));
18431 : :
18432 : : /*
18433 : : * OK, bump the child constraint's inheritance count. (If we fail
18434 : : * later on, this change will just roll back.)
18435 : : */
18436 : 625 : child_copy = heap_copytuple(child_tuple);
18437 : 625 : child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
18438 : :
18439 [ - + ]: 625 : if (pg_add_s16_overflow(child_con->coninhcount, 1,
18440 : : &child_con->coninhcount))
18441 [ # # ]: 0 : ereport(ERROR,
18442 : : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
18443 : : errmsg("too many inheritance parents"));
18444 : :
18445 : : /*
18446 : : * In case of partitions, an inherited constraint must be
18447 : : * inherited only once since it cannot have multiple parents and
18448 : : * it is never considered local.
18449 : : */
18450 [ + + ]: 625 : if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
18451 : : {
18452 : : Assert(child_con->coninhcount == 1);
18453 : 526 : child_con->conislocal = false;
18454 : : }
18455 : :
18456 : 625 : CatalogTupleUpdate(constraintrel, &child_copy->t_self, child_copy);
18457 : 625 : heap_freetuple(child_copy);
18458 : :
18459 : 625 : found = true;
18460 : 625 : break;
18461 : : }
18462 : :
18463 : 641 : systable_endscan(child_scan);
18464 : :
18465 [ + + ]: 641 : if (!found)
18466 : : {
18467 [ - + ]: 16 : if (parent_con->contype == CONSTRAINT_NOTNULL)
18468 [ # # ]: 0 : ereport(ERROR,
18469 : : errcode(ERRCODE_DATATYPE_MISMATCH),
18470 : : errmsg("column \"%s\" in child table \"%s\" must be marked NOT NULL",
18471 : : get_attname(parent_relid,
18472 : : extractNotNullColumn(parent_tuple),
18473 : : false),
18474 : : RelationGetRelationName(child_rel)));
18475 : :
18476 [ + - ]: 16 : ereport(ERROR,
18477 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18478 : : errmsg("child table is missing constraint \"%s\"",
18479 : : NameStr(parent_con->conname))));
18480 : : }
18481 : : }
18482 : :
18483 : 1558 : systable_endscan(parent_scan);
18484 : 1558 : table_close(constraintrel, RowExclusiveLock);
18485 : 1558 : }
18486 : :
18487 : : /*
18488 : : * ALTER TABLE NO INHERIT
18489 : : *
18490 : : * Return value is the address of the relation that is no longer parent.
18491 : : */
18492 : : static ObjectAddress
18493 : 61 : ATExecDropInherit(Relation rel, RangeVar *parent, LOCKMODE lockmode)
18494 : : {
18495 : : ObjectAddress address;
18496 : : Relation parent_rel;
18497 : :
18498 : : /*
18499 : : * AccessShareLock on the parent is probably enough, seeing that DROP
18500 : : * TABLE doesn't lock parent tables at all. We need some lock since we'll
18501 : : * be inspecting the parent's schema.
18502 : : */
18503 : 61 : parent_rel = table_openrv(parent, AccessShareLock);
18504 : :
18505 : : /*
18506 : : * We don't bother to check ownership of the parent table --- ownership of
18507 : : * the child is presumed enough rights.
18508 : : */
18509 : :
18510 : : /* Off to RemoveInheritance() where most of the work happens */
18511 : 61 : RemoveInheritance(rel, parent_rel, false);
18512 : :
18513 : 57 : ObjectAddressSet(address, RelationRelationId,
18514 : : RelationGetRelid(parent_rel));
18515 : :
18516 : : /* keep our lock on the parent relation until commit */
18517 : 57 : table_close(parent_rel, NoLock);
18518 : :
18519 : 57 : return address;
18520 : : }
18521 : :
18522 : : /*
18523 : : * MarkInheritDetached
18524 : : *
18525 : : * Set inhdetachpending for a partition, for ATExecDetachPartition
18526 : : * in concurrent mode. While at it, verify that no other partition is
18527 : : * already pending detach.
18528 : : */
18529 : : static void
18530 : 76 : MarkInheritDetached(Relation child_rel, Relation parent_rel)
18531 : : {
18532 : : Relation catalogRelation;
18533 : : SysScanDesc scan;
18534 : : ScanKeyData key;
18535 : : HeapTuple inheritsTuple;
18536 : 76 : bool found = false;
18537 : :
18538 : : Assert(parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
18539 : :
18540 : : /*
18541 : : * Find pg_inherits entries by inhparent. (We need to scan them all in
18542 : : * order to verify that no other partition is pending detach.)
18543 : : */
18544 : 76 : catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
18545 : 76 : ScanKeyInit(&key,
18546 : : Anum_pg_inherits_inhparent,
18547 : : BTEqualStrategyNumber, F_OIDEQ,
18548 : : ObjectIdGetDatum(RelationGetRelid(parent_rel)));
18549 : 76 : scan = systable_beginscan(catalogRelation, InheritsParentIndexId,
18550 : : true, NULL, 1, &key);
18551 : :
18552 [ + + ]: 298 : while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
18553 : : {
18554 : : Form_pg_inherits inhForm;
18555 : :
18556 : 147 : inhForm = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
18557 [ + + ]: 147 : if (inhForm->inhdetachpending)
18558 [ + - ]: 1 : ereport(ERROR,
18559 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
18560 : : errmsg("partition \"%s\" already pending detach in partitioned table \"%s.%s\"",
18561 : : get_rel_name(inhForm->inhrelid),
18562 : : get_namespace_name(parent_rel->rd_rel->relnamespace),
18563 : : RelationGetRelationName(parent_rel)),
18564 : : errhint("Use ALTER TABLE ... DETACH PARTITION ... FINALIZE to complete the pending detach operation."));
18565 : :
18566 [ + + ]: 146 : if (inhForm->inhrelid == RelationGetRelid(child_rel))
18567 : : {
18568 : : HeapTuple newtup;
18569 : :
18570 : 75 : newtup = heap_copytuple(inheritsTuple);
18571 : 75 : ((Form_pg_inherits) GETSTRUCT(newtup))->inhdetachpending = true;
18572 : :
18573 : 75 : CatalogTupleUpdate(catalogRelation,
18574 : 75 : &inheritsTuple->t_self,
18575 : : newtup);
18576 : 75 : found = true;
18577 : 75 : heap_freetuple(newtup);
18578 : : /* keep looking, to ensure we catch others pending detach */
18579 : : }
18580 : : }
18581 : :
18582 : : /* Done */
18583 : 75 : systable_endscan(scan);
18584 : 75 : table_close(catalogRelation, RowExclusiveLock);
18585 : :
18586 [ - + ]: 75 : if (!found)
18587 [ # # ]: 0 : ereport(ERROR,
18588 : : (errcode(ERRCODE_UNDEFINED_TABLE),
18589 : : errmsg("relation \"%s\" is not a partition of relation \"%s\"",
18590 : : RelationGetRelationName(child_rel),
18591 : : RelationGetRelationName(parent_rel))));
18592 : 75 : }
18593 : :
18594 : : /*
18595 : : * RemoveInheritance
18596 : : *
18597 : : * Drop a parent from the child's parents. This just adjusts the attinhcount
18598 : : * and attislocal of the columns and removes the pg_inherit and pg_depend
18599 : : * entries. expect_detached is passed down to DeleteInheritsTuple, q.v..
18600 : : *
18601 : : * If attinhcount goes to 0 then attislocal gets set to true. If it goes back
18602 : : * up attislocal stays true, which means if a child is ever removed from a
18603 : : * parent then its columns will never be automatically dropped which may
18604 : : * surprise. But at least we'll never surprise by dropping columns someone
18605 : : * isn't expecting to be dropped which would actually mean data loss.
18606 : : *
18607 : : * coninhcount and conislocal for inherited constraints are adjusted in
18608 : : * exactly the same way.
18609 : : *
18610 : : * Common to ATExecDropInherit() and ATExecDetachPartition().
18611 : : */
18612 : : static void
18613 : 385 : RemoveInheritance(Relation child_rel, Relation parent_rel, bool expect_detached)
18614 : : {
18615 : : Relation catalogRelation;
18616 : : SysScanDesc scan;
18617 : : ScanKeyData key[3];
18618 : : HeapTuple attributeTuple,
18619 : : constraintTuple;
18620 : : AttrMap *attmap;
18621 : : List *connames;
18622 : : List *nncolumns;
18623 : : bool found;
18624 : : bool is_partitioning;
18625 : :
18626 : 385 : is_partitioning = (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
18627 : :
18628 : 385 : found = DeleteInheritsTuple(RelationGetRelid(child_rel),
18629 : : RelationGetRelid(parent_rel),
18630 : : expect_detached,
18631 : 385 : RelationGetRelationName(child_rel));
18632 [ + + ]: 385 : if (!found)
18633 : : {
18634 [ + + ]: 16 : if (is_partitioning)
18635 [ + - ]: 12 : ereport(ERROR,
18636 : : (errcode(ERRCODE_UNDEFINED_TABLE),
18637 : : errmsg("relation \"%s\" is not a partition of relation \"%s\"",
18638 : : RelationGetRelationName(child_rel),
18639 : : RelationGetRelationName(parent_rel))));
18640 : : else
18641 [ + - ]: 4 : ereport(ERROR,
18642 : : (errcode(ERRCODE_UNDEFINED_TABLE),
18643 : : errmsg("relation \"%s\" is not a parent of relation \"%s\"",
18644 : : RelationGetRelationName(parent_rel),
18645 : : RelationGetRelationName(child_rel))));
18646 : : }
18647 : :
18648 : : /*
18649 : : * Search through child columns looking for ones matching parent rel
18650 : : */
18651 : 369 : catalogRelation = table_open(AttributeRelationId, RowExclusiveLock);
18652 : 369 : ScanKeyInit(&key[0],
18653 : : Anum_pg_attribute_attrelid,
18654 : : BTEqualStrategyNumber, F_OIDEQ,
18655 : : ObjectIdGetDatum(RelationGetRelid(child_rel)));
18656 : 369 : scan = systable_beginscan(catalogRelation, AttributeRelidNumIndexId,
18657 : : true, NULL, 1, key);
18658 [ + + ]: 3308 : while (HeapTupleIsValid(attributeTuple = systable_getnext(scan)))
18659 : : {
18660 : 2939 : Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attributeTuple);
18661 : :
18662 : : /* Ignore if dropped or not inherited */
18663 [ + + ]: 2939 : if (att->attisdropped)
18664 : 4 : continue;
18665 [ + + ]: 2935 : if (att->attinhcount <= 0)
18666 : 2234 : continue;
18667 : :
18668 [ + + ]: 701 : if (SearchSysCacheExistsAttName(RelationGetRelid(parent_rel),
18669 : 701 : NameStr(att->attname)))
18670 : : {
18671 : : /* Decrement inhcount and possibly set islocal to true */
18672 : 665 : HeapTuple copyTuple = heap_copytuple(attributeTuple);
18673 : 665 : Form_pg_attribute copy_att = (Form_pg_attribute) GETSTRUCT(copyTuple);
18674 : :
18675 : 665 : copy_att->attinhcount--;
18676 [ + + ]: 665 : if (copy_att->attinhcount == 0)
18677 : 645 : copy_att->attislocal = true;
18678 : :
18679 : 665 : CatalogTupleUpdate(catalogRelation, ©Tuple->t_self, copyTuple);
18680 : 665 : heap_freetuple(copyTuple);
18681 : : }
18682 : : }
18683 : 369 : systable_endscan(scan);
18684 : 369 : table_close(catalogRelation, RowExclusiveLock);
18685 : :
18686 : : /*
18687 : : * Likewise, find inherited check and not-null constraints and disinherit
18688 : : * them. To do this, we first need a list of the names of the parent's
18689 : : * check constraints. (We cheat a bit by only checking for name matches,
18690 : : * assuming that the expressions will match.)
18691 : : *
18692 : : * For NOT NULL columns, we store column numbers to match, mapping them in
18693 : : * to the child rel's attribute numbers.
18694 : : */
18695 : 369 : attmap = build_attrmap_by_name(RelationGetDescr(child_rel),
18696 : : RelationGetDescr(parent_rel),
18697 : : false);
18698 : :
18699 : 369 : catalogRelation = table_open(ConstraintRelationId, RowExclusiveLock);
18700 : 369 : ScanKeyInit(&key[0],
18701 : : Anum_pg_constraint_conrelid,
18702 : : BTEqualStrategyNumber, F_OIDEQ,
18703 : : ObjectIdGetDatum(RelationGetRelid(parent_rel)));
18704 : 369 : scan = systable_beginscan(catalogRelation, ConstraintRelidTypidNameIndexId,
18705 : : true, NULL, 1, key);
18706 : :
18707 : 369 : connames = NIL;
18708 : 369 : nncolumns = NIL;
18709 : :
18710 [ + + ]: 794 : while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
18711 : : {
18712 : 425 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
18713 : :
18714 [ + + ]: 425 : if (con->connoinherit)
18715 : 68 : continue;
18716 : :
18717 [ + + ]: 357 : if (con->contype == CONSTRAINT_CHECK)
18718 : 8 : connames = lappend(connames, pstrdup(NameStr(con->conname)));
18719 [ + + ]: 357 : if (con->contype == CONSTRAINT_NOTNULL)
18720 : : {
18721 : 133 : AttrNumber parent_attno = extractNotNullColumn(constraintTuple);
18722 : :
18723 : 133 : nncolumns = lappend_int(nncolumns, attmap->attnums[parent_attno - 1]);
18724 : : }
18725 : : }
18726 : :
18727 : 369 : systable_endscan(scan);
18728 : :
18729 : : /* Now scan the child's constraints to find matches */
18730 : 369 : ScanKeyInit(&key[0],
18731 : : Anum_pg_constraint_conrelid,
18732 : : BTEqualStrategyNumber, F_OIDEQ,
18733 : : ObjectIdGetDatum(RelationGetRelid(child_rel)));
18734 : 369 : scan = systable_beginscan(catalogRelation, ConstraintRelidTypidNameIndexId,
18735 : : true, NULL, 1, key);
18736 : :
18737 [ + + ]: 790 : while (HeapTupleIsValid(constraintTuple = systable_getnext(scan)))
18738 : : {
18739 : 421 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(constraintTuple);
18740 : 421 : bool match = false;
18741 : :
18742 : : /*
18743 : : * Match CHECK constraints by name, not-null constraints by column
18744 : : * number, and ignore all others.
18745 : : */
18746 [ + + ]: 421 : if (con->contype == CONSTRAINT_CHECK)
18747 : : {
18748 [ + + + + : 92 : foreach_ptr(char, chkname, connames)
+ + ]
18749 : : {
18750 [ + - ]: 12 : if (con->contype == CONSTRAINT_CHECK &&
18751 [ + + ]: 12 : strcmp(NameStr(con->conname), chkname) == 0)
18752 : : {
18753 : 8 : match = true;
18754 : 8 : connames = foreach_delete_current(connames, chkname);
18755 : 8 : break;
18756 : : }
18757 : : }
18758 : : }
18759 [ + + ]: 377 : else if (con->contype == CONSTRAINT_NOTNULL)
18760 : : {
18761 : 173 : AttrNumber child_attno = extractNotNullColumn(constraintTuple);
18762 : :
18763 [ + + + + : 350 : foreach_int(prevattno, nncolumns)
+ + ]
18764 : : {
18765 [ + + ]: 137 : if (prevattno == child_attno)
18766 : : {
18767 : 133 : match = true;
18768 : 133 : nncolumns = foreach_delete_current(nncolumns, prevattno);
18769 : 133 : break;
18770 : : }
18771 : : }
18772 : : }
18773 : : else
18774 : 204 : continue;
18775 : :
18776 [ + + ]: 217 : if (match)
18777 : : {
18778 : : /* Decrement inhcount and possibly set islocal to true */
18779 : 141 : HeapTuple copyTuple = heap_copytuple(constraintTuple);
18780 : 141 : Form_pg_constraint copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
18781 : :
18782 [ - + ]: 141 : if (copy_con->coninhcount <= 0) /* shouldn't happen */
18783 [ # # ]: 0 : elog(ERROR, "relation %u has non-inherited constraint \"%s\"",
18784 : : RelationGetRelid(child_rel), NameStr(copy_con->conname));
18785 : :
18786 : 141 : copy_con->coninhcount--;
18787 [ + + ]: 141 : if (copy_con->coninhcount == 0)
18788 : 129 : copy_con->conislocal = true;
18789 : :
18790 : 141 : CatalogTupleUpdate(catalogRelation, ©Tuple->t_self, copyTuple);
18791 : 141 : heap_freetuple(copyTuple);
18792 : : }
18793 : : }
18794 : :
18795 : : /* We should have matched all constraints */
18796 [ + - - + ]: 369 : if (connames != NIL || nncolumns != NIL)
18797 [ # # ]: 0 : elog(ERROR, "%d unmatched constraints while removing inheritance from \"%s\" to \"%s\"",
18798 : : list_length(connames) + list_length(nncolumns),
18799 : : RelationGetRelationName(child_rel), RelationGetRelationName(parent_rel));
18800 : :
18801 : 369 : systable_endscan(scan);
18802 : 369 : table_close(catalogRelation, RowExclusiveLock);
18803 : :
18804 [ + + ]: 369 : drop_parent_dependency(RelationGetRelid(child_rel),
18805 : : RelationRelationId,
18806 : : RelationGetRelid(parent_rel),
18807 : : child_dependency_type(is_partitioning));
18808 : :
18809 : : /*
18810 : : * Post alter hook of this inherits. Since object_access_hook doesn't take
18811 : : * multiple object identifiers, we relay oid of parent relation using
18812 : : * auxiliary_id argument.
18813 : : */
18814 [ - + ]: 369 : InvokeObjectPostAlterHookArg(InheritsRelationId,
18815 : : RelationGetRelid(child_rel), 0,
18816 : : RelationGetRelid(parent_rel), false);
18817 : 369 : }
18818 : :
18819 : : /*
18820 : : * Drop the dependency created by StoreCatalogInheritance1 (CREATE TABLE
18821 : : * INHERITS/ALTER TABLE INHERIT -- refclassid will be RelationRelationId) or
18822 : : * heap_create_with_catalog (CREATE TABLE OF/ALTER TABLE OF -- refclassid will
18823 : : * be TypeRelationId). There's no convenient way to do this, so go trawling
18824 : : * through pg_depend.
18825 : : */
18826 : : static void
18827 : 377 : drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid,
18828 : : DependencyType deptype)
18829 : : {
18830 : : Relation catalogRelation;
18831 : : SysScanDesc scan;
18832 : : ScanKeyData key[3];
18833 : : HeapTuple depTuple;
18834 : :
18835 : 377 : catalogRelation = table_open(DependRelationId, RowExclusiveLock);
18836 : :
18837 : 377 : ScanKeyInit(&key[0],
18838 : : Anum_pg_depend_classid,
18839 : : BTEqualStrategyNumber, F_OIDEQ,
18840 : : ObjectIdGetDatum(RelationRelationId));
18841 : 377 : ScanKeyInit(&key[1],
18842 : : Anum_pg_depend_objid,
18843 : : BTEqualStrategyNumber, F_OIDEQ,
18844 : : ObjectIdGetDatum(relid));
18845 : 377 : ScanKeyInit(&key[2],
18846 : : Anum_pg_depend_objsubid,
18847 : : BTEqualStrategyNumber, F_INT4EQ,
18848 : : Int32GetDatum(0));
18849 : :
18850 : 377 : scan = systable_beginscan(catalogRelation, DependDependerIndexId, true,
18851 : : NULL, 3, key);
18852 : :
18853 [ + + ]: 1172 : while (HeapTupleIsValid(depTuple = systable_getnext(scan)))
18854 : : {
18855 : 795 : Form_pg_depend dep = (Form_pg_depend) GETSTRUCT(depTuple);
18856 : :
18857 [ + + ]: 795 : if (dep->refclassid == refclassid &&
18858 [ + + ]: 405 : dep->refobjid == refobjid &&
18859 [ + - ]: 377 : dep->refobjsubid == 0 &&
18860 [ + - ]: 377 : dep->deptype == deptype)
18861 : 377 : CatalogTupleDelete(catalogRelation, &depTuple->t_self);
18862 : : }
18863 : :
18864 : 377 : systable_endscan(scan);
18865 : 377 : table_close(catalogRelation, RowExclusiveLock);
18866 : 377 : }
18867 : :
18868 : : /*
18869 : : * ALTER TABLE OF
18870 : : *
18871 : : * Attach a table to a composite type, as though it had been created with CREATE
18872 : : * TABLE OF. All attname, atttypid, atttypmod and attcollation must match. The
18873 : : * subject table must not have inheritance parents. These restrictions ensure
18874 : : * that you cannot create a configuration impossible with CREATE TABLE OF alone.
18875 : : *
18876 : : * The address of the type is returned.
18877 : : */
18878 : : static ObjectAddress
18879 : 50 : ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
18880 : : {
18881 : 50 : Oid relid = RelationGetRelid(rel);
18882 : : Type typetuple;
18883 : : Form_pg_type typeform;
18884 : : Oid typeid;
18885 : : Relation inheritsRelation,
18886 : : relationRelation;
18887 : : SysScanDesc scan;
18888 : : ScanKeyData key;
18889 : : AttrNumber table_attno,
18890 : : type_attno;
18891 : : TupleDesc typeTupleDesc,
18892 : : tableTupleDesc;
18893 : : ObjectAddress tableobj,
18894 : : typeobj;
18895 : : HeapTuple classtuple;
18896 : : AclResult aclresult;
18897 : :
18898 : : /* Validate the type. */
18899 : 50 : typetuple = typenameType(NULL, ofTypename, NULL);
18900 : 50 : check_of_type(typetuple);
18901 : 50 : typeform = (Form_pg_type) GETSTRUCT(typetuple);
18902 : 50 : typeid = typeform->oid;
18903 : :
18904 : 50 : aclresult = object_aclcheck(TypeRelationId, typeid, GetUserId(), ACL_USAGE);
18905 [ + + ]: 50 : if (aclresult != ACLCHECK_OK)
18906 : 4 : aclcheck_error_type(aclresult, typeid);
18907 : :
18908 : : /* Fail if the table has any inheritance parents. */
18909 : 46 : inheritsRelation = table_open(InheritsRelationId, AccessShareLock);
18910 : 46 : ScanKeyInit(&key,
18911 : : Anum_pg_inherits_inhrelid,
18912 : : BTEqualStrategyNumber, F_OIDEQ,
18913 : : ObjectIdGetDatum(relid));
18914 : 46 : scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
18915 : : true, NULL, 1, &key);
18916 [ + + ]: 46 : if (HeapTupleIsValid(systable_getnext(scan)))
18917 [ + - ]: 4 : ereport(ERROR,
18918 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
18919 : : errmsg("typed tables cannot inherit")));
18920 : 42 : systable_endscan(scan);
18921 : 42 : table_close(inheritsRelation, AccessShareLock);
18922 : :
18923 : : /*
18924 : : * Check the tuple descriptors for compatibility. Unlike inheritance, we
18925 : : * require that the order also match. However, attnotnull need not match.
18926 : : */
18927 : 42 : typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
18928 : 42 : tableTupleDesc = RelationGetDescr(rel);
18929 : 42 : table_attno = 1;
18930 [ + + ]: 133 : for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
18931 : : {
18932 : : Form_pg_attribute type_attr,
18933 : : table_attr;
18934 : : const char *type_attname,
18935 : : *table_attname;
18936 : :
18937 : : /* Get the next non-dropped type attribute. */
18938 : 107 : type_attr = TupleDescAttr(typeTupleDesc, type_attno - 1);
18939 [ + + ]: 107 : if (type_attr->attisdropped)
18940 : 29 : continue;
18941 : 78 : type_attname = NameStr(type_attr->attname);
18942 : :
18943 : : /* Get the next non-dropped table attribute. */
18944 : : do
18945 : : {
18946 [ + + ]: 86 : if (table_attno > tableTupleDesc->natts)
18947 [ + - ]: 4 : ereport(ERROR,
18948 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18949 : : errmsg("table is missing column \"%s\"",
18950 : : type_attname)));
18951 : 82 : table_attr = TupleDescAttr(tableTupleDesc, table_attno - 1);
18952 : 82 : table_attno++;
18953 [ + + ]: 82 : } while (table_attr->attisdropped);
18954 : 74 : table_attname = NameStr(table_attr->attname);
18955 : :
18956 : : /* Compare name. */
18957 [ + + ]: 74 : if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
18958 [ + - ]: 4 : ereport(ERROR,
18959 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18960 : : errmsg("table has column \"%s\" where type requires \"%s\"",
18961 : : table_attname, type_attname)));
18962 : :
18963 : : /* Compare type. */
18964 [ + + ]: 70 : if (table_attr->atttypid != type_attr->atttypid ||
18965 [ + + ]: 66 : table_attr->atttypmod != type_attr->atttypmod ||
18966 [ - + ]: 62 : table_attr->attcollation != type_attr->attcollation)
18967 [ + - ]: 8 : ereport(ERROR,
18968 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18969 : : errmsg("table \"%s\" has different type for column \"%s\"",
18970 : : RelationGetRelationName(rel), type_attname)));
18971 : : }
18972 [ + - ]: 26 : ReleaseTupleDesc(typeTupleDesc);
18973 : :
18974 : : /* Any remaining columns at the end of the table had better be dropped. */
18975 [ + + ]: 26 : for (; table_attno <= tableTupleDesc->natts; table_attno++)
18976 : : {
18977 : 4 : Form_pg_attribute table_attr = TupleDescAttr(tableTupleDesc,
18978 : : table_attno - 1);
18979 : :
18980 [ + - ]: 4 : if (!table_attr->attisdropped)
18981 [ + - ]: 4 : ereport(ERROR,
18982 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
18983 : : errmsg("table has extra column \"%s\"",
18984 : : NameStr(table_attr->attname))));
18985 : : }
18986 : :
18987 : : /* If the table was already typed, drop the existing dependency. */
18988 [ + + ]: 22 : if (rel->rd_rel->reloftype)
18989 : 4 : drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
18990 : : DEPENDENCY_NORMAL);
18991 : :
18992 : : /* Record a dependency on the new type. */
18993 : 22 : tableobj.classId = RelationRelationId;
18994 : 22 : tableobj.objectId = relid;
18995 : 22 : tableobj.objectSubId = 0;
18996 : 22 : typeobj.classId = TypeRelationId;
18997 : 22 : typeobj.objectId = typeid;
18998 : 22 : typeobj.objectSubId = 0;
18999 : 22 : recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
19000 : :
19001 : : /* Update pg_class.reloftype */
19002 : 22 : relationRelation = table_open(RelationRelationId, RowExclusiveLock);
19003 : 22 : classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
19004 [ - + ]: 22 : if (!HeapTupleIsValid(classtuple))
19005 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
19006 : 22 : ((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
19007 : 22 : CatalogTupleUpdate(relationRelation, &classtuple->t_self, classtuple);
19008 : :
19009 [ - + ]: 22 : InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
19010 : :
19011 : 22 : heap_freetuple(classtuple);
19012 : 22 : table_close(relationRelation, RowExclusiveLock);
19013 : :
19014 : 22 : ReleaseSysCache(typetuple);
19015 : :
19016 : 22 : return typeobj;
19017 : : }
19018 : :
19019 : : /*
19020 : : * ALTER TABLE NOT OF
19021 : : *
19022 : : * Detach a typed table from its originating type. Just clear reloftype and
19023 : : * remove the dependency.
19024 : : */
19025 : : static void
19026 : 4 : ATExecDropOf(Relation rel, LOCKMODE lockmode)
19027 : : {
19028 : 4 : Oid relid = RelationGetRelid(rel);
19029 : : Relation relationRelation;
19030 : : HeapTuple tuple;
19031 : :
19032 [ - + ]: 4 : if (!OidIsValid(rel->rd_rel->reloftype))
19033 [ # # ]: 0 : ereport(ERROR,
19034 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19035 : : errmsg("\"%s\" is not a typed table",
19036 : : RelationGetRelationName(rel))));
19037 : :
19038 : : /*
19039 : : * We don't bother to check ownership of the type --- ownership of the
19040 : : * table is presumed enough rights. No lock required on the type, either.
19041 : : */
19042 : :
19043 : 4 : drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
19044 : : DEPENDENCY_NORMAL);
19045 : :
19046 : : /* Clear pg_class.reloftype */
19047 : 4 : relationRelation = table_open(RelationRelationId, RowExclusiveLock);
19048 : 4 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
19049 [ - + ]: 4 : if (!HeapTupleIsValid(tuple))
19050 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
19051 : 4 : ((Form_pg_class) GETSTRUCT(tuple))->reloftype = InvalidOid;
19052 : 4 : CatalogTupleUpdate(relationRelation, &tuple->t_self, tuple);
19053 : :
19054 [ - + ]: 4 : InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
19055 : :
19056 : 4 : heap_freetuple(tuple);
19057 : 4 : table_close(relationRelation, RowExclusiveLock);
19058 : 4 : }
19059 : :
19060 : : /*
19061 : : * relation_mark_replica_identity: Update a table's replica identity
19062 : : *
19063 : : * Iff ri_type = REPLICA_IDENTITY_INDEX, indexOid must be the Oid of a suitable
19064 : : * index. Otherwise, it must be InvalidOid.
19065 : : *
19066 : : * Caller had better hold an exclusive lock on the relation, as the results
19067 : : * of running two of these concurrently wouldn't be pretty.
19068 : : */
19069 : : static void
19070 : 293 : relation_mark_replica_identity(Relation rel, char ri_type, Oid indexOid,
19071 : : bool is_internal)
19072 : : {
19073 : : Relation pg_index;
19074 : : Relation pg_class;
19075 : : HeapTuple pg_class_tuple;
19076 : : HeapTuple pg_index_tuple;
19077 : : Form_pg_class pg_class_form;
19078 : : Form_pg_index pg_index_form;
19079 : : ListCell *index;
19080 : :
19081 : : /*
19082 : : * Check whether relreplident has changed, and update it if so.
19083 : : */
19084 : 293 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
19085 : 293 : pg_class_tuple = SearchSysCacheCopy1(RELOID,
19086 : : ObjectIdGetDatum(RelationGetRelid(rel)));
19087 [ - + ]: 293 : if (!HeapTupleIsValid(pg_class_tuple))
19088 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation \"%s\"",
19089 : : RelationGetRelationName(rel));
19090 : 293 : pg_class_form = (Form_pg_class) GETSTRUCT(pg_class_tuple);
19091 [ + + ]: 293 : if (pg_class_form->relreplident != ri_type)
19092 : : {
19093 : 260 : pg_class_form->relreplident = ri_type;
19094 : 260 : CatalogTupleUpdate(pg_class, &pg_class_tuple->t_self, pg_class_tuple);
19095 : : }
19096 : 293 : table_close(pg_class, RowExclusiveLock);
19097 : 293 : heap_freetuple(pg_class_tuple);
19098 : :
19099 : : /*
19100 : : * Update the per-index indisreplident flags correctly.
19101 : : */
19102 : 293 : pg_index = table_open(IndexRelationId, RowExclusiveLock);
19103 [ + + + + : 772 : foreach(index, RelationGetIndexList(rel))
+ + ]
19104 : : {
19105 : 479 : Oid thisIndexOid = lfirst_oid(index);
19106 : 479 : bool dirty = false;
19107 : :
19108 : 479 : pg_index_tuple = SearchSysCacheCopy1(INDEXRELID,
19109 : : ObjectIdGetDatum(thisIndexOid));
19110 [ - + ]: 479 : if (!HeapTupleIsValid(pg_index_tuple))
19111 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", thisIndexOid);
19112 : 479 : pg_index_form = (Form_pg_index) GETSTRUCT(pg_index_tuple);
19113 : :
19114 [ + + ]: 479 : if (thisIndexOid == indexOid)
19115 : : {
19116 : : /* Set the bit if not already set. */
19117 [ + + ]: 159 : if (!pg_index_form->indisreplident)
19118 : : {
19119 : 147 : dirty = true;
19120 : 147 : pg_index_form->indisreplident = true;
19121 : : }
19122 : : }
19123 : : else
19124 : : {
19125 : : /* Unset the bit if set. */
19126 [ + + ]: 320 : if (pg_index_form->indisreplident)
19127 : : {
19128 : 34 : dirty = true;
19129 : 34 : pg_index_form->indisreplident = false;
19130 : : }
19131 : : }
19132 : :
19133 [ + + ]: 479 : if (dirty)
19134 : : {
19135 : 181 : CatalogTupleUpdate(pg_index, &pg_index_tuple->t_self, pg_index_tuple);
19136 [ - + ]: 181 : InvokeObjectPostAlterHookArg(IndexRelationId, thisIndexOid, 0,
19137 : : InvalidOid, is_internal);
19138 : :
19139 : : /*
19140 : : * Invalidate the relcache for the table, so that after we commit
19141 : : * all sessions will refresh the table's replica identity index
19142 : : * before attempting any UPDATE or DELETE on the table. (If we
19143 : : * changed the table's pg_class row above, then a relcache inval
19144 : : * is already queued due to that; but we might not have.)
19145 : : */
19146 : 181 : CacheInvalidateRelcache(rel);
19147 : : }
19148 : 479 : heap_freetuple(pg_index_tuple);
19149 : : }
19150 : :
19151 : 293 : table_close(pg_index, RowExclusiveLock);
19152 : 293 : }
19153 : :
19154 : : /*
19155 : : * ALTER TABLE <name> REPLICA IDENTITY ...
19156 : : */
19157 : : static void
19158 : 329 : ATExecReplicaIdentity(Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode)
19159 : : {
19160 : : Oid indexOid;
19161 : : Relation indexRel;
19162 : : int key;
19163 : :
19164 [ + + ]: 329 : if (stmt->identity_type == REPLICA_IDENTITY_DEFAULT)
19165 : : {
19166 : 5 : relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
19167 : 5 : return;
19168 : : }
19169 [ + + ]: 324 : else if (stmt->identity_type == REPLICA_IDENTITY_FULL)
19170 : : {
19171 : 99 : relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
19172 : 99 : return;
19173 : : }
19174 [ + + ]: 225 : else if (stmt->identity_type == REPLICA_IDENTITY_NOTHING)
19175 : : {
19176 : 30 : relation_mark_replica_identity(rel, stmt->identity_type, InvalidOid, true);
19177 : 30 : return;
19178 : : }
19179 [ - + ]: 195 : else if (stmt->identity_type == REPLICA_IDENTITY_INDEX)
19180 : : {
19181 : : /* fallthrough */ ;
19182 : : }
19183 : : else
19184 [ # # ]: 0 : elog(ERROR, "unexpected identity type %u", stmt->identity_type);
19185 : :
19186 : : /* Check that the index exists */
19187 : 195 : indexOid = get_relname_relid(stmt->name, rel->rd_rel->relnamespace);
19188 [ - + ]: 195 : if (!OidIsValid(indexOid))
19189 [ # # ]: 0 : ereport(ERROR,
19190 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
19191 : : errmsg("index \"%s\" for table \"%s\" does not exist",
19192 : : stmt->name, RelationGetRelationName(rel))));
19193 : :
19194 : 195 : indexRel = index_open(indexOid, ShareLock);
19195 : :
19196 : : /* Check that the index is on the relation we're altering. */
19197 [ + - ]: 195 : if (indexRel->rd_index == NULL ||
19198 [ + + ]: 195 : indexRel->rd_index->indrelid != RelationGetRelid(rel))
19199 [ + - ]: 4 : ereport(ERROR,
19200 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19201 : : errmsg("\"%s\" is not an index for table \"%s\"",
19202 : : RelationGetRelationName(indexRel),
19203 : : RelationGetRelationName(rel))));
19204 : :
19205 : : /*
19206 : : * The AM must support uniqueness, and the index must in fact be unique.
19207 : : * If we have a WITHOUT OVERLAPS constraint (identified by uniqueness +
19208 : : * exclusion), we can use that too.
19209 : : */
19210 [ + + ]: 191 : if ((!indexRel->rd_indam->amcanunique ||
19211 [ + + ]: 177 : !indexRel->rd_index->indisunique) &&
19212 [ + + - + ]: 18 : !(indexRel->rd_index->indisunique && indexRel->rd_index->indisexclusion))
19213 [ + - ]: 8 : ereport(ERROR,
19214 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19215 : : errmsg("cannot use non-unique index \"%s\" as replica identity",
19216 : : RelationGetRelationName(indexRel))));
19217 : : /* Deferred indexes are not guaranteed to be always unique. */
19218 [ + + ]: 183 : if (!indexRel->rd_index->indimmediate)
19219 [ + - ]: 8 : ereport(ERROR,
19220 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19221 : : errmsg("cannot use non-immediate index \"%s\" as replica identity",
19222 : : RelationGetRelationName(indexRel))));
19223 : : /* Expression indexes aren't supported. */
19224 [ + + ]: 175 : if (RelationGetIndexExpressions(indexRel) != NIL)
19225 [ + - ]: 4 : ereport(ERROR,
19226 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19227 : : errmsg("cannot use expression index \"%s\" as replica identity",
19228 : : RelationGetRelationName(indexRel))));
19229 : : /* Predicate indexes aren't supported. */
19230 [ + + ]: 171 : if (RelationGetIndexPredicate(indexRel) != NIL)
19231 [ + - ]: 4 : ereport(ERROR,
19232 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19233 : : errmsg("cannot use partial index \"%s\" as replica identity",
19234 : : RelationGetRelationName(indexRel))));
19235 : :
19236 : : /* Check index for nullable columns. */
19237 [ + + ]: 371 : for (key = 0; key < IndexRelationGetNumberOfKeyAttributes(indexRel); key++)
19238 : : {
19239 : 212 : int16 attno = indexRel->rd_index->indkey.values[key];
19240 : : Form_pg_attribute attr;
19241 : : HeapTuple contup;
19242 : : Form_pg_constraint conForm;
19243 : :
19244 : : /*
19245 : : * Reject any other system columns. (Going forward, we'll disallow
19246 : : * indexes containing such columns in the first place, but they might
19247 : : * exist in older branches.)
19248 : : */
19249 [ - + ]: 212 : if (attno <= 0)
19250 [ # # ]: 0 : ereport(ERROR,
19251 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
19252 : : errmsg("index \"%s\" cannot be used as replica identity because column %d is a system column",
19253 : : RelationGetRelationName(indexRel), attno)));
19254 : :
19255 : 212 : attr = TupleDescAttr(rel->rd_att, attno - 1);
19256 [ + + ]: 212 : if (!attr->attnotnull)
19257 [ + - ]: 4 : ereport(ERROR,
19258 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
19259 : : errmsg("index \"%s\" cannot be used as replica identity because column \"%s\" is nullable",
19260 : : RelationGetRelationName(indexRel),
19261 : : NameStr(attr->attname))));
19262 : :
19263 : : /*
19264 : : * Verify that the not-null constraint for the column is valid.
19265 : : */
19266 : 208 : contup = findNotNullConstraintAttnum(RelationGetRelid(rel), attno);
19267 [ - + ]: 208 : if (!HeapTupleIsValid(contup))
19268 [ # # ]: 0 : elog(ERROR, "cache lookup failed for not-null constraint on column \"%s\" of relation \"%s\"",
19269 : : NameStr(attr->attname), RelationGetRelationName(rel));
19270 : 208 : conForm = (Form_pg_constraint) GETSTRUCT(contup);
19271 [ + + ]: 208 : if (!conForm->convalidated)
19272 [ + - ]: 4 : ereport(ERROR,
19273 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
19274 : : errmsg("cannot use index \"%s\" as replica identity",
19275 : : RelationGetRelationName(indexRel)),
19276 : : /*- translator: third %s is a constraint characteristic such as NOT VALID */
19277 : : errdetail("The constraint \"%s\" on column \"%s\" is marked %s.",
19278 : : NameStr(conForm->conname), NameStr(attr->attname), "NOT VALID"),
19279 : : errhint("You might need to validate it using %s.",
19280 : : "ALTER TABLE ... VALIDATE CONSTRAINT"));
19281 : 204 : heap_freetuple(contup);
19282 : : }
19283 : :
19284 : : /* This index is suitable for use as a replica identity. Mark it. */
19285 : 159 : relation_mark_replica_identity(rel, stmt->identity_type, indexOid, true);
19286 : :
19287 : 159 : index_close(indexRel, NoLock);
19288 : : }
19289 : :
19290 : : /*
19291 : : * ALTER TABLE ENABLE/DISABLE ROW LEVEL SECURITY
19292 : : */
19293 : : static void
19294 : 252 : ATExecSetRowSecurity(Relation rel, bool rls)
19295 : : {
19296 : : Relation pg_class;
19297 : : Oid relid;
19298 : : HeapTuple tuple;
19299 : :
19300 : 252 : relid = RelationGetRelid(rel);
19301 : :
19302 : : /* Pull the record for this relation and update it */
19303 : 252 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
19304 : :
19305 : 252 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
19306 : :
19307 [ - + ]: 252 : if (!HeapTupleIsValid(tuple))
19308 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
19309 : :
19310 : 252 : ((Form_pg_class) GETSTRUCT(tuple))->relrowsecurity = rls;
19311 : 252 : CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
19312 : :
19313 [ + + ]: 252 : InvokeObjectPostAlterHook(RelationRelationId,
19314 : : RelationGetRelid(rel), 0);
19315 : :
19316 : 252 : table_close(pg_class, RowExclusiveLock);
19317 : 252 : heap_freetuple(tuple);
19318 : 252 : }
19319 : :
19320 : : /*
19321 : : * ALTER TABLE FORCE/NO FORCE ROW LEVEL SECURITY
19322 : : */
19323 : : static void
19324 : 85 : ATExecForceNoForceRowSecurity(Relation rel, bool force_rls)
19325 : : {
19326 : : Relation pg_class;
19327 : : Oid relid;
19328 : : HeapTuple tuple;
19329 : :
19330 : 85 : relid = RelationGetRelid(rel);
19331 : :
19332 : 85 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
19333 : :
19334 : 85 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
19335 : :
19336 [ - + ]: 85 : if (!HeapTupleIsValid(tuple))
19337 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
19338 : :
19339 : 85 : ((Form_pg_class) GETSTRUCT(tuple))->relforcerowsecurity = force_rls;
19340 : 85 : CatalogTupleUpdate(pg_class, &tuple->t_self, tuple);
19341 : :
19342 [ + + ]: 85 : InvokeObjectPostAlterHook(RelationRelationId,
19343 : : RelationGetRelid(rel), 0);
19344 : :
19345 : 85 : table_close(pg_class, RowExclusiveLock);
19346 : 85 : heap_freetuple(tuple);
19347 : 85 : }
19348 : :
19349 : : /*
19350 : : * ALTER FOREIGN TABLE <name> OPTIONS (...)
19351 : : */
19352 : : static void
19353 : 34 : ATExecGenericOptions(Relation rel, List *options)
19354 : : {
19355 : : Relation ftrel;
19356 : : ForeignServer *server;
19357 : : ForeignDataWrapper *fdw;
19358 : : HeapTuple tuple;
19359 : : bool isnull;
19360 : : Datum repl_val[Natts_pg_foreign_table];
19361 : : bool repl_null[Natts_pg_foreign_table];
19362 : : bool repl_repl[Natts_pg_foreign_table];
19363 : : Datum datum;
19364 : : Form_pg_foreign_table tableform;
19365 : :
19366 [ - + ]: 34 : if (options == NIL)
19367 : 0 : return;
19368 : :
19369 : 34 : ftrel = table_open(ForeignTableRelationId, RowExclusiveLock);
19370 : :
19371 : 34 : tuple = SearchSysCacheCopy1(FOREIGNTABLEREL,
19372 : : ObjectIdGetDatum(rel->rd_id));
19373 [ - + ]: 34 : if (!HeapTupleIsValid(tuple))
19374 [ # # ]: 0 : ereport(ERROR,
19375 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
19376 : : errmsg("foreign table \"%s\" does not exist",
19377 : : RelationGetRelationName(rel))));
19378 : 34 : tableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
19379 : 34 : server = GetForeignServer(tableform->ftserver);
19380 : 34 : fdw = GetForeignDataWrapper(server->fdwid);
19381 : :
19382 : 34 : memset(repl_val, 0, sizeof(repl_val));
19383 : 34 : memset(repl_null, false, sizeof(repl_null));
19384 : 34 : memset(repl_repl, false, sizeof(repl_repl));
19385 : :
19386 : : /* Extract the current options */
19387 : 34 : datum = SysCacheGetAttr(FOREIGNTABLEREL,
19388 : : tuple,
19389 : : Anum_pg_foreign_table_ftoptions,
19390 : : &isnull);
19391 [ + + ]: 34 : if (isnull)
19392 : 2 : datum = PointerGetDatum(NULL);
19393 : :
19394 : : /* Transform the options */
19395 : 34 : datum = transformGenericOptions(ForeignTableRelationId,
19396 : : datum,
19397 : : options,
19398 : : fdw->fdwvalidator);
19399 : :
19400 [ + - ]: 33 : if (DatumGetPointer(datum) != NULL)
19401 : 33 : repl_val[Anum_pg_foreign_table_ftoptions - 1] = datum;
19402 : : else
19403 : 0 : repl_null[Anum_pg_foreign_table_ftoptions - 1] = true;
19404 : :
19405 : 33 : repl_repl[Anum_pg_foreign_table_ftoptions - 1] = true;
19406 : :
19407 : : /* Everything looks good - update the tuple */
19408 : :
19409 : 33 : tuple = heap_modify_tuple(tuple, RelationGetDescr(ftrel),
19410 : : repl_val, repl_null, repl_repl);
19411 : :
19412 : 33 : CatalogTupleUpdate(ftrel, &tuple->t_self, tuple);
19413 : :
19414 : : /*
19415 : : * Invalidate relcache so that all sessions will refresh any cached plans
19416 : : * that might depend on the old options.
19417 : : */
19418 : 33 : CacheInvalidateRelcache(rel);
19419 : :
19420 [ - + ]: 33 : InvokeObjectPostAlterHook(ForeignTableRelationId,
19421 : : RelationGetRelid(rel), 0);
19422 : :
19423 : 33 : table_close(ftrel, RowExclusiveLock);
19424 : :
19425 : 33 : heap_freetuple(tuple);
19426 : : }
19427 : :
19428 : : /*
19429 : : * ALTER TABLE ALTER COLUMN SET COMPRESSION
19430 : : *
19431 : : * Return value is the address of the modified column
19432 : : */
19433 : : static ObjectAddress
19434 : 48 : ATExecSetCompression(Relation rel,
19435 : : const char *column,
19436 : : Node *newValue,
19437 : : LOCKMODE lockmode)
19438 : : {
19439 : : Relation attrel;
19440 : : HeapTuple tuple;
19441 : : Form_pg_attribute atttableform;
19442 : : AttrNumber attnum;
19443 : : char *compression;
19444 : : char cmethod;
19445 : : ObjectAddress address;
19446 : :
19447 : 48 : compression = strVal(newValue);
19448 : :
19449 : 48 : attrel = table_open(AttributeRelationId, RowExclusiveLock);
19450 : :
19451 : : /* copy the cache entry so we can scribble on it below */
19452 : 48 : tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), column);
19453 [ - + ]: 48 : if (!HeapTupleIsValid(tuple))
19454 [ # # ]: 0 : ereport(ERROR,
19455 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
19456 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
19457 : : column, RelationGetRelationName(rel))));
19458 : :
19459 : : /* prevent them from altering a system attribute */
19460 : 48 : atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
19461 : 48 : attnum = atttableform->attnum;
19462 [ - + ]: 48 : if (attnum <= 0)
19463 [ # # ]: 0 : ereport(ERROR,
19464 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19465 : : errmsg("cannot alter system column \"%s\"", column)));
19466 : :
19467 : : /*
19468 : : * Check that column type is compressible, then get the attribute
19469 : : * compression method code
19470 : : */
19471 : 48 : cmethod = GetAttributeCompression(atttableform->atttypid, compression);
19472 : :
19473 : : /* update pg_attribute entry */
19474 : 44 : atttableform->attcompression = cmethod;
19475 : 44 : CatalogTupleUpdate(attrel, &tuple->t_self, tuple);
19476 : :
19477 [ - + ]: 44 : InvokeObjectPostAlterHook(RelationRelationId,
19478 : : RelationGetRelid(rel),
19479 : : attnum);
19480 : :
19481 : : /*
19482 : : * Apply the change to indexes as well (only for simple index columns,
19483 : : * matching behavior of index.c ConstructTupleDescriptor()).
19484 : : */
19485 : 44 : SetIndexStorageProperties(rel, attrel, attnum,
19486 : : false, 0,
19487 : : true, cmethod,
19488 : : lockmode);
19489 : :
19490 : 44 : heap_freetuple(tuple);
19491 : :
19492 : 44 : table_close(attrel, RowExclusiveLock);
19493 : :
19494 : : /* make changes visible */
19495 : 44 : CommandCounterIncrement();
19496 : :
19497 : 44 : ObjectAddressSubSet(address, RelationRelationId,
19498 : : RelationGetRelid(rel), attnum);
19499 : 44 : return address;
19500 : : }
19501 : :
19502 : :
19503 : : /*
19504 : : * Preparation phase for SET LOGGED/UNLOGGED
19505 : : *
19506 : : * This verifies that we're not trying to change a temp table. Also,
19507 : : * existing foreign key constraints are checked to avoid ending up with
19508 : : * permanent tables referencing unlogged tables.
19509 : : */
19510 : : static void
19511 : 71 : ATPrepChangePersistence(AlteredTableInfo *tab, Relation rel, bool toLogged)
19512 : : {
19513 : : Relation pg_constraint;
19514 : : HeapTuple tuple;
19515 : : SysScanDesc scan;
19516 : : ScanKeyData skey[1];
19517 : :
19518 : : /*
19519 : : * Disallow changing status for a temp table. Also verify whether we can
19520 : : * get away with doing nothing; in such cases we don't need to run the
19521 : : * checks below, either.
19522 : : */
19523 [ - + + - ]: 71 : switch (rel->rd_rel->relpersistence)
19524 : : {
19525 : 0 : case RELPERSISTENCE_TEMP:
19526 [ # # ]: 0 : ereport(ERROR,
19527 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
19528 : : errmsg("cannot change logged status of table \"%s\" because it is temporary",
19529 : : RelationGetRelationName(rel)),
19530 : : errtable(rel)));
19531 : : break;
19532 : 41 : case RELPERSISTENCE_PERMANENT:
19533 [ + + ]: 41 : if (toLogged)
19534 : : /* nothing to do */
19535 : 8 : return;
19536 : 37 : break;
19537 : 30 : case RELPERSISTENCE_UNLOGGED:
19538 [ + + ]: 30 : if (!toLogged)
19539 : : /* nothing to do */
19540 : 4 : return;
19541 : 26 : break;
19542 : : }
19543 : :
19544 : : /*
19545 : : * UNLOGGED tables can neither be published nor be named in a
19546 : : * publication's EXCEPT clause, so reject the change if the table is
19547 : : * referenced by any publication.
19548 : : */
19549 [ + + + + ]: 63 : if (!toLogged && RelationHasPublication(RelationGetRelid(rel)))
19550 [ + - ]: 4 : ereport(ERROR,
19551 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
19552 : : errmsg("cannot change table \"%s\" to unlogged because it is referenced by a publication",
19553 : : RelationGetRelationName(rel)),
19554 : : errdetail("Unlogged relations cannot be published or excluded via an EXCEPT clause."),
19555 : : errhint("Drop the table from the publication, or remove it from the publication's EXCEPT clause, first.")));
19556 : :
19557 : : /*
19558 : : * Check existing foreign key constraints to preserve the invariant that
19559 : : * permanent tables cannot reference unlogged ones. Self-referencing
19560 : : * foreign keys can safely be ignored.
19561 : : */
19562 : 59 : pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
19563 : :
19564 : : /*
19565 : : * Scan conrelid if changing to permanent, else confrelid. This also
19566 : : * determines whether a useful index exists.
19567 : : */
19568 [ + + ]: 59 : ScanKeyInit(&skey[0],
19569 : : toLogged ? Anum_pg_constraint_conrelid :
19570 : : Anum_pg_constraint_confrelid,
19571 : : BTEqualStrategyNumber, F_OIDEQ,
19572 : : ObjectIdGetDatum(RelationGetRelid(rel)));
19573 [ + + ]: 59 : scan = systable_beginscan(pg_constraint,
19574 : : toLogged ? ConstraintRelidTypidNameIndexId : InvalidOid,
19575 : : true, NULL, 1, skey);
19576 : :
19577 [ + + ]: 95 : while (HeapTupleIsValid(tuple = systable_getnext(scan)))
19578 : : {
19579 : 44 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
19580 : :
19581 [ + + ]: 44 : if (con->contype == CONSTRAINT_FOREIGN)
19582 : : {
19583 : : Oid foreignrelid;
19584 : : Relation foreignrel;
19585 : :
19586 : : /* the opposite end of what we used as scankey */
19587 [ + + ]: 20 : foreignrelid = toLogged ? con->confrelid : con->conrelid;
19588 : :
19589 : : /* ignore if self-referencing */
19590 [ + + ]: 20 : if (RelationGetRelid(rel) == foreignrelid)
19591 : 8 : continue;
19592 : :
19593 : 12 : foreignrel = relation_open(foreignrelid, AccessShareLock);
19594 : :
19595 [ + + ]: 12 : if (toLogged)
19596 : : {
19597 [ + - ]: 4 : if (!RelationIsPermanent(foreignrel))
19598 [ + - ]: 4 : ereport(ERROR,
19599 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
19600 : : errmsg("could not change table \"%s\" to logged because it references unlogged table \"%s\"",
19601 : : RelationGetRelationName(rel),
19602 : : RelationGetRelationName(foreignrel)),
19603 : : errtableconstraint(rel, NameStr(con->conname))));
19604 : : }
19605 : : else
19606 : : {
19607 [ + + ]: 8 : if (RelationIsPermanent(foreignrel))
19608 [ + - ]: 4 : ereport(ERROR,
19609 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
19610 : : errmsg("could not change table \"%s\" to unlogged because it references logged table \"%s\"",
19611 : : RelationGetRelationName(rel),
19612 : : RelationGetRelationName(foreignrel)),
19613 : : errtableconstraint(rel, NameStr(con->conname))));
19614 : : }
19615 : :
19616 : 4 : relation_close(foreignrel, AccessShareLock);
19617 : : }
19618 : : }
19619 : :
19620 : 51 : systable_endscan(scan);
19621 : :
19622 : 51 : table_close(pg_constraint, AccessShareLock);
19623 : :
19624 : : /* force rewrite if necessary; see comment in ATRewriteTables */
19625 : 51 : tab->rewrite |= AT_REWRITE_ALTER_PERSISTENCE;
19626 [ + + ]: 51 : if (toLogged)
19627 : 22 : tab->newrelpersistence = RELPERSISTENCE_PERMANENT;
19628 : : else
19629 : 29 : tab->newrelpersistence = RELPERSISTENCE_UNLOGGED;
19630 : 51 : tab->chgPersistence = true;
19631 : : }
19632 : :
19633 : : /*
19634 : : * Execute ALTER TABLE SET SCHEMA
19635 : : */
19636 : : ObjectAddress
19637 : 76 : AlterTableNamespace(AlterObjectSchemaStmt *stmt, Oid *oldschema)
19638 : : {
19639 : : Relation rel;
19640 : : Oid relid;
19641 : : Oid oldNspOid;
19642 : : Oid nspOid;
19643 : : RangeVar *newrv;
19644 : : ObjectAddresses *objsMoved;
19645 : : ObjectAddress myself;
19646 : :
19647 : 76 : relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
19648 : 76 : stmt->missing_ok ? RVR_MISSING_OK : 0,
19649 : : RangeVarCallbackForAlterRelation,
19650 : : stmt);
19651 : :
19652 [ + + ]: 71 : if (!OidIsValid(relid))
19653 : : {
19654 [ + - ]: 8 : ereport(NOTICE,
19655 : : (errmsg("relation \"%s\" does not exist, skipping",
19656 : : stmt->relation->relname)));
19657 : 8 : return InvalidObjectAddress;
19658 : : }
19659 : :
19660 : 63 : rel = relation_open(relid, NoLock);
19661 : :
19662 : 63 : oldNspOid = RelationGetNamespace(rel);
19663 : :
19664 : : /* If it's an owned sequence, disallow moving it by itself. */
19665 [ + + ]: 63 : if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
19666 : : {
19667 : : Oid tableId;
19668 : : int32 colId;
19669 : :
19670 [ + + - + ]: 6 : if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
19671 : 1 : sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
19672 [ + - ]: 4 : ereport(ERROR,
19673 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
19674 : : errmsg("cannot move an owned sequence into another schema"),
19675 : : errdetail("Sequence \"%s\" is linked to table \"%s\".",
19676 : : RelationGetRelationName(rel),
19677 : : get_rel_name(tableId))));
19678 : : }
19679 : :
19680 : : /* Get and lock schema OID and check its permissions. */
19681 : 59 : newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
19682 : 59 : nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
19683 : :
19684 : : /* common checks on switching namespaces */
19685 : 55 : CheckSetNamespace(oldNspOid, nspOid);
19686 : :
19687 : 55 : objsMoved = new_object_addresses();
19688 : 55 : AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
19689 : 55 : free_object_addresses(objsMoved);
19690 : :
19691 : 55 : ObjectAddressSet(myself, RelationRelationId, relid);
19692 : :
19693 [ + - ]: 55 : if (oldschema)
19694 : 55 : *oldschema = oldNspOid;
19695 : :
19696 : : /* close rel, but keep lock until commit */
19697 : 55 : relation_close(rel, NoLock);
19698 : :
19699 : 55 : return myself;
19700 : : }
19701 : :
19702 : : /*
19703 : : * The guts of relocating a table or materialized view to another namespace:
19704 : : * besides moving the relation itself, its dependent objects are relocated to
19705 : : * the new schema.
19706 : : */
19707 : : void
19708 : 56 : AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid,
19709 : : ObjectAddresses *objsMoved)
19710 : : {
19711 : : Relation classRel;
19712 : :
19713 : : Assert(objsMoved != NULL);
19714 : :
19715 : : /* OK, modify the pg_class row and pg_depend entry */
19716 : 56 : classRel = table_open(RelationRelationId, RowExclusiveLock);
19717 : :
19718 : 56 : AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
19719 : : nspOid, true, objsMoved);
19720 : :
19721 : : /* Fix the table's row type too, if it has one */
19722 [ + + ]: 56 : if (OidIsValid(rel->rd_rel->reltype))
19723 : 55 : AlterTypeNamespaceInternal(rel->rd_rel->reltype, nspOid,
19724 : : false, /* isImplicitArray */
19725 : : false, /* ignoreDependent */
19726 : : false, /* errorOnTableType */
19727 : : objsMoved);
19728 : :
19729 : : /* Fix other dependent stuff */
19730 : 56 : AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
19731 : 56 : AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
19732 : : objsMoved, AccessExclusiveLock);
19733 : 56 : AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
19734 : : false, objsMoved);
19735 : :
19736 : 56 : table_close(classRel, RowExclusiveLock);
19737 : 56 : }
19738 : :
19739 : : /*
19740 : : * The guts of relocating a relation to another namespace: fix the pg_class
19741 : : * entry, and the pg_depend entry if any. Caller must already have
19742 : : * opened and write-locked pg_class.
19743 : : */
19744 : : void
19745 : 123 : AlterRelationNamespaceInternal(Relation classRel, Oid relOid,
19746 : : Oid oldNspOid, Oid newNspOid,
19747 : : bool hasDependEntry,
19748 : : ObjectAddresses *objsMoved)
19749 : : {
19750 : : HeapTuple classTup;
19751 : : Form_pg_class classForm;
19752 : : ObjectAddress thisobj;
19753 : 123 : bool already_done = false;
19754 : :
19755 : : /* no rel lock for relkind=c so use LOCKTAG_TUPLE */
19756 : 123 : classTup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(relOid));
19757 [ - + ]: 123 : if (!HeapTupleIsValid(classTup))
19758 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relOid);
19759 : 123 : classForm = (Form_pg_class) GETSTRUCT(classTup);
19760 : :
19761 : : Assert(classForm->relnamespace == oldNspOid);
19762 : :
19763 : 123 : thisobj.classId = RelationRelationId;
19764 : 123 : thisobj.objectId = relOid;
19765 : 123 : thisobj.objectSubId = 0;
19766 : :
19767 : : /*
19768 : : * If the object has already been moved, don't move it again. If it's
19769 : : * already in the right place, don't move it, but still fire the object
19770 : : * access hook.
19771 : : */
19772 : 123 : already_done = object_address_present(&thisobj, objsMoved);
19773 [ + - + + ]: 123 : if (!already_done && oldNspOid != newNspOid)
19774 : 95 : {
19775 : 95 : ItemPointerData otid = classTup->t_self;
19776 : :
19777 : : /* check for duplicate name (more friendly than unique-index failure) */
19778 [ - + ]: 95 : if (get_relname_relid(NameStr(classForm->relname),
19779 : : newNspOid) != InvalidOid)
19780 [ # # ]: 0 : ereport(ERROR,
19781 : : (errcode(ERRCODE_DUPLICATE_TABLE),
19782 : : errmsg("relation \"%s\" already exists in schema \"%s\"",
19783 : : NameStr(classForm->relname),
19784 : : get_namespace_name(newNspOid))));
19785 : :
19786 : : /* classTup is a copy, so OK to scribble on */
19787 : 95 : classForm->relnamespace = newNspOid;
19788 : :
19789 : 95 : CatalogTupleUpdate(classRel, &otid, classTup);
19790 : 95 : UnlockTuple(classRel, &otid, InplaceUpdateTupleLock);
19791 : :
19792 : :
19793 : : /* Update dependency on schema if caller said so */
19794 [ + + - + ]: 163 : if (hasDependEntry &&
19795 : 68 : changeDependencyFor(RelationRelationId,
19796 : : relOid,
19797 : : NamespaceRelationId,
19798 : : oldNspOid,
19799 : : newNspOid) != 1)
19800 [ # # ]: 0 : elog(ERROR, "could not change schema dependency for relation \"%s\"",
19801 : : NameStr(classForm->relname));
19802 : : }
19803 : : else
19804 : 28 : UnlockTuple(classRel, &classTup->t_self, InplaceUpdateTupleLock);
19805 [ + - ]: 123 : if (!already_done)
19806 : : {
19807 : 123 : add_exact_object_address(&thisobj, objsMoved);
19808 : :
19809 [ - + ]: 123 : InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
19810 : : }
19811 : :
19812 : 123 : heap_freetuple(classTup);
19813 : 123 : }
19814 : :
19815 : : /*
19816 : : * Move all indexes for the specified relation to another namespace.
19817 : : *
19818 : : * Note: we assume adequate permission checking was done by the caller,
19819 : : * and that the caller has a suitable lock on the owning relation.
19820 : : */
19821 : : static void
19822 : 56 : AlterIndexNamespaces(Relation classRel, Relation rel,
19823 : : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
19824 : : {
19825 : : List *indexList;
19826 : : ListCell *l;
19827 : :
19828 : 56 : indexList = RelationGetIndexList(rel);
19829 : :
19830 [ + + + + : 86 : foreach(l, indexList)
+ + ]
19831 : : {
19832 : 30 : Oid indexOid = lfirst_oid(l);
19833 : : ObjectAddress thisobj;
19834 : :
19835 : 30 : thisobj.classId = RelationRelationId;
19836 : 30 : thisobj.objectId = indexOid;
19837 : 30 : thisobj.objectSubId = 0;
19838 : :
19839 : : /*
19840 : : * Note: currently, the index will not have its own dependency on the
19841 : : * namespace, so we don't need to do changeDependencyFor(). There's no
19842 : : * row type in pg_type, either.
19843 : : *
19844 : : * XXX this objsMoved test may be pointless -- surely we have a single
19845 : : * dependency link from a relation to each index?
19846 : : */
19847 [ + - ]: 30 : if (!object_address_present(&thisobj, objsMoved))
19848 : : {
19849 : 30 : AlterRelationNamespaceInternal(classRel, indexOid,
19850 : : oldNspOid, newNspOid,
19851 : : false, objsMoved);
19852 : 30 : add_exact_object_address(&thisobj, objsMoved);
19853 : : }
19854 : : }
19855 : :
19856 : 56 : list_free(indexList);
19857 : 56 : }
19858 : :
19859 : : /*
19860 : : * Move all identity and SERIAL-column sequences of the specified relation to another
19861 : : * namespace.
19862 : : *
19863 : : * Note: we assume adequate permission checking was done by the caller,
19864 : : * and that the caller has a suitable lock on the owning relation.
19865 : : */
19866 : : static void
19867 : 56 : AlterSeqNamespaces(Relation classRel, Relation rel,
19868 : : Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved,
19869 : : LOCKMODE lockmode)
19870 : : {
19871 : : Relation depRel;
19872 : : SysScanDesc scan;
19873 : : ScanKeyData key[2];
19874 : : HeapTuple tup;
19875 : :
19876 : : /*
19877 : : * SERIAL sequences are those having an auto dependency on one of the
19878 : : * table's columns (we don't care *which* column, exactly).
19879 : : */
19880 : 56 : depRel = table_open(DependRelationId, AccessShareLock);
19881 : :
19882 : 56 : ScanKeyInit(&key[0],
19883 : : Anum_pg_depend_refclassid,
19884 : : BTEqualStrategyNumber, F_OIDEQ,
19885 : : ObjectIdGetDatum(RelationRelationId));
19886 : 56 : ScanKeyInit(&key[1],
19887 : : Anum_pg_depend_refobjid,
19888 : : BTEqualStrategyNumber, F_OIDEQ,
19889 : : ObjectIdGetDatum(RelationGetRelid(rel)));
19890 : : /* we leave refobjsubid unspecified */
19891 : :
19892 : 56 : scan = systable_beginscan(depRel, DependReferenceIndexId, true,
19893 : : NULL, 2, key);
19894 : :
19895 [ + + ]: 405 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
19896 : : {
19897 : 349 : Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
19898 : : Relation seqRel;
19899 : :
19900 : : /* skip dependencies other than auto dependencies on columns */
19901 [ + + ]: 349 : if (depForm->refobjsubid == 0 ||
19902 [ + + ]: 252 : depForm->classid != RelationRelationId ||
19903 [ + - ]: 28 : depForm->objsubid != 0 ||
19904 [ - + - - ]: 28 : !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
19905 : 321 : continue;
19906 : :
19907 : : /* Use relation_open just in case it's an index */
19908 : 28 : seqRel = relation_open(depForm->objid, lockmode);
19909 : :
19910 : : /* skip non-sequence relations */
19911 [ - + ]: 28 : if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
19912 : : {
19913 : : /* No need to keep the lock */
19914 : 0 : relation_close(seqRel, lockmode);
19915 : 0 : continue;
19916 : : }
19917 : :
19918 : : /* Fix the pg_class and pg_depend entries */
19919 : 28 : AlterRelationNamespaceInternal(classRel, depForm->objid,
19920 : : oldNspOid, newNspOid,
19921 : : true, objsMoved);
19922 : :
19923 : : /*
19924 : : * Sequences used to have entries in pg_type, but no longer do. If we
19925 : : * ever re-instate that, we'll need to move the pg_type entry to the
19926 : : * new namespace, too (using AlterTypeNamespaceInternal).
19927 : : */
19928 : : Assert(RelationGetForm(seqRel)->reltype == InvalidOid);
19929 : :
19930 : : /* Now we can close it. Keep the lock till end of transaction. */
19931 : 28 : relation_close(seqRel, NoLock);
19932 : : }
19933 : :
19934 : 56 : systable_endscan(scan);
19935 : :
19936 : 56 : relation_close(depRel, AccessShareLock);
19937 : 56 : }
19938 : :
19939 : :
19940 : : /*
19941 : : * This code supports
19942 : : * CREATE TEMP TABLE ... ON COMMIT { DROP | PRESERVE ROWS | DELETE ROWS }
19943 : : *
19944 : : * Because we only support this for TEMP tables, it's sufficient to remember
19945 : : * the state in a backend-local data structure.
19946 : : */
19947 : :
19948 : : /*
19949 : : * Register a newly-created relation's ON COMMIT action.
19950 : : */
19951 : : void
19952 : 116 : register_on_commit_action(Oid relid, OnCommitAction action)
19953 : : {
19954 : : OnCommitItem *oc;
19955 : : MemoryContext oldcxt;
19956 : :
19957 : : /*
19958 : : * We needn't bother registering the relation unless there is an ON COMMIT
19959 : : * action we need to take.
19960 : : */
19961 [ + - + + ]: 116 : if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
19962 : 16 : return;
19963 : :
19964 : 100 : oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
19965 : :
19966 : 100 : oc = palloc_object(OnCommitItem);
19967 : 100 : oc->relid = relid;
19968 : 100 : oc->oncommit = action;
19969 : 100 : oc->creating_subid = GetCurrentSubTransactionId();
19970 : 100 : oc->deleting_subid = InvalidSubTransactionId;
19971 : :
19972 : : /*
19973 : : * We use lcons() here so that ON COMMIT actions are processed in reverse
19974 : : * order of registration. That might not be essential but it seems
19975 : : * reasonable.
19976 : : */
19977 : 100 : on_commits = lcons(oc, on_commits);
19978 : :
19979 : 100 : MemoryContextSwitchTo(oldcxt);
19980 : : }
19981 : :
19982 : : /*
19983 : : * Unregister any ON COMMIT action when a relation is deleted.
19984 : : *
19985 : : * Actually, we only mark the OnCommitItem entry as to be deleted after commit.
19986 : : */
19987 : : void
19988 : 32419 : remove_on_commit_action(Oid relid)
19989 : : {
19990 : : ListCell *l;
19991 : :
19992 [ + + + + : 32516 : foreach(l, on_commits)
+ + ]
19993 : : {
19994 : 189 : OnCommitItem *oc = (OnCommitItem *) lfirst(l);
19995 : :
19996 [ + + ]: 189 : if (oc->relid == relid)
19997 : : {
19998 : 92 : oc->deleting_subid = GetCurrentSubTransactionId();
19999 : 92 : break;
20000 : : }
20001 : : }
20002 : 32419 : }
20003 : :
20004 : : /*
20005 : : * Perform ON COMMIT actions.
20006 : : *
20007 : : * This is invoked just before actually committing, since it's possible
20008 : : * to encounter errors.
20009 : : */
20010 : : void
20011 : 612709 : PreCommit_on_commit_actions(void)
20012 : : {
20013 : : ListCell *l;
20014 : 612709 : List *oids_to_truncate = NIL;
20015 : 612709 : List *oids_to_drop = NIL;
20016 : :
20017 [ + + + + : 613256 : foreach(l, on_commits)
+ + ]
20018 : : {
20019 : 547 : OnCommitItem *oc = (OnCommitItem *) lfirst(l);
20020 : :
20021 : : /* Ignore entry if already dropped in this xact */
20022 [ + + ]: 547 : if (oc->deleting_subid != InvalidSubTransactionId)
20023 : 49 : continue;
20024 : :
20025 [ - + + - ]: 498 : switch (oc->oncommit)
20026 : : {
20027 : 0 : case ONCOMMIT_NOOP:
20028 : : case ONCOMMIT_PRESERVE_ROWS:
20029 : : /* Do nothing (there shouldn't be such entries, actually) */
20030 : 0 : break;
20031 : 463 : case ONCOMMIT_DELETE_ROWS:
20032 : :
20033 : : /*
20034 : : * If this transaction hasn't accessed any temporary
20035 : : * relations, we can skip truncating ON COMMIT DELETE ROWS
20036 : : * tables, as they must still be empty.
20037 : : */
20038 [ + + ]: 463 : if ((MyXactFlags & XACT_FLAGS_ACCESSEDTEMPNAMESPACE))
20039 : 298 : oids_to_truncate = lappend_oid(oids_to_truncate, oc->relid);
20040 : 463 : break;
20041 : 35 : case ONCOMMIT_DROP:
20042 : 35 : oids_to_drop = lappend_oid(oids_to_drop, oc->relid);
20043 : 35 : break;
20044 : : }
20045 : : }
20046 : :
20047 : : /*
20048 : : * Truncate relations before dropping so that all dependencies between
20049 : : * relations are removed after they are worked on. Doing it like this
20050 : : * might be a waste as it is possible that a relation being truncated will
20051 : : * be dropped anyway due to its parent being dropped, but this makes the
20052 : : * code more robust because of not having to re-check that the relation
20053 : : * exists at truncation time.
20054 : : */
20055 [ + + ]: 612709 : if (oids_to_truncate != NIL)
20056 : 254 : heap_truncate(oids_to_truncate);
20057 : :
20058 [ + + ]: 612705 : if (oids_to_drop != NIL)
20059 : : {
20060 : 31 : ObjectAddresses *targetObjects = new_object_addresses();
20061 : :
20062 [ + - + + : 66 : foreach(l, oids_to_drop)
+ + ]
20063 : : {
20064 : : ObjectAddress object;
20065 : :
20066 : 35 : object.classId = RelationRelationId;
20067 : 35 : object.objectId = lfirst_oid(l);
20068 : 35 : object.objectSubId = 0;
20069 : :
20070 : : Assert(!object_address_present(&object, targetObjects));
20071 : :
20072 : 35 : add_exact_object_address(&object, targetObjects);
20073 : : }
20074 : :
20075 : : /*
20076 : : * Object deletion might involve toast table access (to clean up
20077 : : * toasted catalog entries), so ensure we have a valid snapshot.
20078 : : */
20079 : 31 : PushActiveSnapshot(GetTransactionSnapshot());
20080 : :
20081 : : /*
20082 : : * Since this is an automatic drop, rather than one directly initiated
20083 : : * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
20084 : : */
20085 : 31 : performMultipleDeletions(targetObjects, DROP_CASCADE,
20086 : : PERFORM_DELETION_INTERNAL | PERFORM_DELETION_QUIETLY);
20087 : :
20088 : 31 : PopActiveSnapshot();
20089 : :
20090 : : #ifdef USE_ASSERT_CHECKING
20091 : :
20092 : : /*
20093 : : * Note that table deletion will call remove_on_commit_action, so the
20094 : : * entry should get marked as deleted.
20095 : : */
20096 : : foreach(l, on_commits)
20097 : : {
20098 : : OnCommitItem *oc = (OnCommitItem *) lfirst(l);
20099 : :
20100 : : if (oc->oncommit != ONCOMMIT_DROP)
20101 : : continue;
20102 : :
20103 : : Assert(oc->deleting_subid != InvalidSubTransactionId);
20104 : : }
20105 : : #endif
20106 : : }
20107 : 612705 : }
20108 : :
20109 : : /*
20110 : : * Post-commit or post-abort cleanup for ON COMMIT management.
20111 : : *
20112 : : * All we do here is remove no-longer-needed OnCommitItem entries.
20113 : : *
20114 : : * During commit, remove entries that were deleted during this transaction;
20115 : : * during abort, remove those created during this transaction.
20116 : : */
20117 : : void
20118 : 648035 : AtEOXact_on_commit_actions(bool isCommit)
20119 : : {
20120 : : ListCell *cur_item;
20121 : :
20122 [ + + + + : 648602 : foreach(cur_item, on_commits)
+ + ]
20123 : : {
20124 : 567 : OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
20125 : :
20126 [ + + + + ]: 635 : if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
20127 : 68 : oc->creating_subid != InvalidSubTransactionId)
20128 : : {
20129 : : /* cur_item must be removed */
20130 : 100 : on_commits = foreach_delete_current(on_commits, cur_item);
20131 : 100 : pfree(oc);
20132 : : }
20133 : : else
20134 : : {
20135 : : /* cur_item must be preserved */
20136 : 467 : oc->creating_subid = InvalidSubTransactionId;
20137 : 467 : oc->deleting_subid = InvalidSubTransactionId;
20138 : : }
20139 : : }
20140 : 648035 : }
20141 : :
20142 : : /*
20143 : : * Post-subcommit or post-subabort cleanup for ON COMMIT management.
20144 : : *
20145 : : * During subabort, we can immediately remove entries created during this
20146 : : * subtransaction. During subcommit, just relabel entries marked during
20147 : : * this subtransaction as being the parent's responsibility.
20148 : : */
20149 : : void
20150 : 22903 : AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid,
20151 : : SubTransactionId parentSubid)
20152 : : {
20153 : : ListCell *cur_item;
20154 : :
20155 [ - + - - : 22903 : foreach(cur_item, on_commits)
- + ]
20156 : : {
20157 : 0 : OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
20158 : :
20159 [ # # # # ]: 0 : if (!isCommit && oc->creating_subid == mySubid)
20160 : : {
20161 : : /* cur_item must be removed */
20162 : 0 : on_commits = foreach_delete_current(on_commits, cur_item);
20163 : 0 : pfree(oc);
20164 : : }
20165 : : else
20166 : : {
20167 : : /* cur_item must be preserved */
20168 [ # # ]: 0 : if (oc->creating_subid == mySubid)
20169 : 0 : oc->creating_subid = parentSubid;
20170 [ # # ]: 0 : if (oc->deleting_subid == mySubid)
20171 [ # # ]: 0 : oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
20172 : : }
20173 : : }
20174 : 22903 : }
20175 : :
20176 : : /*
20177 : : * This is intended as a callback for RangeVarGetRelidExtended(). It allows
20178 : : * the relation to be locked only if (1) it's a plain or partitioned table,
20179 : : * materialized view, or TOAST table and (2) the current user is the owner (or
20180 : : * the superuser) or has been granted MAINTAIN. This meets the
20181 : : * permission-checking needs of CLUSTER, REPACK, REINDEX TABLE, and REFRESH
20182 : : * MATERIALIZED VIEW; we expose it here so that it can be used by all.
20183 : : */
20184 : : void
20185 : 741 : RangeVarCallbackMaintainsTable(const RangeVar *relation,
20186 : : Oid relId, Oid oldRelId, void *arg)
20187 : : {
20188 : : char relkind;
20189 : : AclResult aclresult;
20190 : :
20191 : : /* Nothing to do if the relation was not found. */
20192 [ + + ]: 741 : if (!OidIsValid(relId))
20193 : 3 : return;
20194 : :
20195 : : /*
20196 : : * If the relation does exist, check whether it's an index. But note that
20197 : : * the relation might have been dropped between the time we did the name
20198 : : * lookup and now. In that case, there's nothing to do.
20199 : : */
20200 : 738 : relkind = get_rel_relkind(relId);
20201 [ - + ]: 738 : if (!relkind)
20202 : 0 : return;
20203 [ + + + + : 738 : if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
+ + ]
20204 [ + + ]: 102 : relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
20205 [ + - ]: 18 : ereport(ERROR,
20206 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20207 : : errmsg("\"%s\" is not a table or materialized view", relation->relname)));
20208 : :
20209 : : /* Check permissions */
20210 : 720 : aclresult = pg_class_aclcheck(relId, GetUserId(), ACL_MAINTAIN);
20211 [ + + ]: 720 : if (aclresult != ACLCHECK_OK)
20212 : 20 : aclcheck_error(aclresult,
20213 : 20 : get_relkind_objtype(get_rel_relkind(relId)),
20214 : 20 : relation->relname);
20215 : : }
20216 : :
20217 : : /*
20218 : : * Callback to RangeVarGetRelidExtended() for TRUNCATE processing.
20219 : : */
20220 : : static void
20221 : 1433 : RangeVarCallbackForTruncate(const RangeVar *relation,
20222 : : Oid relId, Oid oldRelId, void *arg)
20223 : : {
20224 : : HeapTuple tuple;
20225 : :
20226 : : /* Nothing to do if the relation was not found. */
20227 [ - + ]: 1433 : if (!OidIsValid(relId))
20228 : 0 : return;
20229 : :
20230 : 1433 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
20231 [ - + ]: 1433 : if (!HeapTupleIsValid(tuple)) /* should not happen */
20232 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relId);
20233 : :
20234 : 1433 : truncate_check_rel(relId, (Form_pg_class) GETSTRUCT(tuple));
20235 : 1430 : truncate_check_perms(relId, (Form_pg_class) GETSTRUCT(tuple));
20236 : :
20237 : 1410 : ReleaseSysCache(tuple);
20238 : : }
20239 : :
20240 : : /*
20241 : : * Callback for RangeVarGetRelidExtended(). Checks that the current user is
20242 : : * the owner of the relation, or superuser.
20243 : : */
20244 : : void
20245 : 10471 : RangeVarCallbackOwnsRelation(const RangeVar *relation,
20246 : : Oid relId, Oid oldRelId, void *arg)
20247 : : {
20248 : : HeapTuple tuple;
20249 : :
20250 : : /* Nothing to do if the relation was not found. */
20251 [ + + ]: 10471 : if (!OidIsValid(relId))
20252 : 4 : return;
20253 : :
20254 : 10467 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
20255 [ - + ]: 10467 : if (!HeapTupleIsValid(tuple)) /* should not happen */
20256 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relId);
20257 : :
20258 [ + + ]: 10467 : if (!object_ownercheck(RelationRelationId, relId, GetUserId()))
20259 : 4 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relId)),
20260 : 4 : relation->relname);
20261 : :
20262 : : /*
20263 : : * Conflict log tables are used internally for logical replication
20264 : : * conflict logging and should not be modified directly, as it could
20265 : : * disrupt conflict logging.
20266 : : */
20267 [ + + ]: 10463 : if (IsConflictLogTableClass((Form_pg_class) GETSTRUCT(tuple)))
20268 [ + - ]: 4 : ereport(ERROR,
20269 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20270 : : errmsg("cannot change conflict log table \"%s\"",
20271 : : relation->relname),
20272 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
20273 : :
20274 [ + + + + ]: 20858 : if (!allowSystemTableMods &&
20275 : 10399 : IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
20276 [ + - ]: 1 : ereport(ERROR,
20277 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
20278 : : errmsg("permission denied: \"%s\" is a system catalog",
20279 : : relation->relname)));
20280 : :
20281 : 10458 : ReleaseSysCache(tuple);
20282 : : }
20283 : :
20284 : : /*
20285 : : * Common RangeVarGetRelid callback for rename, set schema, and alter table
20286 : : * processing.
20287 : : */
20288 : : static void
20289 : 22048 : RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid,
20290 : : void *arg)
20291 : : {
20292 : 22048 : Node *stmt = (Node *) arg;
20293 : : ObjectType reltype;
20294 : : HeapTuple tuple;
20295 : : Form_pg_class classform;
20296 : : AclResult aclresult;
20297 : : char relkind;
20298 : :
20299 : 22048 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
20300 [ + + ]: 22048 : if (!HeapTupleIsValid(tuple))
20301 : 161 : return; /* concurrently dropped */
20302 : 21887 : classform = (Form_pg_class) GETSTRUCT(tuple);
20303 : 21887 : relkind = classform->relkind;
20304 : :
20305 : : /* Must own relation. */
20306 [ + + ]: 21887 : if (!object_ownercheck(RelationRelationId, relid, GetUserId()))
20307 : 40 : aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relid)), rv->relname);
20308 : :
20309 : : /*
20310 : : * Conflict log tables are used internally for logical replication
20311 : : * conflict logging and should not be altered directly, as it could
20312 : : * disrupt conflict logging.
20313 : : */
20314 [ + + ]: 21847 : if (IsConflictLogTableClass(classform))
20315 [ + - ]: 13 : ereport(ERROR,
20316 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20317 : : errmsg("cannot alter conflict log table \"%s\"",
20318 : : rv->relname),
20319 : : errdetail("Conflict log tables are system-managed tables for logical replication conflicts.")));
20320 : :
20321 : : /* No system table modifications unless explicitly allowed. */
20322 [ + + + + ]: 21834 : if (!allowSystemTableMods && IsSystemClass(relid, classform))
20323 [ + - ]: 18 : ereport(ERROR,
20324 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
20325 : : errmsg("permission denied: \"%s\" is a system catalog",
20326 : : rv->relname)));
20327 : :
20328 : : /*
20329 : : * Extract the specified relation type from the statement parse tree.
20330 : : *
20331 : : * Also, for ALTER .. RENAME, check permissions: the user must (still)
20332 : : * have CREATE rights on the containing namespace.
20333 : : */
20334 [ + + ]: 21816 : if (IsA(stmt, RenameStmt))
20335 : : {
20336 : 298 : aclresult = object_aclcheck(NamespaceRelationId, classform->relnamespace,
20337 : : GetUserId(), ACL_CREATE);
20338 [ - + ]: 298 : if (aclresult != ACLCHECK_OK)
20339 : 0 : aclcheck_error(aclresult, OBJECT_SCHEMA,
20340 : 0 : get_namespace_name(classform->relnamespace));
20341 : 298 : reltype = ((RenameStmt *) stmt)->renameType;
20342 : : }
20343 [ + + ]: 21518 : else if (IsA(stmt, AlterObjectSchemaStmt))
20344 : 64 : reltype = ((AlterObjectSchemaStmt *) stmt)->objectType;
20345 : :
20346 [ + - ]: 21454 : else if (IsA(stmt, AlterTableStmt))
20347 : 21454 : reltype = ((AlterTableStmt *) stmt)->objtype;
20348 : : else
20349 : : {
20350 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
20351 : : reltype = OBJECT_TABLE; /* placate compiler */
20352 : : }
20353 : :
20354 : : /*
20355 : : * For compatibility with prior releases, we allow ALTER TABLE to be used
20356 : : * with most other types of relations (but not composite types). We allow
20357 : : * similar flexibility for ALTER INDEX in the case of RENAME, but not
20358 : : * otherwise. Otherwise, the user must select the correct form of the
20359 : : * command for the relation at issue.
20360 : : */
20361 [ + + - + ]: 21816 : if (reltype == OBJECT_SEQUENCE && relkind != RELKIND_SEQUENCE)
20362 [ # # ]: 0 : ereport(ERROR,
20363 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20364 : : errmsg("\"%s\" is not a sequence", rv->relname)));
20365 : :
20366 [ + + - + ]: 21816 : if (reltype == OBJECT_VIEW && relkind != RELKIND_VIEW)
20367 [ # # ]: 0 : ereport(ERROR,
20368 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20369 : : errmsg("\"%s\" is not a view", rv->relname)));
20370 : :
20371 [ + + - + ]: 21816 : if (reltype == OBJECT_MATVIEW && relkind != RELKIND_MATVIEW)
20372 [ # # ]: 0 : ereport(ERROR,
20373 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20374 : : errmsg("\"%s\" is not a materialized view", rv->relname)));
20375 : :
20376 [ + + - + ]: 21816 : if (reltype == OBJECT_FOREIGN_TABLE && relkind != RELKIND_FOREIGN_TABLE)
20377 [ # # ]: 0 : ereport(ERROR,
20378 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20379 : : errmsg("\"%s\" is not a foreign table", rv->relname)));
20380 : :
20381 [ + + - + ]: 21816 : if (reltype == OBJECT_TYPE && relkind != RELKIND_COMPOSITE_TYPE)
20382 [ # # ]: 0 : ereport(ERROR,
20383 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20384 : : errmsg("\"%s\" is not a composite type", rv->relname)));
20385 : :
20386 [ + + + + : 21816 : if (reltype == OBJECT_INDEX && relkind != RELKIND_INDEX &&
+ + ]
20387 : : relkind != RELKIND_PARTITIONED_INDEX
20388 [ + + ]: 23 : && !IsA(stmt, RenameStmt))
20389 [ + - ]: 4 : ereport(ERROR,
20390 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20391 : : errmsg("\"%s\" is not an index", rv->relname)));
20392 : :
20393 : : /*
20394 : : * Don't allow ALTER TABLE on composite types. We want people to use ALTER
20395 : : * TYPE for that.
20396 : : */
20397 [ + + - + ]: 21812 : if (reltype != OBJECT_TYPE && relkind == RELKIND_COMPOSITE_TYPE)
20398 [ # # ]: 0 : ereport(ERROR,
20399 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20400 : : errmsg("\"%s\" is a composite type", rv->relname),
20401 : : /* translator: %s is an SQL ALTER command */
20402 : : errhint("Use %s instead.",
20403 : : "ALTER TYPE")));
20404 : :
20405 : : /*
20406 : : * Don't allow ALTER TABLE .. SET SCHEMA on relations that can't be moved
20407 : : * to a different schema, such as indexes and TOAST tables.
20408 : : */
20409 [ + + ]: 21812 : if (IsA(stmt, AlterObjectSchemaStmt))
20410 : : {
20411 [ + - - + ]: 64 : if (relkind == RELKIND_INDEX || relkind == RELKIND_PARTITIONED_INDEX)
20412 [ # # ]: 0 : ereport(ERROR,
20413 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20414 : : errmsg("cannot change schema of index \"%s\"",
20415 : : rv->relname),
20416 : : errhint("Change the schema of the table instead.")));
20417 [ - + ]: 64 : else if (relkind == RELKIND_COMPOSITE_TYPE)
20418 [ # # ]: 0 : ereport(ERROR,
20419 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20420 : : errmsg("cannot change schema of composite type \"%s\"",
20421 : : rv->relname),
20422 : : /* translator: %s is an SQL ALTER command */
20423 : : errhint("Use %s instead.",
20424 : : "ALTER TYPE")));
20425 [ - + ]: 64 : else if (relkind == RELKIND_TOASTVALUE)
20426 [ # # ]: 0 : ereport(ERROR,
20427 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
20428 : : errmsg("cannot change schema of TOAST table \"%s\"",
20429 : : rv->relname),
20430 : : errhint("Change the schema of the table instead.")));
20431 : : }
20432 : :
20433 : 21812 : ReleaseSysCache(tuple);
20434 : : }
20435 : :
20436 : : /*
20437 : : * Transform any expressions present in the partition key
20438 : : *
20439 : : * Returns a transformed PartitionSpec.
20440 : : */
20441 : : static PartitionSpec *
20442 : 3384 : transformPartitionSpec(Relation rel, PartitionSpec *partspec)
20443 : : {
20444 : : PartitionSpec *newspec;
20445 : : ParseState *pstate;
20446 : : ParseNamespaceItem *nsitem;
20447 : : ListCell *l;
20448 : :
20449 : 3384 : newspec = makeNode(PartitionSpec);
20450 : :
20451 : 3384 : newspec->strategy = partspec->strategy;
20452 : 3384 : newspec->partParams = NIL;
20453 : 3384 : newspec->location = partspec->location;
20454 : :
20455 : : /* Check valid number of columns for strategy */
20456 [ + + + + ]: 4978 : if (partspec->strategy == PARTITION_STRATEGY_LIST &&
20457 : 1594 : list_length(partspec->partParams) != 1)
20458 [ + - ]: 4 : ereport(ERROR,
20459 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20460 : : errmsg("cannot use \"list\" partition strategy with more than one column")));
20461 : :
20462 : : /*
20463 : : * Create a dummy ParseState and insert the target relation as its sole
20464 : : * rangetable entry. We need a ParseState for transformExpr.
20465 : : */
20466 : 3380 : pstate = make_parsestate(NULL);
20467 : 3380 : nsitem = addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
20468 : : NULL, false, true);
20469 : 3380 : addNSItemToQuery(pstate, nsitem, true, true, true);
20470 : :
20471 : : /* take care of any partition expressions */
20472 [ + - + + : 7062 : foreach(l, partspec->partParams)
+ + ]
20473 : : {
20474 : 3698 : PartitionElem *pelem = lfirst_node(PartitionElem, l);
20475 : :
20476 [ + + ]: 3698 : if (pelem->expr)
20477 : : {
20478 : : /* Copy, to avoid scribbling on the input */
20479 : 232 : pelem = copyObject(pelem);
20480 : :
20481 : : /* Now do parse transformation of the expression */
20482 : 232 : pelem->expr = transformExpr(pstate, pelem->expr,
20483 : : EXPR_KIND_PARTITION_EXPRESSION);
20484 : :
20485 : : /* we have to fix its collations too */
20486 : 216 : assign_expr_collations(pstate, pelem->expr);
20487 : : }
20488 : :
20489 : 3682 : newspec->partParams = lappend(newspec->partParams, pelem);
20490 : : }
20491 : :
20492 : 3364 : return newspec;
20493 : : }
20494 : :
20495 : : /*
20496 : : * Compute per-partition-column information from a list of PartitionElems.
20497 : : * Expressions in the PartitionElems must be parse-analyzed already.
20498 : : */
20499 : : static void
20500 : 3364 : ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs,
20501 : : List **partexprs, Oid *partopclass, Oid *partcollation,
20502 : : PartitionStrategy strategy)
20503 : : {
20504 : : int attn;
20505 : : ListCell *lc;
20506 : : Oid am_oid;
20507 : :
20508 : 3364 : attn = 0;
20509 [ + - + + : 6958 : foreach(lc, partParams)
+ + ]
20510 : : {
20511 : 3682 : PartitionElem *pelem = lfirst_node(PartitionElem, lc);
20512 : : Oid atttype;
20513 : : Oid attcollation;
20514 : :
20515 [ + + ]: 3682 : if (pelem->name != NULL)
20516 : : {
20517 : : /* Simple attribute reference */
20518 : : HeapTuple atttuple;
20519 : : Form_pg_attribute attform;
20520 : :
20521 : 3466 : atttuple = SearchSysCacheAttName(RelationGetRelid(rel),
20522 : 3466 : pelem->name);
20523 [ + + ]: 3466 : if (!HeapTupleIsValid(atttuple))
20524 [ + - ]: 8 : ereport(ERROR,
20525 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
20526 : : errmsg("column \"%s\" named in partition key does not exist",
20527 : : pelem->name),
20528 : : parser_errposition(pstate, pelem->location)));
20529 : 3458 : attform = (Form_pg_attribute) GETSTRUCT(atttuple);
20530 : :
20531 [ + + ]: 3458 : if (attform->attnum <= 0)
20532 [ + - ]: 4 : ereport(ERROR,
20533 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20534 : : errmsg("cannot use system column \"%s\" in partition key",
20535 : : pelem->name),
20536 : : parser_errposition(pstate, pelem->location)));
20537 : :
20538 : : /*
20539 : : * Stored generated columns cannot work: They are computed after
20540 : : * BEFORE triggers, but partition routing is done before all
20541 : : * triggers. Maybe virtual generated columns could be made to
20542 : : * work, but then they would need to be handled as an expression
20543 : : * below.
20544 : : */
20545 [ + + ]: 3454 : if (attform->attgenerated)
20546 [ + - ]: 8 : ereport(ERROR,
20547 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20548 : : errmsg("cannot use generated column in partition key"),
20549 : : errdetail("Column \"%s\" is a generated column.",
20550 : : pelem->name),
20551 : : parser_errposition(pstate, pelem->location)));
20552 : :
20553 : 3446 : partattrs[attn] = attform->attnum;
20554 : 3446 : atttype = attform->atttypid;
20555 : 3446 : attcollation = attform->attcollation;
20556 : 3446 : ReleaseSysCache(atttuple);
20557 : : }
20558 : : else
20559 : : {
20560 : : /* Expression */
20561 : 216 : Node *expr = pelem->expr;
20562 : : char partattname[16];
20563 : 216 : Bitmapset *expr_attrs = NULL;
20564 : : int i;
20565 : :
20566 : : Assert(expr != NULL);
20567 : 216 : atttype = exprType(expr);
20568 : 216 : attcollation = exprCollation(expr);
20569 : :
20570 : : /*
20571 : : * The expression must be of a storable type (e.g., not RECORD).
20572 : : * The test is the same as for whether a table column is of a safe
20573 : : * type (which is why we needn't check for the non-expression
20574 : : * case).
20575 : : */
20576 : 216 : snprintf(partattname, sizeof(partattname), "%d", attn + 1);
20577 : 216 : CheckAttributeType(partattname,
20578 : : atttype, attcollation,
20579 : : NIL, CHKATYPE_IS_PARTKEY);
20580 : :
20581 : : /*
20582 : : * Strip any top-level COLLATE clause. This ensures that we treat
20583 : : * "x COLLATE y" and "(x COLLATE y)" alike.
20584 : : */
20585 [ - + ]: 208 : while (IsA(expr, CollateExpr))
20586 : 0 : expr = (Node *) ((CollateExpr *) expr)->arg;
20587 : :
20588 : : /*
20589 : : * Examine all the columns in the partition key expression. When
20590 : : * the whole-row reference is present, examine all the columns of
20591 : : * the partitioned table.
20592 : : */
20593 : 208 : pull_varattnos(expr, 1, &expr_attrs);
20594 [ + + ]: 208 : if (bms_is_member(0 - FirstLowInvalidHeapAttributeNumber, expr_attrs))
20595 : : {
20596 : 40 : expr_attrs = bms_add_range(expr_attrs,
20597 : : 1 - FirstLowInvalidHeapAttributeNumber,
20598 : 20 : RelationGetNumberOfAttributes(rel) - FirstLowInvalidHeapAttributeNumber);
20599 : 20 : expr_attrs = bms_del_member(expr_attrs, 0 - FirstLowInvalidHeapAttributeNumber);
20600 : : }
20601 : :
20602 : 208 : i = -1;
20603 [ + + ]: 457 : while ((i = bms_next_member(expr_attrs, i)) >= 0)
20604 : : {
20605 : 281 : AttrNumber attno = i + FirstLowInvalidHeapAttributeNumber;
20606 : :
20607 : : Assert(attno != 0);
20608 : :
20609 : : /*
20610 : : * Cannot allow system column references, since that would
20611 : : * make partition routing impossible: their values won't be
20612 : : * known yet when we need to do that.
20613 : : */
20614 [ - + ]: 281 : if (attno < 0)
20615 [ # # ]: 0 : ereport(ERROR,
20616 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20617 : : errmsg("partition key expressions cannot contain system column references")));
20618 : :
20619 : : /*
20620 : : * Stored generated columns cannot work: They are computed
20621 : : * after BEFORE triggers, but partition routing is done before
20622 : : * all triggers. Virtual generated columns could probably
20623 : : * work, but it would require more work elsewhere (for example
20624 : : * SET EXPRESSION would need to check whether the column is
20625 : : * used in partition keys). Seems safer to prohibit for now.
20626 : : */
20627 [ + + ]: 281 : if (TupleDescAttr(RelationGetDescr(rel), attno - 1)->attgenerated)
20628 [ + - ]: 32 : ereport(ERROR,
20629 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20630 : : errmsg("cannot use generated column in partition key"),
20631 : : errdetail("Column \"%s\" is a generated column.",
20632 : : get_attname(RelationGetRelid(rel), attno, false)),
20633 : : parser_errposition(pstate, pelem->location)));
20634 : : }
20635 : :
20636 [ + + ]: 176 : if (IsA(expr, Var) &&
20637 [ + + ]: 8 : ((Var *) expr)->varattno > 0)
20638 : : {
20639 : :
20640 : : /*
20641 : : * User wrote "(column)" or "(column COLLATE something)".
20642 : : * Treat it like simple attribute anyway.
20643 : : */
20644 : 4 : partattrs[attn] = ((Var *) expr)->varattno;
20645 : : }
20646 : : else
20647 : : {
20648 : 172 : partattrs[attn] = 0; /* marks the column as expression */
20649 : 172 : *partexprs = lappend(*partexprs, expr);
20650 : :
20651 : : /*
20652 : : * transformPartitionSpec() should have already rejected
20653 : : * subqueries, aggregates, window functions, and SRFs, based
20654 : : * on the EXPR_KIND_ for partition expressions.
20655 : : */
20656 : :
20657 : : /*
20658 : : * Preprocess the expression before checking for mutability.
20659 : : * This is essential for the reasons described in
20660 : : * contain_mutable_functions_after_planning. However, we call
20661 : : * expression_planner for ourselves rather than using that
20662 : : * function, because if constant-folding reduces the
20663 : : * expression to a constant, we'd like to know that so we can
20664 : : * complain below.
20665 : : *
20666 : : * Like contain_mutable_functions_after_planning, assume that
20667 : : * expression_planner won't scribble on its input, so this
20668 : : * won't affect the partexprs entry we saved above.
20669 : : */
20670 : 172 : expr = (Node *) expression_planner((Expr *) expr);
20671 : :
20672 : : /*
20673 : : * Partition expressions cannot contain mutable functions,
20674 : : * because a given row must always map to the same partition
20675 : : * as long as there is no change in the partition boundary
20676 : : * structure.
20677 : : */
20678 [ + + ]: 172 : if (contain_mutable_functions(expr))
20679 [ + - ]: 4 : ereport(ERROR,
20680 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20681 : : errmsg("functions in partition key expression must be marked IMMUTABLE")));
20682 : :
20683 : : /*
20684 : : * While it is not exactly *wrong* for a partition expression
20685 : : * to be a constant, it seems better to reject such keys.
20686 : : */
20687 [ + + ]: 168 : if (IsA(expr, Const))
20688 [ + - ]: 8 : ereport(ERROR,
20689 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
20690 : : errmsg("cannot use constant expression as partition key")));
20691 : : }
20692 : : }
20693 : :
20694 : : /*
20695 : : * Apply collation override if any
20696 : : */
20697 [ + + ]: 3610 : if (pelem->collation)
20698 : 36 : attcollation = get_collation_oid(pelem->collation, false);
20699 : :
20700 : : /*
20701 : : * Check we have a collation iff it's a collatable type. The only
20702 : : * expected failures here are (1) COLLATE applied to a noncollatable
20703 : : * type, or (2) partition expression had an unresolved collation. But
20704 : : * we might as well code this to be a complete consistency check.
20705 : : */
20706 [ + + ]: 3610 : if (type_is_collatable(atttype))
20707 : : {
20708 [ - + ]: 395 : if (!OidIsValid(attcollation))
20709 [ # # ]: 0 : ereport(ERROR,
20710 : : (errcode(ERRCODE_INDETERMINATE_COLLATION),
20711 : : errmsg("could not determine which collation to use for partition expression"),
20712 : : errhint("Use the COLLATE clause to set the collation explicitly.")));
20713 : : }
20714 : : else
20715 : : {
20716 [ - + ]: 3215 : if (OidIsValid(attcollation))
20717 [ # # ]: 0 : ereport(ERROR,
20718 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
20719 : : errmsg("collations are not supported by type %s",
20720 : : format_type_be(atttype))));
20721 : : }
20722 : :
20723 : 3610 : partcollation[attn] = attcollation;
20724 : :
20725 : : /*
20726 : : * Identify the appropriate operator class. For list and range
20727 : : * partitioning, we use a btree operator class; hash partitioning uses
20728 : : * a hash operator class.
20729 : : */
20730 [ + + ]: 3610 : if (strategy == PARTITION_STRATEGY_HASH)
20731 : 207 : am_oid = HASH_AM_OID;
20732 : : else
20733 : 3403 : am_oid = BTREE_AM_OID;
20734 : :
20735 [ + + ]: 3610 : if (!pelem->opclass)
20736 : : {
20737 : 3514 : partopclass[attn] = GetDefaultOpClass(atttype, am_oid);
20738 : :
20739 [ + + ]: 3514 : if (!OidIsValid(partopclass[attn]))
20740 : : {
20741 [ - + ]: 8 : if (strategy == PARTITION_STRATEGY_HASH)
20742 [ # # ]: 0 : ereport(ERROR,
20743 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
20744 : : errmsg("data type %s has no default operator class for access method \"%s\"",
20745 : : format_type_be(atttype), "hash"),
20746 : : errhint("You must specify a hash operator class or define a default hash operator class for the data type.")));
20747 : : else
20748 [ + - ]: 8 : ereport(ERROR,
20749 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
20750 : : errmsg("data type %s has no default operator class for access method \"%s\"",
20751 : : format_type_be(atttype), "btree"),
20752 : : errhint("You must specify a btree operator class or define a default btree operator class for the data type.")));
20753 : : }
20754 : : }
20755 : : else
20756 [ + + ]: 96 : partopclass[attn] = ResolveOpClass(pelem->opclass,
20757 : : atttype,
20758 : : am_oid == HASH_AM_OID ? "hash" : "btree",
20759 : : am_oid);
20760 : :
20761 : 3594 : attn++;
20762 : : }
20763 : 3276 : }
20764 : :
20765 : : /*
20766 : : * PartConstraintImpliedByRelConstraint
20767 : : * Do scanrel's existing constraints imply the partition constraint?
20768 : : *
20769 : : * "Existing constraints" include its check constraints and column-level
20770 : : * not-null constraints. partConstraint describes the partition constraint,
20771 : : * in implicit-AND form.
20772 : : */
20773 : : bool
20774 : 1979 : PartConstraintImpliedByRelConstraint(Relation scanrel,
20775 : : List *partConstraint)
20776 : : {
20777 : 1979 : List *existConstraint = NIL;
20778 : 1979 : TupleConstr *constr = RelationGetDescr(scanrel)->constr;
20779 : : int i;
20780 : :
20781 [ + + + + ]: 1979 : if (constr && constr->has_not_null)
20782 : : {
20783 : 500 : int natts = scanrel->rd_att->natts;
20784 : :
20785 [ + + ]: 1662 : for (i = 1; i <= natts; i++)
20786 : : {
20787 : 1162 : CompactAttribute *att = TupleDescCompactAttr(scanrel->rd_att, i - 1);
20788 : :
20789 : : /* invalid not-null constraint must be ignored here */
20790 [ + + + - ]: 1162 : if (att->attnullability == ATTNULLABLE_VALID && !att->attisdropped)
20791 : : {
20792 : 695 : Form_pg_attribute wholeatt = TupleDescAttr(scanrel->rd_att, i - 1);
20793 : 695 : NullTest *ntest = makeNode(NullTest);
20794 : :
20795 : 695 : ntest->arg = (Expr *) makeVar(1,
20796 : : i,
20797 : : wholeatt->atttypid,
20798 : : wholeatt->atttypmod,
20799 : : wholeatt->attcollation,
20800 : : 0);
20801 : 695 : ntest->nulltesttype = IS_NOT_NULL;
20802 : :
20803 : : /*
20804 : : * argisrow=false is correct even for a composite column,
20805 : : * because attnotnull does not represent a SQL-spec IS NOT
20806 : : * NULL test in such a case, just IS DISTINCT FROM NULL.
20807 : : */
20808 : 695 : ntest->argisrow = false;
20809 : 695 : ntest->location = -1;
20810 : 695 : existConstraint = lappend(existConstraint, ntest);
20811 : : }
20812 : : }
20813 : : }
20814 : :
20815 : 1979 : return ConstraintImpliedByRelConstraint(scanrel, partConstraint, existConstraint);
20816 : : }
20817 : :
20818 : : /*
20819 : : * ConstraintImpliedByRelConstraint
20820 : : * Do scanrel's existing constraints imply the given constraint?
20821 : : *
20822 : : * testConstraint is the constraint to validate. provenConstraint is a
20823 : : * caller-provided list of conditions which this function may assume
20824 : : * to be true. Both provenConstraint and testConstraint must be in
20825 : : * implicit-AND form, must only contain immutable clauses, and must
20826 : : * contain only Vars with varno = 1.
20827 : : */
20828 : : bool
20829 : 2794 : ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
20830 : : {
20831 : 2794 : List *existConstraint = list_copy(provenConstraint);
20832 : 2794 : TupleConstr *constr = RelationGetDescr(scanrel)->constr;
20833 : : int num_check,
20834 : : i;
20835 : :
20836 [ + + ]: 2794 : num_check = (constr != NULL) ? constr->num_check : 0;
20837 [ + + ]: 3130 : for (i = 0; i < num_check; i++)
20838 : : {
20839 : : Node *cexpr;
20840 : :
20841 : : /*
20842 : : * If this constraint hasn't been fully validated yet, we must ignore
20843 : : * it here.
20844 : : */
20845 [ + + ]: 336 : if (!constr->check[i].ccvalid)
20846 : 12 : continue;
20847 : :
20848 : : /*
20849 : : * NOT ENFORCED constraints are always marked as invalid, which should
20850 : : * have been ignored.
20851 : : */
20852 : : Assert(constr->check[i].ccenforced);
20853 : :
20854 : 324 : cexpr = stringToNode(constr->check[i].ccbin);
20855 : :
20856 : : /*
20857 : : * Run each expression through const-simplification and
20858 : : * canonicalization. It is necessary, because we will be comparing it
20859 : : * to similarly-processed partition constraint expressions, and may
20860 : : * fail to detect valid matches without this.
20861 : : */
20862 : 324 : cexpr = eval_const_expressions(NULL, cexpr);
20863 : 324 : cexpr = (Node *) canonicalize_qual((Expr *) cexpr, true);
20864 : :
20865 : 324 : existConstraint = list_concat(existConstraint,
20866 : 324 : make_ands_implicit((Expr *) cexpr));
20867 : : }
20868 : :
20869 : : /*
20870 : : * Try to make the proof. Since we are comparing CHECK constraints, we
20871 : : * need to use weak implication, i.e., we assume existConstraint is
20872 : : * not-false and try to prove the same for testConstraint.
20873 : : *
20874 : : * Note that predicate_implied_by assumes its first argument is known
20875 : : * immutable. That should always be true for both NOT NULL and partition
20876 : : * constraints, so we don't test it here.
20877 : : */
20878 : 2794 : return predicate_implied_by(testConstraint, existConstraint, true);
20879 : : }
20880 : :
20881 : : /*
20882 : : * QueuePartitionConstraintValidation
20883 : : *
20884 : : * Add an entry to wqueue to have the given partition constraint validated by
20885 : : * Phase 3, for the given relation, and all its children.
20886 : : *
20887 : : * We first verify whether the given constraint is implied by pre-existing
20888 : : * relation constraints; if it is, there's no need to scan the table to
20889 : : * validate, so don't queue in that case.
20890 : : */
20891 : : static void
20892 : 1638 : QueuePartitionConstraintValidation(List **wqueue, Relation scanrel,
20893 : : List *partConstraint,
20894 : : bool validate_default)
20895 : : {
20896 : : /*
20897 : : * Based on the table's existing constraints, determine whether or not we
20898 : : * may skip scanning the table.
20899 : : */
20900 [ + + ]: 1638 : if (PartConstraintImpliedByRelConstraint(scanrel, partConstraint))
20901 : : {
20902 [ + + ]: 55 : if (!validate_default)
20903 [ + + ]: 41 : ereport(DEBUG1,
20904 : : (errmsg_internal("partition constraint for table \"%s\" is implied by existing constraints",
20905 : : RelationGetRelationName(scanrel))));
20906 : : else
20907 [ + + ]: 14 : ereport(DEBUG1,
20908 : : (errmsg_internal("updated partition constraint for default partition \"%s\" is implied by existing constraints",
20909 : : RelationGetRelationName(scanrel))));
20910 : 55 : return;
20911 : : }
20912 : :
20913 : : /*
20914 : : * Constraints proved insufficient. For plain relations, queue a
20915 : : * validation item now; for partitioned tables, recurse to process each
20916 : : * partition.
20917 : : */
20918 [ + + ]: 1583 : if (scanrel->rd_rel->relkind == RELKIND_RELATION)
20919 : : {
20920 : : AlteredTableInfo *tab;
20921 : :
20922 : : /* Grab a work queue entry. */
20923 : 1320 : tab = ATGetQueueEntry(wqueue, scanrel);
20924 : : Assert(tab->partition_constraint == NULL);
20925 : 1320 : tab->partition_constraint = (Expr *) linitial(partConstraint);
20926 : 1320 : tab->validate_default = validate_default;
20927 : : }
20928 [ + + ]: 263 : else if (scanrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
20929 : : {
20930 : 232 : PartitionDesc partdesc = RelationGetPartitionDesc(scanrel, true);
20931 : : int i;
20932 : :
20933 [ + + ]: 488 : for (i = 0; i < partdesc->nparts; i++)
20934 : : {
20935 : : Relation part_rel;
20936 : : List *thisPartConstraint;
20937 : :
20938 : : /*
20939 : : * This is the minimum lock we need to prevent deadlocks.
20940 : : */
20941 : 256 : part_rel = table_open(partdesc->oids[i], AccessExclusiveLock);
20942 : :
20943 : : /*
20944 : : * Adjust the constraint for scanrel so that it matches this
20945 : : * partition's attribute numbers.
20946 : : */
20947 : : thisPartConstraint =
20948 : 256 : map_partition_varattnos(partConstraint, 1,
20949 : : part_rel, scanrel);
20950 : :
20951 : 256 : QueuePartitionConstraintValidation(wqueue, part_rel,
20952 : : thisPartConstraint,
20953 : : validate_default);
20954 : 256 : table_close(part_rel, NoLock); /* keep lock till commit */
20955 : : }
20956 : : }
20957 : : }
20958 : :
20959 : : /*
20960 : : * ALTER TABLE <name> ATTACH PARTITION <partition-name> FOR VALUES
20961 : : *
20962 : : * Return the address of the newly attached partition.
20963 : : */
20964 : : static ObjectAddress
20965 : 1533 : ATExecAttachPartition(List **wqueue, Relation rel, PartitionCmd *cmd,
20966 : : AlterTableUtilityContext *context)
20967 : : {
20968 : : Relation attachrel,
20969 : : catalog;
20970 : : List *attachrel_children;
20971 : : List *partConstraint;
20972 : : SysScanDesc scan;
20973 : : ScanKeyData skey;
20974 : : AttrNumber attno;
20975 : : int natts;
20976 : : TupleDesc tupleDesc;
20977 : : ObjectAddress address;
20978 : : const char *trigger_name;
20979 : : Oid defaultPartOid;
20980 : : List *partBoundConstraint;
20981 : 1533 : List *exceptpuboids = NIL;
20982 : 1533 : ParseState *pstate = make_parsestate(NULL);
20983 : :
20984 : 1533 : pstate->p_sourcetext = context->queryString;
20985 : :
20986 : : /*
20987 : : * We must lock the default partition if one exists, because attaching a
20988 : : * new partition will change its partition constraint.
20989 : : */
20990 : : defaultPartOid =
20991 : 1533 : get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
20992 [ + + ]: 1533 : if (OidIsValid(defaultPartOid))
20993 : 117 : LockRelationOid(defaultPartOid, AccessExclusiveLock);
20994 : :
20995 : 1533 : attachrel = table_openrv(cmd->name, AccessExclusiveLock);
20996 : :
20997 : : /*
20998 : : * XXX I think it'd be a good idea to grab locks on all tables referenced
20999 : : * by FKs at this point also.
21000 : : */
21001 : :
21002 : : /*
21003 : : * Must be owner of both parent and source table -- parent was checked by
21004 : : * ATSimplePermissions call in ATPrepCmd
21005 : : */
21006 : 1529 : ATSimplePermissions(AT_AttachPartition, attachrel,
21007 : : ATT_TABLE | ATT_PARTITIONED_TABLE | ATT_FOREIGN_TABLE);
21008 : :
21009 : : /* A partition can only have one parent */
21010 [ + + ]: 1525 : if (attachrel->rd_rel->relispartition)
21011 [ + - ]: 4 : ereport(ERROR,
21012 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21013 : : errmsg("\"%s\" is already a partition",
21014 : : RelationGetRelationName(attachrel))));
21015 : :
21016 [ + + ]: 1521 : if (OidIsValid(attachrel->rd_rel->reloftype))
21017 [ + - ]: 4 : ereport(ERROR,
21018 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21019 : : errmsg("cannot attach a typed table as partition")));
21020 : :
21021 : : /*
21022 : : * Disallow attaching a partition if the table is referenced in a
21023 : : * publication EXCEPT clause. Changing the partition hierarchy could alter
21024 : : * the effective publication membership.
21025 : : */
21026 : 1517 : exceptpuboids = GetRelationExcludedPublications(RelationGetRelid(attachrel));
21027 [ + + ]: 1517 : if (exceptpuboids != NIL)
21028 : : {
21029 : 4 : bool first = true;
21030 : : StringInfoData pubnames;
21031 : :
21032 : 4 : initStringInfo(&pubnames);
21033 : :
21034 [ + - + + : 12 : foreach_oid(pubid, exceptpuboids)
+ + ]
21035 : : {
21036 : 4 : char *pubname = get_publication_name(pubid, false);
21037 : :
21038 [ + - ]: 4 : if (first)
21039 : 4 : appendStringInfo(&pubnames, _("\"%s\""), pubname);
21040 : : else
21041 : 0 : appendStringInfo(&pubnames, _(", \"%s\""), pubname);
21042 : 4 : first = false;
21043 : : }
21044 : :
21045 [ + - ]: 4 : ereport(ERROR,
21046 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21047 : : errmsg_plural("cannot attach table \"%s\" as partition because it is referenced in publication %s EXCEPT clause",
21048 : : "cannot attach table \"%s\" as partition because it is referenced in publications %s EXCEPT clause",
21049 : : list_length(exceptpuboids),
21050 : : RelationGetRelationName(attachrel),
21051 : : pubnames.data),
21052 : : errdetail("The publication EXCEPT clause cannot contain tables that are partitions."),
21053 : : errhint("Change the publication's EXCEPT clause using ALTER PUBLICATION ... SET ALL TABLES."));
21054 : : }
21055 : :
21056 : 1513 : list_free(exceptpuboids);
21057 : :
21058 : : /*
21059 : : * Table being attached should not already be part of inheritance; either
21060 : : * as a child table...
21061 : : */
21062 : 1513 : catalog = table_open(InheritsRelationId, AccessShareLock);
21063 : 1513 : ScanKeyInit(&skey,
21064 : : Anum_pg_inherits_inhrelid,
21065 : : BTEqualStrategyNumber, F_OIDEQ,
21066 : : ObjectIdGetDatum(RelationGetRelid(attachrel)));
21067 : 1513 : scan = systable_beginscan(catalog, InheritsRelidSeqnoIndexId, true,
21068 : : NULL, 1, &skey);
21069 [ + + ]: 1513 : if (HeapTupleIsValid(systable_getnext(scan)))
21070 [ + - ]: 4 : ereport(ERROR,
21071 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21072 : : errmsg("cannot attach inheritance child as partition")));
21073 : 1509 : systable_endscan(scan);
21074 : :
21075 : : /* ...or as a parent table (except the case when it is partitioned) */
21076 : 1509 : ScanKeyInit(&skey,
21077 : : Anum_pg_inherits_inhparent,
21078 : : BTEqualStrategyNumber, F_OIDEQ,
21079 : : ObjectIdGetDatum(RelationGetRelid(attachrel)));
21080 : 1509 : scan = systable_beginscan(catalog, InheritsParentIndexId, true, NULL,
21081 : : 1, &skey);
21082 [ + + ]: 1509 : if (HeapTupleIsValid(systable_getnext(scan)) &&
21083 [ + + ]: 172 : attachrel->rd_rel->relkind == RELKIND_RELATION)
21084 [ + - ]: 4 : ereport(ERROR,
21085 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21086 : : errmsg("cannot attach inheritance parent as partition")));
21087 : 1505 : systable_endscan(scan);
21088 : 1505 : table_close(catalog, AccessShareLock);
21089 : :
21090 : : /*
21091 : : * Prevent circularity by seeing if rel is a partition of attachrel. (In
21092 : : * particular, this disallows making a rel a partition of itself.)
21093 : : *
21094 : : * We do that by checking if rel is a member of the list of attachrel's
21095 : : * partitions provided the latter is partitioned at all. We want to avoid
21096 : : * having to construct this list again, so we request the strongest lock
21097 : : * on all partitions. We need the strongest lock, because we may decide
21098 : : * to scan them if we find out that the table being attached (or its leaf
21099 : : * partitions) may contain rows that violate the partition constraint. If
21100 : : * the table has a constraint that would prevent such rows, which by
21101 : : * definition is present in all the partitions, we need not scan the
21102 : : * table, nor its partitions. But we cannot risk a deadlock by taking a
21103 : : * weaker lock now and the stronger one only when needed.
21104 : : */
21105 : 1505 : attachrel_children = find_all_inheritors(RelationGetRelid(attachrel),
21106 : : AccessExclusiveLock, NULL);
21107 [ + + ]: 1505 : if (list_member_oid(attachrel_children, RelationGetRelid(rel)))
21108 [ + - ]: 8 : ereport(ERROR,
21109 : : (errcode(ERRCODE_DUPLICATE_TABLE),
21110 : : errmsg("circular inheritance not allowed"),
21111 : : errdetail("\"%s\" is already a child of \"%s\".",
21112 : : RelationGetRelationName(rel),
21113 : : RelationGetRelationName(attachrel))));
21114 : :
21115 : : /* If the parent is permanent, so must be all of its partitions. */
21116 [ + + ]: 1497 : if (rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP &&
21117 [ + + ]: 1469 : attachrel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
21118 [ + - ]: 4 : ereport(ERROR,
21119 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21120 : : errmsg("cannot attach a temporary relation as partition of permanent relation \"%s\"",
21121 : : RelationGetRelationName(rel))));
21122 : :
21123 : : /* Temp parent cannot have a partition that is itself not a temp */
21124 [ + + ]: 1493 : if (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
21125 [ + + ]: 28 : attachrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
21126 [ + - ]: 12 : ereport(ERROR,
21127 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21128 : : errmsg("cannot attach a permanent relation as partition of temporary relation \"%s\"",
21129 : : RelationGetRelationName(rel))));
21130 : :
21131 : : /* If the parent is temp, it must belong to this session */
21132 [ + + - + ]: 1481 : if (RELATION_IS_OTHER_TEMP(rel))
21133 [ # # ]: 0 : ereport(ERROR,
21134 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21135 : : errmsg("cannot attach as partition of temporary relation of another session")));
21136 : :
21137 : : /* Ditto for the partition */
21138 [ + + - + ]: 1481 : if (RELATION_IS_OTHER_TEMP(attachrel))
21139 [ # # ]: 0 : ereport(ERROR,
21140 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21141 : : errmsg("cannot attach temporary relation of another session as partition")));
21142 : :
21143 : : /*
21144 : : * Check if attachrel has any identity columns or any columns that aren't
21145 : : * in the parent.
21146 : : */
21147 : 1481 : tupleDesc = RelationGetDescr(attachrel);
21148 : 1481 : natts = tupleDesc->natts;
21149 [ + + ]: 5051 : for (attno = 1; attno <= natts; attno++)
21150 : : {
21151 : 3598 : Form_pg_attribute attribute = TupleDescAttr(tupleDesc, attno - 1);
21152 : 3598 : char *attributeName = NameStr(attribute->attname);
21153 : :
21154 : : /* Ignore dropped */
21155 [ + + ]: 3598 : if (attribute->attisdropped)
21156 : 368 : continue;
21157 : :
21158 [ + + ]: 3230 : if (attribute->attidentity)
21159 [ + - ]: 16 : ereport(ERROR,
21160 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21161 : : errmsg("table \"%s\" being attached contains an identity column \"%s\"",
21162 : : RelationGetRelationName(attachrel), attributeName),
21163 : : errdetail("The new partition may not contain an identity column."));
21164 : :
21165 : : /* Try to find the column in parent (matching on column name) */
21166 [ + + ]: 3214 : if (!SearchSysCacheExists2(ATTNAME,
21167 : : ObjectIdGetDatum(RelationGetRelid(rel)),
21168 : : CStringGetDatum(attributeName)))
21169 [ + - ]: 12 : ereport(ERROR,
21170 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
21171 : : errmsg("table \"%s\" contains column \"%s\" not found in parent \"%s\"",
21172 : : RelationGetRelationName(attachrel), attributeName,
21173 : : RelationGetRelationName(rel)),
21174 : : errdetail("The new partition may contain only the columns present in parent.")));
21175 : : }
21176 : :
21177 : : /*
21178 : : * If child_rel has row-level triggers with transition tables, we
21179 : : * currently don't allow it to become a partition. See also prohibitions
21180 : : * in ATExecAddInherit() and CreateTrigger().
21181 : : */
21182 : 1453 : trigger_name = FindTriggerIncompatibleWithInheritance(attachrel->trigdesc);
21183 [ + + ]: 1453 : if (trigger_name != NULL)
21184 [ + - ]: 4 : ereport(ERROR,
21185 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
21186 : : errmsg("trigger \"%s\" prevents table \"%s\" from becoming a partition",
21187 : : trigger_name, RelationGetRelationName(attachrel)),
21188 : : errdetail("ROW triggers with transition tables are not supported on partitions.")));
21189 : :
21190 : : /*
21191 : : * Check that the new partition's bound is valid and does not overlap any
21192 : : * of existing partitions of the parent - note that it does not return on
21193 : : * error.
21194 : : */
21195 : 1449 : check_new_partition_bound(RelationGetRelationName(attachrel), rel,
21196 : : cmd->bound, pstate);
21197 : :
21198 : : /* OK to create inheritance. Rest of the checks performed there */
21199 : 1425 : CreateInheritance(attachrel, rel, true);
21200 : :
21201 : : /* Update the pg_class entry. */
21202 : 1353 : StorePartitionBound(attachrel, rel, cmd->bound);
21203 : :
21204 : : /* Ensure there exists a correct set of indexes in the partition. */
21205 : 1353 : AttachPartitionEnsureIndexes(wqueue, rel, attachrel);
21206 : :
21207 : : /* and triggers */
21208 : 1333 : CloneRowTriggersToPartition(rel, attachrel);
21209 : :
21210 : : /*
21211 : : * Clone foreign key constraints. Callee is responsible for setting up
21212 : : * for phase 3 constraint verification.
21213 : : */
21214 : 1329 : CloneForeignKeyConstraints(wqueue, rel, attachrel);
21215 : :
21216 : : /*
21217 : : * Generate partition constraint from the partition bound specification.
21218 : : * If the parent itself is a partition, make sure to include its
21219 : : * constraint as well.
21220 : : */
21221 : 1317 : partBoundConstraint = get_qual_from_partbound(rel, cmd->bound);
21222 : :
21223 : : /*
21224 : : * Use list_concat_copy() to avoid modifying partBoundConstraint in place,
21225 : : * since it's needed later to construct the constraint expression for
21226 : : * validating against the default partition, if any.
21227 : : */
21228 : 1317 : partConstraint = list_concat_copy(partBoundConstraint,
21229 : 1317 : RelationGetPartitionQual(rel));
21230 : :
21231 : : /* Skip validation if there are no constraints to validate. */
21232 [ + + ]: 1317 : if (partConstraint)
21233 : : {
21234 : : /*
21235 : : * Run the partition quals through const-simplification similar to
21236 : : * check constraints. We skip canonicalize_qual, though, because
21237 : : * partition quals should be in canonical form already.
21238 : : */
21239 : : partConstraint =
21240 : 1289 : (List *) eval_const_expressions(NULL,
21241 : : (Node *) partConstraint);
21242 : :
21243 : : /* XXX this sure looks wrong */
21244 : 1289 : partConstraint = list_make1(make_ands_explicit(partConstraint));
21245 : :
21246 : : /*
21247 : : * Adjust the generated constraint to match this partition's attribute
21248 : : * numbers.
21249 : : */
21250 : 1289 : partConstraint = map_partition_varattnos(partConstraint, 1, attachrel,
21251 : : rel);
21252 : :
21253 : : /* Validate partition constraints against the table being attached. */
21254 : 1289 : QueuePartitionConstraintValidation(wqueue, attachrel, partConstraint,
21255 : : false);
21256 : : }
21257 : :
21258 : : /*
21259 : : * If we're attaching a partition other than the default partition and a
21260 : : * default one exists, then that partition's partition constraint changes,
21261 : : * so add an entry to the work queue to validate it, too. (We must not do
21262 : : * this when the partition being attached is the default one; we already
21263 : : * did it above!)
21264 : : */
21265 [ + + ]: 1317 : if (OidIsValid(defaultPartOid))
21266 : : {
21267 : : Relation defaultrel;
21268 : : List *defPartConstraint;
21269 : :
21270 : : Assert(!cmd->bound->is_default);
21271 : :
21272 : : /* we already hold a lock on the default partition */
21273 : 93 : defaultrel = table_open(defaultPartOid, NoLock);
21274 : : defPartConstraint =
21275 : 93 : get_proposed_default_constraint(partBoundConstraint);
21276 : :
21277 : : /*
21278 : : * Map the Vars in the constraint expression from rel's attnos to
21279 : : * defaultrel's.
21280 : : */
21281 : : defPartConstraint =
21282 : 93 : map_partition_varattnos(defPartConstraint,
21283 : : 1, defaultrel, rel);
21284 : 93 : QueuePartitionConstraintValidation(wqueue, defaultrel,
21285 : : defPartConstraint, true);
21286 : :
21287 : : /* keep our lock until commit. */
21288 : 93 : table_close(defaultrel, NoLock);
21289 : : }
21290 : :
21291 : 1317 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(attachrel));
21292 : :
21293 : : /*
21294 : : * If the partition we just attached is partitioned itself, invalidate
21295 : : * relcache for all descendent partitions too to ensure that their
21296 : : * rd_partcheck expression trees are rebuilt; partitions already locked at
21297 : : * the beginning of this function.
21298 : : */
21299 [ + + ]: 1317 : if (attachrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
21300 : : {
21301 : : ListCell *l;
21302 : :
21303 [ + - + + : 663 : foreach(l, attachrel_children)
+ + ]
21304 : : {
21305 : 446 : CacheInvalidateRelcacheByRelid(lfirst_oid(l));
21306 : : }
21307 : : }
21308 : :
21309 : : /* keep our lock until commit */
21310 : 1317 : table_close(attachrel, NoLock);
21311 : :
21312 : 1317 : return address;
21313 : : }
21314 : :
21315 : : /*
21316 : : * AttachPartitionEnsureIndexes
21317 : : * subroutine for ATExecAttachPartition to create/match indexes
21318 : : *
21319 : : * Enforce the indexing rule for partitioned tables during ALTER TABLE / ATTACH
21320 : : * PARTITION: every partition must have an index attached to each index on the
21321 : : * partitioned table.
21322 : : */
21323 : : static void
21324 : 1353 : AttachPartitionEnsureIndexes(List **wqueue, Relation rel, Relation attachrel)
21325 : : {
21326 : : List *idxes;
21327 : : List *attachRelIdxs;
21328 : : Relation *attachrelIdxRels;
21329 : : IndexInfo **attachInfos;
21330 : : ListCell *cell;
21331 : : MemoryContext cxt;
21332 : : MemoryContext oldcxt;
21333 : :
21334 : 1353 : cxt = AllocSetContextCreate(CurrentMemoryContext,
21335 : : "AttachPartitionEnsureIndexes",
21336 : : ALLOCSET_DEFAULT_SIZES);
21337 : 1353 : oldcxt = MemoryContextSwitchTo(cxt);
21338 : :
21339 : 1353 : idxes = RelationGetIndexList(rel);
21340 : 1353 : attachRelIdxs = RelationGetIndexList(attachrel);
21341 : 1353 : attachrelIdxRels = palloc_array(Relation, list_length(attachRelIdxs));
21342 : 1353 : attachInfos = palloc_array(IndexInfo *, list_length(attachRelIdxs));
21343 : :
21344 : : /* Build arrays of all existing indexes and their IndexInfos */
21345 [ + + + + : 2959 : foreach_oid(cldIdxId, attachRelIdxs)
+ + ]
21346 : : {
21347 : 253 : int i = foreach_current_index(cldIdxId);
21348 : :
21349 : 253 : attachrelIdxRels[i] = index_open(cldIdxId, AccessShareLock);
21350 : 253 : attachInfos[i] = BuildIndexInfo(attachrelIdxRels[i]);
21351 : : }
21352 : :
21353 : : /*
21354 : : * If we're attaching a foreign table, we must fail if any of the indexes
21355 : : * is a constraint index; otherwise, there's nothing to do here. Do this
21356 : : * before starting work, to avoid wasting the effort of building a few
21357 : : * non-unique indexes before coming across a unique one.
21358 : : */
21359 [ + + ]: 1353 : if (attachrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
21360 : : {
21361 [ + + + + : 55 : foreach(cell, idxes)
+ + ]
21362 : : {
21363 : 24 : Oid idx = lfirst_oid(cell);
21364 : 24 : Relation idxRel = index_open(idx, AccessShareLock);
21365 : :
21366 [ + + ]: 24 : if (idxRel->rd_index->indisunique ||
21367 [ - + ]: 16 : idxRel->rd_index->indisprimary)
21368 [ + - ]: 8 : ereport(ERROR,
21369 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
21370 : : errmsg("cannot attach foreign table \"%s\" as partition of partitioned table \"%s\"",
21371 : : RelationGetRelationName(attachrel),
21372 : : RelationGetRelationName(rel)),
21373 : : errdetail("Partitioned table \"%s\" contains unique indexes.",
21374 : : RelationGetRelationName(rel))));
21375 : 16 : index_close(idxRel, AccessShareLock);
21376 : : }
21377 : :
21378 : 31 : goto out;
21379 : : }
21380 : :
21381 : : /*
21382 : : * For each index on the partitioned table, find a matching one in the
21383 : : * partition-to-be; if one is not found, create one.
21384 : : */
21385 [ + + + + : 1595 : foreach(cell, idxes)
+ + ]
21386 : : {
21387 : 293 : Oid idx = lfirst_oid(cell);
21388 : 293 : Relation idxRel = index_open(idx, AccessShareLock);
21389 : : IndexInfo *info;
21390 : : AttrMap *attmap;
21391 : 293 : bool found = false;
21392 : : Oid constraintOid;
21393 : :
21394 : : /*
21395 : : * Ignore indexes in the partitioned table other than partitioned
21396 : : * indexes.
21397 : : */
21398 [ - + ]: 293 : if (idxRel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
21399 : : {
21400 : 0 : index_close(idxRel, AccessShareLock);
21401 : 0 : continue;
21402 : : }
21403 : :
21404 : : /* construct an indexinfo to compare existing indexes against */
21405 : 293 : info = BuildIndexInfo(idxRel);
21406 : 293 : attmap = build_attrmap_by_name(RelationGetDescr(attachrel),
21407 : : RelationGetDescr(rel),
21408 : : false);
21409 : 293 : constraintOid = get_relation_idx_constraint_oid(RelationGetRelid(rel), idx);
21410 : :
21411 : : /*
21412 : : * Scan the list of existing indexes in the partition-to-be, and mark
21413 : : * the first matching, valid, unattached one we find, if any, as
21414 : : * partition of the parent index. If we find one, we're done.
21415 : : */
21416 [ + + ]: 333 : for (int i = 0; i < list_length(attachRelIdxs); i++)
21417 : : {
21418 : 181 : Oid cldIdxId = RelationGetRelid(attachrelIdxRels[i]);
21419 : 181 : Oid cldConstrOid = InvalidOid;
21420 : :
21421 : : /* does this index have a parent? if so, can't use it */
21422 [ + + ]: 181 : if (attachrelIdxRels[i]->rd_rel->relispartition)
21423 : 8 : continue;
21424 : :
21425 : : /* If this index is invalid, can't use it */
21426 [ + + ]: 173 : if (!attachrelIdxRels[i]->rd_index->indisvalid)
21427 : 4 : continue;
21428 : :
21429 [ + + ]: 169 : if (CompareIndexInfo(attachInfos[i], info,
21430 : 169 : attachrelIdxRels[i]->rd_indcollation,
21431 : 169 : idxRel->rd_indcollation,
21432 : 169 : attachrelIdxRels[i]->rd_opfamily,
21433 : 169 : idxRel->rd_opfamily,
21434 : : attmap))
21435 : : {
21436 : : /*
21437 : : * If this index is being created in the parent because of a
21438 : : * constraint, then the child needs to have a constraint also,
21439 : : * so look for one. If there is no such constraint, this
21440 : : * index is no good, so keep looking.
21441 : : */
21442 [ + + ]: 145 : if (OidIsValid(constraintOid))
21443 : : {
21444 : : cldConstrOid =
21445 : 80 : get_relation_idx_constraint_oid(RelationGetRelid(attachrel),
21446 : : cldIdxId);
21447 : : /* no dice */
21448 [ + + ]: 80 : if (!OidIsValid(cldConstrOid))
21449 : 4 : continue;
21450 : :
21451 : : /* Ensure they're both the same type of constraint */
21452 [ - + ]: 152 : if (get_constraint_type(constraintOid) !=
21453 : 76 : get_constraint_type(cldConstrOid))
21454 : 0 : continue;
21455 : : }
21456 : :
21457 : : /* bingo. */
21458 : 141 : IndexSetParentIndex(attachrelIdxRels[i], idx);
21459 [ + + ]: 141 : if (OidIsValid(constraintOid))
21460 : 76 : ConstraintSetParentConstraint(cldConstrOid, constraintOid,
21461 : : RelationGetRelid(attachrel));
21462 : 141 : found = true;
21463 : :
21464 : 141 : CommandCounterIncrement();
21465 : 141 : break;
21466 : : }
21467 : : }
21468 : :
21469 : : /*
21470 : : * If no suitable index was found in the partition-to-be, create one
21471 : : * now. Note that if this is a PK, not-null constraints must already
21472 : : * exist.
21473 : : */
21474 [ + + ]: 293 : if (!found)
21475 : : {
21476 : : IndexStmt *stmt;
21477 : : Oid conOid;
21478 : :
21479 : 152 : stmt = generateClonedIndexStmt(NULL,
21480 : : idxRel, attmap,
21481 : : &conOid);
21482 : 152 : DefineIndex(NULL,
21483 : : RelationGetRelid(attachrel), stmt, InvalidOid,
21484 : : RelationGetRelid(idxRel),
21485 : : conOid,
21486 : : -1,
21487 : : true, false, false, false, false);
21488 : : }
21489 : :
21490 : 281 : index_close(idxRel, AccessShareLock);
21491 : : }
21492 : :
21493 : 1333 : out:
21494 : : /* Clean up. */
21495 [ + + ]: 1578 : for (int i = 0; i < list_length(attachRelIdxs); i++)
21496 : 245 : index_close(attachrelIdxRels[i], AccessShareLock);
21497 : 1333 : MemoryContextSwitchTo(oldcxt);
21498 : 1333 : MemoryContextDelete(cxt);
21499 : 1333 : }
21500 : :
21501 : : /*
21502 : : * CloneRowTriggersToPartition
21503 : : * subroutine for ATExecAttachPartition/DefineRelation to create row
21504 : : * triggers on partitions
21505 : : */
21506 : : static void
21507 : 1565 : CloneRowTriggersToPartition(Relation parent, Relation partition)
21508 : : {
21509 : : Relation pg_trigger;
21510 : : ScanKeyData key;
21511 : : SysScanDesc scan;
21512 : : HeapTuple tuple;
21513 : : MemoryContext perTupCxt;
21514 : :
21515 : 1565 : ScanKeyInit(&key, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber,
21516 : : F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(parent)));
21517 : 1565 : pg_trigger = table_open(TriggerRelationId, RowExclusiveLock);
21518 : 1565 : scan = systable_beginscan(pg_trigger, TriggerRelidNameIndexId,
21519 : : true, NULL, 1, &key);
21520 : :
21521 : 1565 : perTupCxt = AllocSetContextCreate(CurrentMemoryContext,
21522 : : "clone trig", ALLOCSET_SMALL_SIZES);
21523 : :
21524 [ + + ]: 2622 : while (HeapTupleIsValid(tuple = systable_getnext(scan)))
21525 : : {
21526 : 1061 : Form_pg_trigger trigForm = (Form_pg_trigger) GETSTRUCT(tuple);
21527 : : CreateTrigStmt *trigStmt;
21528 : 1061 : Node *qual = NULL;
21529 : : Datum value;
21530 : : bool isnull;
21531 : 1061 : List *cols = NIL;
21532 : 1061 : List *trigargs = NIL;
21533 : : MemoryContext oldcxt;
21534 : :
21535 : : /*
21536 : : * Ignore statement-level triggers; those are not cloned.
21537 : : */
21538 [ + + ]: 1061 : if (!TRIGGER_FOR_ROW(trigForm->tgtype))
21539 : 958 : continue;
21540 : :
21541 : : /*
21542 : : * Don't clone internal triggers, because the constraint cloning code
21543 : : * will.
21544 : : */
21545 [ + + ]: 1049 : if (trigForm->tgisinternal)
21546 : 946 : continue;
21547 : :
21548 : : /*
21549 : : * Complain if we find an unexpected trigger type.
21550 : : */
21551 [ + + ]: 103 : if (!TRIGGER_FOR_BEFORE(trigForm->tgtype) &&
21552 [ - + ]: 91 : !TRIGGER_FOR_AFTER(trigForm->tgtype))
21553 [ # # ]: 0 : elog(ERROR, "unexpected trigger \"%s\" found",
21554 : : NameStr(trigForm->tgname));
21555 : :
21556 : : /* Use short-lived context for CREATE TRIGGER */
21557 : 103 : oldcxt = MemoryContextSwitchTo(perTupCxt);
21558 : :
21559 : : /*
21560 : : * If there is a WHEN clause, generate a 'cooked' version of it that's
21561 : : * appropriate for the partition.
21562 : : */
21563 : 103 : value = heap_getattr(tuple, Anum_pg_trigger_tgqual,
21564 : : RelationGetDescr(pg_trigger), &isnull);
21565 [ + + ]: 103 : if (!isnull)
21566 : : {
21567 : 4 : qual = stringToNode(TextDatumGetCString(value));
21568 : 4 : qual = (Node *) map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
21569 : : partition, parent);
21570 : 4 : qual = (Node *) map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
21571 : : partition, parent);
21572 : : }
21573 : :
21574 : : /*
21575 : : * If there is a column list, transform it to a list of column names.
21576 : : * Note we don't need to map this list in any way ...
21577 : : */
21578 [ + + ]: 103 : if (trigForm->tgattr.dim1 > 0)
21579 : : {
21580 : : int i;
21581 : :
21582 [ + + ]: 8 : for (i = 0; i < trigForm->tgattr.dim1; i++)
21583 : : {
21584 : : Form_pg_attribute col;
21585 : :
21586 : 4 : col = TupleDescAttr(parent->rd_att,
21587 : 4 : trigForm->tgattr.values[i] - 1);
21588 : 4 : cols = lappend(cols,
21589 : 4 : makeString(pstrdup(NameStr(col->attname))));
21590 : : }
21591 : : }
21592 : :
21593 : : /* Reconstruct trigger arguments list. */
21594 [ + + ]: 103 : if (trigForm->tgnargs > 0)
21595 : : {
21596 : : char *p;
21597 : :
21598 : 8 : value = heap_getattr(tuple, Anum_pg_trigger_tgargs,
21599 : : RelationGetDescr(pg_trigger), &isnull);
21600 [ - + ]: 8 : if (isnull)
21601 [ # # ]: 0 : elog(ERROR, "tgargs is null for trigger \"%s\" in partition \"%s\"",
21602 : : NameStr(trigForm->tgname), RelationGetRelationName(partition));
21603 : :
21604 : 8 : p = (char *) VARDATA_ANY(DatumGetByteaPP(value));
21605 : :
21606 [ + + ]: 24 : for (int i = 0; i < trigForm->tgnargs; i++)
21607 : : {
21608 : 16 : trigargs = lappend(trigargs, makeString(pstrdup(p)));
21609 : 16 : p += strlen(p) + 1;
21610 : : }
21611 : : }
21612 : :
21613 : 103 : trigStmt = makeNode(CreateTrigStmt);
21614 : 103 : trigStmt->replace = false;
21615 : 103 : trigStmt->isconstraint = OidIsValid(trigForm->tgconstraint);
21616 : 103 : trigStmt->trigname = NameStr(trigForm->tgname);
21617 : 103 : trigStmt->relation = NULL;
21618 : 103 : trigStmt->funcname = NULL; /* passed separately */
21619 : 103 : trigStmt->args = trigargs;
21620 : 103 : trigStmt->row = true;
21621 : 103 : trigStmt->timing = trigForm->tgtype & TRIGGER_TYPE_TIMING_MASK;
21622 : 103 : trigStmt->events = trigForm->tgtype & TRIGGER_TYPE_EVENT_MASK;
21623 : 103 : trigStmt->columns = cols;
21624 : 103 : trigStmt->whenClause = NULL; /* passed separately */
21625 : 103 : trigStmt->transitionRels = NIL; /* not supported at present */
21626 : 103 : trigStmt->deferrable = trigForm->tgdeferrable;
21627 : 103 : trigStmt->initdeferred = trigForm->tginitdeferred;
21628 : 103 : trigStmt->constrrel = NULL; /* passed separately */
21629 : :
21630 : 103 : CreateTriggerFiringOn(trigStmt, NULL, RelationGetRelid(partition),
21631 : : trigForm->tgconstrrelid, InvalidOid, InvalidOid,
21632 : : trigForm->tgfoid, trigForm->oid, qual,
21633 : 103 : false, true, trigForm->tgenabled);
21634 : :
21635 : 99 : MemoryContextSwitchTo(oldcxt);
21636 : 99 : MemoryContextReset(perTupCxt);
21637 : : }
21638 : :
21639 : 1561 : MemoryContextDelete(perTupCxt);
21640 : :
21641 : 1561 : systable_endscan(scan);
21642 : 1561 : table_close(pg_trigger, RowExclusiveLock);
21643 : 1561 : }
21644 : :
21645 : : /*
21646 : : * ALTER TABLE DETACH PARTITION
21647 : : *
21648 : : * Return the address of the relation that is no longer a partition of rel.
21649 : : *
21650 : : * If concurrent mode is requested, we run in two transactions. A side-
21651 : : * effect is that this command cannot run in a multi-part ALTER TABLE.
21652 : : * Currently, that's enforced by the grammar.
21653 : : *
21654 : : * The strategy for concurrency is to first modify the partition's
21655 : : * pg_inherit catalog row to make it visible to everyone that the
21656 : : * partition is detached, lock the partition against writes, and commit
21657 : : * the transaction; anyone who requests the partition descriptor from
21658 : : * that point onwards has to ignore such a partition. In a second
21659 : : * transaction, we wait until all transactions that could have seen the
21660 : : * partition as attached are gone, then we remove the rest of partition
21661 : : * metadata (pg_inherits and pg_class.relpartbounds).
21662 : : */
21663 : : static ObjectAddress
21664 : 362 : ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab, Relation rel,
21665 : : RangeVar *name, bool concurrent)
21666 : : {
21667 : : Relation partRel;
21668 : : ObjectAddress address;
21669 : : Oid defaultPartOid;
21670 : :
21671 : : /*
21672 : : * We must lock the default partition, because detaching this partition
21673 : : * will change its partition constraint.
21674 : : */
21675 : : defaultPartOid =
21676 : 362 : get_default_oid_from_partdesc(RelationGetPartitionDesc(rel, true));
21677 [ + + ]: 362 : if (OidIsValid(defaultPartOid))
21678 : : {
21679 : : /*
21680 : : * Concurrent detaching when a default partition exists is not
21681 : : * supported. The main problem is that the default partition
21682 : : * constraint would change. And there's a definitional problem: what
21683 : : * should happen to the tuples that are being inserted that belong to
21684 : : * the partition being detached? Putting them on the partition being
21685 : : * detached would be wrong, since they'd become "lost" after the
21686 : : * detaching completes but we cannot put them in the default partition
21687 : : * either until we alter its partition constraint.
21688 : : *
21689 : : * I think we could solve this problem if we effected the constraint
21690 : : * change before committing the first transaction. But the lock would
21691 : : * have to remain AEL and it would cause concurrent query planning to
21692 : : * be blocked, so changing it that way would be even worse.
21693 : : */
21694 [ + + ]: 70 : if (concurrent)
21695 [ + - ]: 8 : ereport(ERROR,
21696 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21697 : : errmsg("cannot detach partitions concurrently when a default partition exists")));
21698 : 62 : LockRelationOid(defaultPartOid, AccessExclusiveLock);
21699 : : }
21700 : :
21701 : : /*
21702 : : * In concurrent mode, the partition is locked with share-update-exclusive
21703 : : * in the first transaction. This allows concurrent transactions to be
21704 : : * doing DML to the partition.
21705 : : */
21706 [ + + ]: 354 : partRel = table_openrv(name, concurrent ? ShareUpdateExclusiveLock :
21707 : : AccessExclusiveLock);
21708 : :
21709 : : /*
21710 : : * Check inheritance conditions and either delete the pg_inherits row (in
21711 : : * non-concurrent mode) or just set the inhdetachpending flag.
21712 : : */
21713 [ + + ]: 346 : if (!concurrent)
21714 : 270 : RemoveInheritance(partRel, rel, false);
21715 : : else
21716 : 76 : MarkInheritDetached(partRel, rel);
21717 : :
21718 : : /*
21719 : : * Ensure that foreign keys still hold after this detach. This keeps
21720 : : * locks on the referencing tables, which prevents concurrent transactions
21721 : : * from adding rows that we wouldn't see. For this to work in concurrent
21722 : : * mode, it is critical that the partition appears as no longer attached
21723 : : * for the RI queries as soon as the first transaction commits.
21724 : : */
21725 : 333 : ATDetachCheckNoForeignKeyRefs(partRel);
21726 : :
21727 : : /*
21728 : : * Concurrent mode has to work harder; first we add a new constraint to
21729 : : * the partition that matches the partition constraint. Then we close our
21730 : : * existing transaction, and in a new one wait for all processes to catch
21731 : : * up on the catalog updates we've done so far; at that point we can
21732 : : * complete the operation.
21733 : : */
21734 [ + + ]: 311 : if (concurrent)
21735 : : {
21736 : : Oid partrelid,
21737 : : parentrelid;
21738 : : LOCKTAG tag;
21739 : : char *parentrelname;
21740 : : char *partrelname;
21741 : :
21742 : : /*
21743 : : * We're almost done now; the only traces that remain are the
21744 : : * pg_inherits tuple and the partition's relpartbounds. Before we can
21745 : : * remove those, we need to wait until all transactions that know that
21746 : : * this is a partition are gone.
21747 : : */
21748 : :
21749 : : /*
21750 : : * Remember relation OIDs to re-acquire them later; and relation names
21751 : : * too, for error messages if something is dropped in between.
21752 : : */
21753 : 73 : partrelid = RelationGetRelid(partRel);
21754 : 73 : parentrelid = RelationGetRelid(rel);
21755 : 73 : parentrelname = MemoryContextStrdup(PortalContext,
21756 : 73 : RelationGetRelationName(rel));
21757 : 73 : partrelname = MemoryContextStrdup(PortalContext,
21758 : 73 : RelationGetRelationName(partRel));
21759 : :
21760 : : /* Invalidate relcache entries for the parent -- must be before close */
21761 : 73 : CacheInvalidateRelcache(rel);
21762 : :
21763 : 73 : table_close(partRel, NoLock);
21764 : 73 : table_close(rel, NoLock);
21765 : 73 : tab->rel = NULL;
21766 : :
21767 : : /* Make updated catalog entry visible */
21768 : 73 : PopActiveSnapshot();
21769 : 73 : CommitTransactionCommand();
21770 : :
21771 : 73 : StartTransactionCommand();
21772 : :
21773 : : /*
21774 : : * Now wait. This ensures that all queries that were planned
21775 : : * including the partition are finished before we remove the rest of
21776 : : * catalog entries. We don't need or indeed want to acquire this
21777 : : * lock, though -- that would block later queries.
21778 : : *
21779 : : * We don't need to concern ourselves with waiting for a lock on the
21780 : : * partition itself, since we will acquire AccessExclusiveLock below.
21781 : : */
21782 : 73 : SET_LOCKTAG_RELATION(tag, MyDatabaseId, parentrelid);
21783 : 73 : WaitForLockersMultiple(list_make1(&tag), AccessExclusiveLock, false);
21784 : :
21785 : : /*
21786 : : * Now acquire locks in both relations again. Note they may have been
21787 : : * removed in the meantime, so care is required.
21788 : : */
21789 : 47 : rel = try_relation_open(parentrelid, ShareUpdateExclusiveLock);
21790 : 47 : partRel = try_relation_open(partrelid, AccessExclusiveLock);
21791 : :
21792 : : /* If the relations aren't there, something bad happened; bail out */
21793 [ - + ]: 47 : if (rel == NULL)
21794 : : {
21795 [ # # ]: 0 : if (partRel != NULL) /* shouldn't happen */
21796 [ # # ]: 0 : elog(WARNING, "dangling partition \"%s\" remains, can't fix",
21797 : : partrelname);
21798 [ # # ]: 0 : ereport(ERROR,
21799 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21800 : : errmsg("partitioned table \"%s\" was removed concurrently",
21801 : : parentrelname)));
21802 : : }
21803 [ - + ]: 47 : if (partRel == NULL)
21804 [ # # ]: 0 : ereport(ERROR,
21805 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
21806 : : errmsg("partition \"%s\" was removed concurrently", partrelname)));
21807 : :
21808 : 47 : tab->rel = rel;
21809 : : }
21810 : :
21811 : : /*
21812 : : * Detaching the partition might involve TOAST table access, so ensure we
21813 : : * have a valid snapshot.
21814 : : */
21815 : 285 : PushActiveSnapshot(GetTransactionSnapshot());
21816 : :
21817 : : /* Do the final part of detaching */
21818 : 285 : DetachPartitionFinalize(rel, partRel, concurrent, defaultPartOid);
21819 : :
21820 : 284 : PopActiveSnapshot();
21821 : :
21822 : 284 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partRel));
21823 : :
21824 : : /* keep our lock until commit */
21825 : 284 : table_close(partRel, NoLock);
21826 : :
21827 : 284 : return address;
21828 : : }
21829 : :
21830 : : /*
21831 : : * Second part of ALTER TABLE .. DETACH.
21832 : : *
21833 : : * This is separate so that it can be run independently when the second
21834 : : * transaction of the concurrent algorithm fails (crash or abort).
21835 : : */
21836 : : static void
21837 : 292 : DetachPartitionFinalize(Relation rel, Relation partRel, bool concurrent,
21838 : : Oid defaultPartOid)
21839 : : {
21840 : : Relation classRel;
21841 : : List *fks;
21842 : : ListCell *cell;
21843 : : List *indexes;
21844 : : Datum new_val[Natts_pg_class];
21845 : : bool new_null[Natts_pg_class],
21846 : : new_repl[Natts_pg_class];
21847 : : HeapTuple tuple,
21848 : : newtuple;
21849 : 292 : Relation trigrel = NULL;
21850 : 292 : List *fkoids = NIL;
21851 : :
21852 [ + + ]: 292 : if (concurrent)
21853 : : {
21854 : : /*
21855 : : * We can remove the pg_inherits row now. (In the non-concurrent case,
21856 : : * this was already done).
21857 : : */
21858 : 54 : RemoveInheritance(partRel, rel, true);
21859 : : }
21860 : :
21861 : : /* Drop any triggers that were cloned on creation/attach. */
21862 : 292 : DropClonedTriggersFromPartition(RelationGetRelid(partRel));
21863 : :
21864 : : /*
21865 : : * Detach any foreign keys that are inherited. This includes creating
21866 : : * additional action triggers.
21867 : : */
21868 : 292 : fks = copyObject(RelationGetFKeyList(partRel));
21869 [ + + ]: 292 : if (fks != NIL)
21870 : 56 : trigrel = table_open(TriggerRelationId, RowExclusiveLock);
21871 : :
21872 : : /*
21873 : : * It's possible that the partition being detached has a foreign key that
21874 : : * references a partitioned table. When that happens, there are multiple
21875 : : * pg_constraint rows for the partition: one points to the partitioned
21876 : : * table itself, while the others point to each of its partitions. Only
21877 : : * the topmost one is to be considered here; the child constraints must be
21878 : : * left alone, because conceptually those aren't coming from our parent
21879 : : * partitioned table, but from this partition itself.
21880 : : *
21881 : : * We implement this by collecting all the constraint OIDs in a first scan
21882 : : * of the FK array, and skipping in the loop below those constraints whose
21883 : : * parents are listed here.
21884 : : */
21885 [ + + + + : 696 : foreach_node(ForeignKeyCacheInfo, fk, fks)
+ + ]
21886 : 112 : fkoids = lappend_oid(fkoids, fk->conoid);
21887 : :
21888 [ + + + + : 404 : foreach(cell, fks)
+ + ]
21889 : : {
21890 : 112 : ForeignKeyCacheInfo *fk = lfirst(cell);
21891 : : HeapTuple contup;
21892 : : Form_pg_constraint conform;
21893 : :
21894 : 112 : contup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(fk->conoid));
21895 [ - + ]: 112 : if (!HeapTupleIsValid(contup))
21896 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", fk->conoid);
21897 : 112 : conform = (Form_pg_constraint) GETSTRUCT(contup);
21898 : :
21899 : : /*
21900 : : * Consider only inherited foreign keys, and only if their parents
21901 : : * aren't in the list.
21902 : : */
21903 [ + - ]: 112 : if (conform->contype != CONSTRAINT_FOREIGN ||
21904 [ + + + + ]: 208 : !OidIsValid(conform->conparentid) ||
21905 : 96 : list_member_oid(fkoids, conform->conparentid))
21906 : : {
21907 : 44 : ReleaseSysCache(contup);
21908 : 44 : continue;
21909 : : }
21910 : :
21911 : : /*
21912 : : * The constraint on this table must be marked no longer a child of
21913 : : * the parent's constraint, as do its check triggers.
21914 : : */
21915 : 68 : ConstraintSetParentConstraint(fk->conoid, InvalidOid, InvalidOid);
21916 : :
21917 : : /*
21918 : : * Also, look up the partition's "check" triggers corresponding to the
21919 : : * ENFORCED constraint being detached and detach them from the parent
21920 : : * triggers. NOT ENFORCED constraints do not have these triggers;
21921 : : * therefore, this step is not needed.
21922 : : */
21923 [ + - ]: 68 : if (fk->conenforced)
21924 : : {
21925 : : Oid insertTriggerOid,
21926 : : updateTriggerOid;
21927 : :
21928 : 68 : GetForeignKeyCheckTriggers(trigrel,
21929 : : fk->conoid, fk->confrelid, fk->conrelid,
21930 : : &insertTriggerOid, &updateTriggerOid);
21931 : : Assert(OidIsValid(insertTriggerOid));
21932 : 68 : TriggerSetParentTrigger(trigrel, insertTriggerOid, InvalidOid,
21933 : : RelationGetRelid(partRel));
21934 : : Assert(OidIsValid(updateTriggerOid));
21935 : 68 : TriggerSetParentTrigger(trigrel, updateTriggerOid, InvalidOid,
21936 : : RelationGetRelid(partRel));
21937 : : }
21938 : :
21939 : : /*
21940 : : * Lastly, create the action triggers on the referenced table, using
21941 : : * addFkRecurseReferenced, which requires some elaborate setup (so put
21942 : : * it in a separate block). While at it, if the table is partitioned,
21943 : : * that function will recurse to create the pg_constraint rows and
21944 : : * action triggers for each partition.
21945 : : *
21946 : : * Note there's no need to do addFkConstraint() here, because the
21947 : : * pg_constraint row already exists.
21948 : : */
21949 : : {
21950 : : Constraint *fkconstraint;
21951 : : int numfks;
21952 : : AttrNumber conkey[INDEX_MAX_KEYS];
21953 : : AttrNumber confkey[INDEX_MAX_KEYS];
21954 : : Oid conpfeqop[INDEX_MAX_KEYS];
21955 : : Oid conppeqop[INDEX_MAX_KEYS];
21956 : : Oid conffeqop[INDEX_MAX_KEYS];
21957 : : int numfkdelsetcols;
21958 : : AttrNumber confdelsetcols[INDEX_MAX_KEYS];
21959 : : Relation refdRel;
21960 : :
21961 : 68 : DeconstructFkConstraintRow(contup,
21962 : : &numfks,
21963 : : conkey,
21964 : : confkey,
21965 : : conpfeqop,
21966 : : conppeqop,
21967 : : conffeqop,
21968 : : &numfkdelsetcols,
21969 : : confdelsetcols);
21970 : :
21971 : : /* Create a synthetic node we'll use throughout */
21972 : 68 : fkconstraint = makeNode(Constraint);
21973 : 68 : fkconstraint->contype = CONSTRAINT_FOREIGN;
21974 : 68 : fkconstraint->conname = pstrdup(NameStr(conform->conname));
21975 : 68 : fkconstraint->deferrable = conform->condeferrable;
21976 : 68 : fkconstraint->initdeferred = conform->condeferred;
21977 : 68 : fkconstraint->is_enforced = conform->conenforced;
21978 : 68 : fkconstraint->skip_validation = true;
21979 : 68 : fkconstraint->initially_valid = conform->convalidated;
21980 : : /* a few irrelevant fields omitted here */
21981 : 68 : fkconstraint->pktable = NULL;
21982 : 68 : fkconstraint->fk_attrs = NIL;
21983 : 68 : fkconstraint->pk_attrs = NIL;
21984 : 68 : fkconstraint->fk_matchtype = conform->confmatchtype;
21985 : 68 : fkconstraint->fk_upd_action = conform->confupdtype;
21986 : 68 : fkconstraint->fk_del_action = conform->confdeltype;
21987 : 68 : fkconstraint->fk_del_set_cols = NIL;
21988 : 68 : fkconstraint->old_conpfeqop = NIL;
21989 : 68 : fkconstraint->old_pktable_oid = InvalidOid;
21990 : 68 : fkconstraint->location = -1;
21991 : :
21992 : : /* set up colnames, used to generate the constraint name */
21993 [ + + ]: 168 : for (int i = 0; i < numfks; i++)
21994 : : {
21995 : : Form_pg_attribute att;
21996 : :
21997 : 100 : att = TupleDescAttr(RelationGetDescr(partRel),
21998 : 100 : conkey[i] - 1);
21999 : :
22000 : 100 : fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
22001 : 100 : makeString(NameStr(att->attname)));
22002 : : }
22003 : :
22004 : 68 : refdRel = table_open(fk->confrelid, ShareRowExclusiveLock);
22005 : :
22006 : 68 : addFkRecurseReferenced(fkconstraint, partRel,
22007 : : refdRel,
22008 : : conform->conindid,
22009 : : fk->conoid,
22010 : : numfks,
22011 : : confkey,
22012 : : conkey,
22013 : : conpfeqop,
22014 : : conppeqop,
22015 : : conffeqop,
22016 : : numfkdelsetcols,
22017 : : confdelsetcols,
22018 : : true,
22019 : : InvalidOid, InvalidOid,
22020 : 68 : conform->conperiod);
22021 : 68 : table_close(refdRel, NoLock); /* keep lock till end of xact */
22022 : : }
22023 : :
22024 : 68 : ReleaseSysCache(contup);
22025 : : }
22026 : 292 : list_free_deep(fks);
22027 [ + + ]: 292 : if (trigrel)
22028 : 56 : table_close(trigrel, RowExclusiveLock);
22029 : :
22030 : : /*
22031 : : * Any sub-constraints that are in the referenced-side of a larger
22032 : : * constraint have to be removed. This partition is no longer part of the
22033 : : * key space of the constraint.
22034 : : */
22035 [ + + + + : 327 : foreach(cell, GetParentedForeignKeyRefs(partRel))
+ + ]
22036 : : {
22037 : 36 : Oid constrOid = lfirst_oid(cell);
22038 : : ObjectAddress constraint;
22039 : :
22040 : 36 : ConstraintSetParentConstraint(constrOid, InvalidOid, InvalidOid);
22041 : 36 : deleteDependencyRecordsForClass(ConstraintRelationId,
22042 : : constrOid,
22043 : : ConstraintRelationId,
22044 : : DEPENDENCY_INTERNAL);
22045 : 36 : CommandCounterIncrement();
22046 : :
22047 : 36 : ObjectAddressSet(constraint, ConstraintRelationId, constrOid);
22048 : 36 : performDeletion(&constraint, DROP_RESTRICT, 0);
22049 : : }
22050 : :
22051 : : /* Now we can detach indexes */
22052 : 291 : indexes = RelationGetIndexList(partRel);
22053 [ + + + + : 415 : foreach(cell, indexes)
+ + ]
22054 : : {
22055 : 124 : Oid idxid = lfirst_oid(cell);
22056 : : Oid parentidx;
22057 : : Relation idx;
22058 : : Oid constrOid;
22059 : : Oid parentConstrOid;
22060 : :
22061 [ + + ]: 124 : if (!has_superclass(idxid))
22062 : 8 : continue;
22063 : :
22064 : 116 : parentidx = get_partition_parent(idxid, false);
22065 : : Assert((IndexGetRelation(parentidx, false) == RelationGetRelid(rel)));
22066 : :
22067 : 116 : idx = index_open(idxid, AccessExclusiveLock);
22068 : 116 : IndexSetParentIndex(idx, InvalidOid);
22069 : :
22070 : : /*
22071 : : * If there's a constraint associated with the index, detach it too.
22072 : : * Careful: it is possible for a constraint index in a partition to be
22073 : : * the child of a non-constraint index, so verify whether the parent
22074 : : * index does actually have a constraint.
22075 : : */
22076 : 116 : constrOid = get_relation_idx_constraint_oid(RelationGetRelid(partRel),
22077 : : idxid);
22078 : 116 : parentConstrOid = get_relation_idx_constraint_oid(RelationGetRelid(rel),
22079 : : parentidx);
22080 [ + + + - ]: 116 : if (OidIsValid(parentConstrOid) && OidIsValid(constrOid))
22081 : 51 : ConstraintSetParentConstraint(constrOid, InvalidOid, InvalidOid);
22082 : :
22083 : 116 : index_close(idx, NoLock);
22084 : : }
22085 : :
22086 : : /* Update pg_class tuple */
22087 : 291 : classRel = table_open(RelationRelationId, RowExclusiveLock);
22088 : 291 : tuple = SearchSysCacheCopy1(RELOID,
22089 : : ObjectIdGetDatum(RelationGetRelid(partRel)));
22090 [ - + ]: 291 : if (!HeapTupleIsValid(tuple))
22091 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u",
22092 : : RelationGetRelid(partRel));
22093 : : Assert(((Form_pg_class) GETSTRUCT(tuple))->relispartition);
22094 : :
22095 : : /* Clear relpartbound and reset relispartition */
22096 : 291 : memset(new_val, 0, sizeof(new_val));
22097 : 291 : memset(new_null, false, sizeof(new_null));
22098 : 291 : memset(new_repl, false, sizeof(new_repl));
22099 : 291 : new_val[Anum_pg_class_relpartbound - 1] = (Datum) 0;
22100 : 291 : new_null[Anum_pg_class_relpartbound - 1] = true;
22101 : 291 : new_repl[Anum_pg_class_relpartbound - 1] = true;
22102 : 291 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(classRel),
22103 : : new_val, new_null, new_repl);
22104 : :
22105 : 291 : ((Form_pg_class) GETSTRUCT(newtuple))->relispartition = false;
22106 : 291 : CatalogTupleUpdate(classRel, &newtuple->t_self, newtuple);
22107 : 291 : heap_freetuple(newtuple);
22108 : 291 : table_close(classRel, RowExclusiveLock);
22109 : :
22110 : : /*
22111 : : * Drop identity property from all identity columns of partition.
22112 : : */
22113 [ + + ]: 840 : for (int attno = 0; attno < RelationGetNumberOfAttributes(partRel); attno++)
22114 : : {
22115 : 549 : Form_pg_attribute attr = TupleDescAttr(partRel->rd_att, attno);
22116 : :
22117 [ + + + + ]: 549 : if (!attr->attisdropped && attr->attidentity)
22118 : 4 : ATExecDropIdentity(partRel, NameStr(attr->attname), false,
22119 : : AccessExclusiveLock, true, true);
22120 : : }
22121 : :
22122 [ + + ]: 291 : if (OidIsValid(defaultPartOid))
22123 : : {
22124 : : /*
22125 : : * If the relation being detached is the default partition itself,
22126 : : * remove it from the parent's pg_partitioned_table entry.
22127 : : *
22128 : : * If not, we must invalidate default partition's relcache entry, as
22129 : : * in StorePartitionBound: its partition constraint depends on every
22130 : : * other partition's partition constraint.
22131 : : */
22132 [ + + ]: 30 : if (RelationGetRelid(partRel) == defaultPartOid)
22133 : 1 : update_default_partition_oid(RelationGetRelid(rel), InvalidOid);
22134 : : else
22135 : 29 : CacheInvalidateRelcacheByRelid(defaultPartOid);
22136 : : }
22137 : :
22138 : : /*
22139 : : * Invalidate the parent's relcache so that the partition is no longer
22140 : : * included in its partition descriptor.
22141 : : */
22142 : 291 : CacheInvalidateRelcache(rel);
22143 : :
22144 : : /*
22145 : : * If the partition we just detached is partitioned itself, invalidate
22146 : : * relcache for all descendent partitions too to ensure that their
22147 : : * rd_partcheck expression trees are rebuilt; must lock partitions before
22148 : : * doing so, using the same lockmode as what partRel has been locked with
22149 : : * by the caller.
22150 : : */
22151 [ + + ]: 291 : if (partRel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
22152 : : {
22153 : : List *children;
22154 : :
22155 : 41 : children = find_all_inheritors(RelationGetRelid(partRel),
22156 : : AccessExclusiveLock, NULL);
22157 [ + - + + : 135 : foreach(cell, children)
+ + ]
22158 : : {
22159 : 94 : CacheInvalidateRelcacheByRelid(lfirst_oid(cell));
22160 : : }
22161 : : }
22162 : 291 : }
22163 : :
22164 : : /*
22165 : : * ALTER TABLE ... DETACH PARTITION ... FINALIZE
22166 : : *
22167 : : * To use when a DETACH PARTITION command previously did not run to
22168 : : * completion; this completes the detaching process.
22169 : : */
22170 : : static ObjectAddress
22171 : 7 : ATExecDetachPartitionFinalize(Relation rel, RangeVar *name)
22172 : : {
22173 : : Relation partRel;
22174 : : ObjectAddress address;
22175 : 7 : Snapshot snap = GetActiveSnapshot();
22176 : :
22177 : 7 : partRel = table_openrv(name, AccessExclusiveLock);
22178 : :
22179 : : /*
22180 : : * Wait until existing snapshots are gone. This is important if the
22181 : : * second transaction of DETACH PARTITION CONCURRENTLY is canceled: the
22182 : : * user could immediately run DETACH FINALIZE without actually waiting for
22183 : : * existing transactions. We must not complete the detach action until
22184 : : * all such queries are complete (otherwise we would present them with an
22185 : : * inconsistent view of catalogs).
22186 : : */
22187 : 7 : WaitForOlderSnapshots(snap->xmin, false);
22188 : :
22189 : 7 : DetachPartitionFinalize(rel, partRel, true, InvalidOid);
22190 : :
22191 : 7 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partRel));
22192 : :
22193 : 7 : table_close(partRel, NoLock);
22194 : :
22195 : 7 : return address;
22196 : : }
22197 : :
22198 : : /*
22199 : : * DropClonedTriggersFromPartition
22200 : : * subroutine for ATExecDetachPartition to remove any triggers that were
22201 : : * cloned to the partition when it was created-as-partition or attached.
22202 : : * This undoes what CloneRowTriggersToPartition did.
22203 : : */
22204 : : static void
22205 : 292 : DropClonedTriggersFromPartition(Oid partitionId)
22206 : : {
22207 : : ScanKeyData skey;
22208 : : SysScanDesc scan;
22209 : : HeapTuple trigtup;
22210 : : Relation tgrel;
22211 : : ObjectAddresses *objects;
22212 : :
22213 : 292 : objects = new_object_addresses();
22214 : :
22215 : : /*
22216 : : * Scan pg_trigger to search for all triggers on this rel.
22217 : : */
22218 : 292 : ScanKeyInit(&skey, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber,
22219 : : F_OIDEQ, ObjectIdGetDatum(partitionId));
22220 : 292 : tgrel = table_open(TriggerRelationId, RowExclusiveLock);
22221 : 292 : scan = systable_beginscan(tgrel, TriggerRelidNameIndexId,
22222 : : true, NULL, 1, &skey);
22223 [ + + ]: 556 : while (HeapTupleIsValid(trigtup = systable_getnext(scan)))
22224 : : {
22225 : 264 : Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(trigtup);
22226 : : ObjectAddress trig;
22227 : :
22228 : : /* Ignore triggers that weren't cloned */
22229 [ + + ]: 264 : if (!OidIsValid(pg_trigger->tgparentid))
22230 : 252 : continue;
22231 : :
22232 : : /*
22233 : : * Ignore internal triggers that are implementation objects of foreign
22234 : : * keys, because these will be detached when the foreign keys
22235 : : * themselves are.
22236 : : */
22237 [ + + ]: 220 : if (OidIsValid(pg_trigger->tgconstrrelid))
22238 : 208 : continue;
22239 : :
22240 : : /*
22241 : : * This is ugly, but necessary: remove the dependency markings on the
22242 : : * trigger so that it can be removed.
22243 : : */
22244 : 12 : deleteDependencyRecordsForClass(TriggerRelationId, pg_trigger->oid,
22245 : : TriggerRelationId,
22246 : : DEPENDENCY_PARTITION_PRI);
22247 : 12 : deleteDependencyRecordsForClass(TriggerRelationId, pg_trigger->oid,
22248 : : RelationRelationId,
22249 : : DEPENDENCY_PARTITION_SEC);
22250 : :
22251 : : /* remember this trigger to remove it below */
22252 : 12 : ObjectAddressSet(trig, TriggerRelationId, pg_trigger->oid);
22253 : 12 : add_exact_object_address(&trig, objects);
22254 : : }
22255 : :
22256 : : /* make the dependency removal visible to the deletion below */
22257 : 292 : CommandCounterIncrement();
22258 : 292 : performMultipleDeletions(objects, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
22259 : :
22260 : : /* done */
22261 : 292 : free_object_addresses(objects);
22262 : 292 : systable_endscan(scan);
22263 : 292 : table_close(tgrel, RowExclusiveLock);
22264 : 292 : }
22265 : :
22266 : : /*
22267 : : * Before acquiring lock on an index, acquire the same lock on the owning
22268 : : * table.
22269 : : */
22270 : : struct AttachIndexCallbackState
22271 : : {
22272 : : Oid partitionOid;
22273 : : Oid parentTblOid;
22274 : : bool lockedParentTbl;
22275 : : };
22276 : :
22277 : : static void
22278 : 295 : RangeVarCallbackForAttachIndex(const RangeVar *rv, Oid relOid, Oid oldRelOid,
22279 : : void *arg)
22280 : : {
22281 : : struct AttachIndexCallbackState *state;
22282 : : Form_pg_class classform;
22283 : : HeapTuple tuple;
22284 : :
22285 : 295 : state = (struct AttachIndexCallbackState *) arg;
22286 : :
22287 [ + + ]: 295 : if (!state->lockedParentTbl)
22288 : : {
22289 : 286 : LockRelationOid(state->parentTblOid, AccessShareLock);
22290 : 286 : state->lockedParentTbl = true;
22291 : : }
22292 : :
22293 : : /*
22294 : : * If we previously locked some other heap, and the name we're looking up
22295 : : * no longer refers to an index on that relation, release the now-useless
22296 : : * lock. XXX maybe we should do *after* we verify whether the index does
22297 : : * not actually belong to the same relation ...
22298 : : */
22299 [ + + - + ]: 295 : if (relOid != oldRelOid && OidIsValid(state->partitionOid))
22300 : : {
22301 : 0 : UnlockRelationOid(state->partitionOid, AccessShareLock);
22302 : 0 : state->partitionOid = InvalidOid;
22303 : : }
22304 : :
22305 : : /* Didn't find a relation, so no need for locking or permission checks. */
22306 [ + + ]: 295 : if (!OidIsValid(relOid))
22307 : 4 : return;
22308 : :
22309 : 291 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
22310 [ - + ]: 291 : if (!HeapTupleIsValid(tuple))
22311 : 0 : return; /* concurrently dropped, so nothing to do */
22312 : 291 : classform = (Form_pg_class) GETSTRUCT(tuple);
22313 [ + + ]: 291 : if (classform->relkind != RELKIND_PARTITIONED_INDEX &&
22314 [ + + ]: 225 : classform->relkind != RELKIND_INDEX)
22315 [ + - ]: 4 : ereport(ERROR,
22316 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
22317 : : errmsg("\"%s\" is not an index", rv->relname)));
22318 : 287 : ReleaseSysCache(tuple);
22319 : :
22320 : : /*
22321 : : * Since we need only examine the heap's tupledesc, an access share lock
22322 : : * on it (preventing any DDL) is sufficient.
22323 : : */
22324 : 287 : state->partitionOid = IndexGetRelation(relOid, false);
22325 : 287 : LockRelationOid(state->partitionOid, AccessShareLock);
22326 : : }
22327 : :
22328 : : /*
22329 : : * ALTER INDEX i1 ATTACH PARTITION i2
22330 : : */
22331 : : static ObjectAddress
22332 : 286 : ATExecAttachPartitionIdx(List **wqueue, Relation parentIdx, RangeVar *name)
22333 : : {
22334 : : Relation partIdx;
22335 : : Relation partTbl;
22336 : : Relation parentTbl;
22337 : : ObjectAddress address;
22338 : : Oid partIdxId;
22339 : : Oid currParent;
22340 : : struct AttachIndexCallbackState state;
22341 : :
22342 : : /*
22343 : : * We need to obtain lock on the index 'name' to modify it, but we also
22344 : : * need to read its owning table's tuple descriptor -- so we need to lock
22345 : : * both. To avoid deadlocks, obtain lock on the table before doing so on
22346 : : * the index. Furthermore, we need to examine the parent table of the
22347 : : * partition, so lock that one too.
22348 : : */
22349 : 286 : state.partitionOid = InvalidOid;
22350 : 286 : state.parentTblOid = parentIdx->rd_index->indrelid;
22351 : 286 : state.lockedParentTbl = false;
22352 : : partIdxId =
22353 : 286 : RangeVarGetRelidExtended(name, AccessExclusiveLock, 0,
22354 : : RangeVarCallbackForAttachIndex,
22355 : : &state);
22356 : : /* Not there? */
22357 [ - + ]: 278 : if (!OidIsValid(partIdxId))
22358 [ # # ]: 0 : ereport(ERROR,
22359 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
22360 : : errmsg("index \"%s\" does not exist", name->relname)));
22361 : :
22362 : : /* no deadlock risk: RangeVarGetRelidExtended already acquired the lock */
22363 : 278 : partIdx = relation_open(partIdxId, AccessExclusiveLock);
22364 : :
22365 : : /* we already hold locks on both tables, so this is safe: */
22366 : 278 : parentTbl = relation_open(parentIdx->rd_index->indrelid, AccessShareLock);
22367 : 278 : partTbl = relation_open(partIdx->rd_index->indrelid, NoLock);
22368 : :
22369 : 278 : ObjectAddressSet(address, RelationRelationId, RelationGetRelid(partIdx));
22370 : :
22371 : : /*
22372 : : * Check if the index is already attached to the correct parent,
22373 : : * ultimately attempting one round of validation if already the case.
22374 : : */
22375 : 556 : currParent = partIdx->rd_rel->relispartition ?
22376 [ + + ]: 278 : get_partition_parent(partIdxId, false) : InvalidOid;
22377 [ + + ]: 278 : if (currParent != RelationGetRelid(parentIdx))
22378 : : {
22379 : : IndexInfo *childInfo;
22380 : : IndexInfo *parentInfo;
22381 : : AttrMap *attmap;
22382 : : bool found;
22383 : : int i;
22384 : : PartitionDesc partDesc;
22385 : : Oid constraintOid,
22386 : 254 : cldConstrId = InvalidOid;
22387 : :
22388 : : /*
22389 : : * If this partition already has an index attached, refuse the
22390 : : * operation.
22391 : : */
22392 : 254 : refuseDupeIndexAttach(parentIdx, partIdx, partTbl);
22393 : :
22394 [ - + ]: 250 : if (OidIsValid(currParent))
22395 [ # # ]: 0 : ereport(ERROR,
22396 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
22397 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
22398 : : RelationGetRelationName(partIdx),
22399 : : RelationGetRelationName(parentIdx)),
22400 : : errdetail("Index \"%s\" is already attached to another index.",
22401 : : RelationGetRelationName(partIdx))));
22402 : :
22403 : : /* Make sure it indexes a partition of the other index's table */
22404 : 250 : partDesc = RelationGetPartitionDesc(parentTbl, true);
22405 : 250 : found = false;
22406 [ + + ]: 379 : for (i = 0; i < partDesc->nparts; i++)
22407 : : {
22408 [ + + ]: 375 : if (partDesc->oids[i] == state.partitionOid)
22409 : : {
22410 : 246 : found = true;
22411 : 246 : break;
22412 : : }
22413 : : }
22414 [ + + ]: 250 : if (!found)
22415 [ + - ]: 4 : ereport(ERROR,
22416 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
22417 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
22418 : : RelationGetRelationName(partIdx),
22419 : : RelationGetRelationName(parentIdx)),
22420 : : errdetail("Index \"%s\" is not an index on any partition of table \"%s\".",
22421 : : RelationGetRelationName(partIdx),
22422 : : RelationGetRelationName(parentTbl))));
22423 : :
22424 : : /* Ensure the indexes are compatible */
22425 : 246 : childInfo = BuildIndexInfo(partIdx);
22426 : 246 : parentInfo = BuildIndexInfo(parentIdx);
22427 : 246 : attmap = build_attrmap_by_name(RelationGetDescr(partTbl),
22428 : : RelationGetDescr(parentTbl),
22429 : : false);
22430 [ + + ]: 246 : if (!CompareIndexInfo(childInfo, parentInfo,
22431 : 246 : partIdx->rd_indcollation,
22432 : 246 : parentIdx->rd_indcollation,
22433 : 246 : partIdx->rd_opfamily,
22434 : 246 : parentIdx->rd_opfamily,
22435 : : attmap))
22436 [ + - ]: 32 : ereport(ERROR,
22437 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
22438 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
22439 : : RelationGetRelationName(partIdx),
22440 : : RelationGetRelationName(parentIdx)),
22441 : : errdetail("The index definitions do not match.")));
22442 : :
22443 : : /*
22444 : : * If there is a constraint in the parent, make sure there is one in
22445 : : * the child too.
22446 : : */
22447 : 214 : constraintOid = get_relation_idx_constraint_oid(RelationGetRelid(parentTbl),
22448 : : RelationGetRelid(parentIdx));
22449 : :
22450 [ + + ]: 214 : if (OidIsValid(constraintOid))
22451 : : {
22452 : 72 : cldConstrId = get_relation_idx_constraint_oid(RelationGetRelid(partTbl),
22453 : : partIdxId);
22454 [ + + ]: 72 : if (!OidIsValid(cldConstrId))
22455 [ + - ]: 4 : ereport(ERROR,
22456 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
22457 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
22458 : : RelationGetRelationName(partIdx),
22459 : : RelationGetRelationName(parentIdx)),
22460 : : errdetail("The index \"%s\" belongs to a constraint in table \"%s\" but no constraint exists for index \"%s\".",
22461 : : RelationGetRelationName(parentIdx),
22462 : : RelationGetRelationName(parentTbl),
22463 : : RelationGetRelationName(partIdx))));
22464 : : }
22465 : :
22466 : : /*
22467 : : * If it's a primary key, make sure the columns in the partition are
22468 : : * NOT NULL.
22469 : : */
22470 [ + + ]: 210 : if (parentIdx->rd_index->indisprimary)
22471 : 51 : verifyPartitionIndexNotNull(childInfo, partTbl);
22472 : :
22473 : : /* All good -- do it */
22474 : 210 : IndexSetParentIndex(partIdx, RelationGetRelid(parentIdx));
22475 [ + + ]: 210 : if (OidIsValid(constraintOid))
22476 : 68 : ConstraintSetParentConstraint(cldConstrId, constraintOid,
22477 : : RelationGetRelid(partTbl));
22478 : :
22479 : 210 : free_attrmap(attmap);
22480 : :
22481 : 210 : validatePartitionedIndex(parentIdx, parentTbl);
22482 : : }
22483 [ + + ]: 24 : else if (!parentIdx->rd_index->indisvalid)
22484 : : {
22485 : : /*
22486 : : * The index is attached, but the parent is still invalid; see if it
22487 : : * can be validated now.
22488 : : */
22489 : 12 : validatePartitionedIndex(parentIdx, parentTbl);
22490 : : }
22491 : :
22492 : 234 : relation_close(parentTbl, AccessShareLock);
22493 : : /* keep these locks till commit */
22494 : 234 : relation_close(partTbl, NoLock);
22495 : 234 : relation_close(partIdx, NoLock);
22496 : :
22497 : 234 : return address;
22498 : : }
22499 : :
22500 : : /*
22501 : : * Verify whether the given partition already contains an index attached
22502 : : * to the given partitioned index. If so, raise an error.
22503 : : */
22504 : : static void
22505 : 254 : refuseDupeIndexAttach(Relation parentIdx, Relation partIdx, Relation partitionTbl)
22506 : : {
22507 : : Oid existingIdx;
22508 : :
22509 : 254 : existingIdx = index_get_partition(partitionTbl,
22510 : : RelationGetRelid(parentIdx));
22511 [ + + ]: 254 : if (OidIsValid(existingIdx))
22512 [ + - ]: 4 : ereport(ERROR,
22513 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
22514 : : errmsg("cannot attach index \"%s\" as a partition of index \"%s\"",
22515 : : RelationGetRelationName(partIdx),
22516 : : RelationGetRelationName(parentIdx)),
22517 : : errdetail("Another index \"%s\" is already attached for partition \"%s\".",
22518 : : get_rel_name(existingIdx),
22519 : : RelationGetRelationName(partitionTbl))));
22520 : 250 : }
22521 : :
22522 : : /*
22523 : : * Verify whether the set of attached partition indexes to a parent index on
22524 : : * a partitioned table is complete. If it is, mark the parent index valid.
22525 : : *
22526 : : * This should be called each time a partition index is attached.
22527 : : */
22528 : : static void
22529 : 254 : validatePartitionedIndex(Relation partedIdx, Relation partedTbl)
22530 : : {
22531 : : Relation inheritsRel;
22532 : : SysScanDesc scan;
22533 : : ScanKeyData key;
22534 : 254 : int tuples = 0;
22535 : : HeapTuple inhTup;
22536 : 254 : bool updated = false;
22537 : :
22538 : : Assert(partedIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
22539 : :
22540 : : /*
22541 : : * Scan pg_inherits for this parent index. Count each valid index we find
22542 : : * (verifying the pg_index entry for each), and if we reach the total
22543 : : * amount we expect, we can mark this parent index as valid.
22544 : : */
22545 : 254 : inheritsRel = table_open(InheritsRelationId, AccessShareLock);
22546 : 254 : ScanKeyInit(&key, Anum_pg_inherits_inhparent,
22547 : : BTEqualStrategyNumber, F_OIDEQ,
22548 : : ObjectIdGetDatum(RelationGetRelid(partedIdx)));
22549 : 254 : scan = systable_beginscan(inheritsRel, InheritsParentIndexId, true,
22550 : : NULL, 1, &key);
22551 [ + + ]: 647 : while ((inhTup = systable_getnext(scan)) != NULL)
22552 : : {
22553 : 393 : Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(inhTup);
22554 : : HeapTuple indTup;
22555 : : Form_pg_index indexForm;
22556 : :
22557 : 393 : indTup = SearchSysCache1(INDEXRELID,
22558 : : ObjectIdGetDatum(inhForm->inhrelid));
22559 [ - + ]: 393 : if (!HeapTupleIsValid(indTup))
22560 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", inhForm->inhrelid);
22561 : 393 : indexForm = (Form_pg_index) GETSTRUCT(indTup);
22562 [ + + ]: 393 : if (indexForm->indisvalid)
22563 : 327 : tuples += 1;
22564 : 393 : ReleaseSysCache(indTup);
22565 : : }
22566 : :
22567 : : /* Done with pg_inherits */
22568 : 254 : systable_endscan(scan);
22569 : 254 : table_close(inheritsRel, AccessShareLock);
22570 : :
22571 : : /*
22572 : : * If we found as many inherited indexes as the partitioned table has
22573 : : * partitions, we're good; update pg_index to set indisvalid.
22574 : : */
22575 [ + + ]: 254 : if (tuples == RelationGetPartitionDesc(partedTbl, true)->nparts)
22576 : : {
22577 : : Relation idxRel;
22578 : : HeapTuple indTup;
22579 : : Form_pg_index indexForm;
22580 : :
22581 : 121 : idxRel = table_open(IndexRelationId, RowExclusiveLock);
22582 : 121 : indTup = SearchSysCacheCopy1(INDEXRELID,
22583 : : ObjectIdGetDatum(RelationGetRelid(partedIdx)));
22584 [ - + ]: 121 : if (!HeapTupleIsValid(indTup))
22585 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u",
22586 : : RelationGetRelid(partedIdx));
22587 : 121 : indexForm = (Form_pg_index) GETSTRUCT(indTup);
22588 : :
22589 : 121 : indexForm->indisvalid = true;
22590 : 121 : updated = true;
22591 : :
22592 : 121 : CatalogTupleUpdate(idxRel, &indTup->t_self, indTup);
22593 : :
22594 : 121 : table_close(idxRel, RowExclusiveLock);
22595 : 121 : heap_freetuple(indTup);
22596 : : }
22597 : :
22598 : : /*
22599 : : * If this index is in turn a partition of a larger index, validating it
22600 : : * might cause the parent to become valid also. Try that.
22601 : : */
22602 [ + + + + ]: 254 : if (updated && partedIdx->rd_rel->relispartition)
22603 : : {
22604 : : Oid parentIdxId,
22605 : : parentTblId;
22606 : : Relation parentIdx,
22607 : : parentTbl;
22608 : :
22609 : : /* make sure we see the validation we just did */
22610 : 32 : CommandCounterIncrement();
22611 : :
22612 : 32 : parentIdxId = get_partition_parent(RelationGetRelid(partedIdx), false);
22613 : 32 : parentTblId = get_partition_parent(RelationGetRelid(partedTbl), false);
22614 : 32 : parentIdx = relation_open(parentIdxId, AccessExclusiveLock);
22615 : 32 : parentTbl = relation_open(parentTblId, AccessExclusiveLock);
22616 : : Assert(!parentIdx->rd_index->indisvalid);
22617 : :
22618 : 32 : validatePartitionedIndex(parentIdx, parentTbl);
22619 : :
22620 : 32 : relation_close(parentIdx, AccessExclusiveLock);
22621 : 32 : relation_close(parentTbl, AccessExclusiveLock);
22622 : : }
22623 : 254 : }
22624 : :
22625 : : /*
22626 : : * When attaching an index as a partition of a partitioned index which is a
22627 : : * primary key, verify that all the columns in the partition are marked NOT
22628 : : * NULL.
22629 : : */
22630 : : static void
22631 : 51 : verifyPartitionIndexNotNull(IndexInfo *iinfo, Relation partition)
22632 : : {
22633 [ + + ]: 103 : for (int i = 0; i < iinfo->ii_NumIndexKeyAttrs; i++)
22634 : : {
22635 : 52 : Form_pg_attribute att = TupleDescAttr(RelationGetDescr(partition),
22636 : 52 : iinfo->ii_IndexAttrNumbers[i] - 1);
22637 : :
22638 [ - + ]: 52 : if (!att->attnotnull)
22639 [ # # ]: 0 : ereport(ERROR,
22640 : : errcode(ERRCODE_INVALID_TABLE_DEFINITION),
22641 : : errmsg("invalid primary key definition"),
22642 : : errdetail("Column \"%s\" of relation \"%s\" is not marked NOT NULL.",
22643 : : NameStr(att->attname),
22644 : : RelationGetRelationName(partition)));
22645 : : }
22646 : 51 : }
22647 : :
22648 : : /*
22649 : : * Return an OID list of constraints that reference the given relation
22650 : : * that are marked as having a parent constraints.
22651 : : */
22652 : : static List *
22653 : 625 : GetParentedForeignKeyRefs(Relation partition)
22654 : : {
22655 : : Relation pg_constraint;
22656 : : HeapTuple tuple;
22657 : : SysScanDesc scan;
22658 : : ScanKeyData key[2];
22659 : 625 : List *constraints = NIL;
22660 : :
22661 : : /*
22662 : : * If no indexes, or no columns are referenceable by FKs, we can avoid the
22663 : : * scan.
22664 : : */
22665 [ + + + + ]: 896 : if (RelationGetIndexList(partition) == NIL ||
22666 : 271 : bms_is_empty(RelationGetIndexAttrBitmap(partition,
22667 : : INDEX_ATTR_BITMAP_KEY)))
22668 : 458 : return NIL;
22669 : :
22670 : : /* Search for constraints referencing this table */
22671 : 167 : pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
22672 : 167 : ScanKeyInit(&key[0],
22673 : : Anum_pg_constraint_confrelid, BTEqualStrategyNumber,
22674 : : F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(partition)));
22675 : 167 : ScanKeyInit(&key[1],
22676 : : Anum_pg_constraint_contype, BTEqualStrategyNumber,
22677 : : F_CHAREQ, CharGetDatum(CONSTRAINT_FOREIGN));
22678 : :
22679 : : /* XXX This is a seqscan, as we don't have a usable index */
22680 : 167 : scan = systable_beginscan(pg_constraint, InvalidOid, true, NULL, 2, key);
22681 [ + + ]: 268 : while ((tuple = systable_getnext(scan)) != NULL)
22682 : : {
22683 : 101 : Form_pg_constraint constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
22684 : :
22685 : : /*
22686 : : * We only need to process constraints that are part of larger ones.
22687 : : */
22688 [ - + ]: 101 : if (!OidIsValid(constrForm->conparentid))
22689 : 0 : continue;
22690 : :
22691 : 101 : constraints = lappend_oid(constraints, constrForm->oid);
22692 : : }
22693 : :
22694 : 167 : systable_endscan(scan);
22695 : 167 : table_close(pg_constraint, AccessShareLock);
22696 : :
22697 : 167 : return constraints;
22698 : : }
22699 : :
22700 : : /*
22701 : : * During DETACH PARTITION, verify that any foreign keys pointing to the
22702 : : * partitioned table would not become invalid. An error is raised if any
22703 : : * referenced values exist.
22704 : : */
22705 : : static void
22706 : 333 : ATDetachCheckNoForeignKeyRefs(Relation partition)
22707 : : {
22708 : : List *constraints;
22709 : : ListCell *cell;
22710 : :
22711 : 333 : constraints = GetParentedForeignKeyRefs(partition);
22712 : :
22713 [ + + + + : 376 : foreach(cell, constraints)
+ + ]
22714 : : {
22715 : 65 : Oid constrOid = lfirst_oid(cell);
22716 : : HeapTuple tuple;
22717 : : Form_pg_constraint constrForm;
22718 : : Relation rel;
22719 : 65 : Trigger trig = {0};
22720 : :
22721 : 65 : tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
22722 [ - + ]: 65 : if (!HeapTupleIsValid(tuple))
22723 [ # # ]: 0 : elog(ERROR, "cache lookup failed for constraint %u", constrOid);
22724 : 65 : constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
22725 : :
22726 : : Assert(OidIsValid(constrForm->conparentid));
22727 : : Assert(constrForm->confrelid == RelationGetRelid(partition));
22728 : :
22729 : : /* prevent data changes into the referencing table until commit */
22730 : 65 : rel = table_open(constrForm->conrelid, ShareLock);
22731 : :
22732 : 65 : trig.tgoid = InvalidOid;
22733 : 65 : trig.tgname = NameStr(constrForm->conname);
22734 : 65 : trig.tgenabled = TRIGGER_FIRES_ON_ORIGIN;
22735 : 65 : trig.tgisinternal = true;
22736 : 65 : trig.tgconstrrelid = RelationGetRelid(partition);
22737 : 65 : trig.tgconstrindid = constrForm->conindid;
22738 : 65 : trig.tgconstraint = constrForm->oid;
22739 : 65 : trig.tgdeferrable = false;
22740 : 65 : trig.tginitdeferred = false;
22741 : : /* we needn't fill in remaining fields */
22742 : :
22743 : 65 : RI_PartitionRemove_Check(&trig, rel, partition);
22744 : :
22745 : 43 : ReleaseSysCache(tuple);
22746 : :
22747 : 43 : table_close(rel, NoLock);
22748 : : }
22749 : 311 : }
22750 : :
22751 : : /*
22752 : : * resolve column compression specification to compression method.
22753 : : */
22754 : : static char
22755 : 165443 : GetAttributeCompression(Oid atttypid, const char *compression)
22756 : : {
22757 : : char cmethod;
22758 : :
22759 [ + + + + ]: 165443 : if (compression == NULL || strcmp(compression, "default") == 0)
22760 : 165324 : return InvalidCompressionMethod;
22761 : :
22762 : : /*
22763 : : * To specify a nondefault method, the column data type must be toastable.
22764 : : * Note this says nothing about whether the column's attstorage setting
22765 : : * permits compression; we intentionally allow attstorage and
22766 : : * attcompression to be independent. But with a non-toastable type,
22767 : : * attstorage could not be set to a value that would permit compression.
22768 : : *
22769 : : * We don't actually need to enforce this, since nothing bad would happen
22770 : : * if attcompression were non-default; it would never be consulted. But
22771 : : * it seems more user-friendly to complain about a certainly-useless
22772 : : * attempt to set the property.
22773 : : */
22774 [ + + ]: 119 : if (!TypeIsToastable(atttypid))
22775 [ + - ]: 4 : ereport(ERROR,
22776 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
22777 : : errmsg("column data type %s does not support compression",
22778 : : format_type_be(atttypid))));
22779 : :
22780 : 115 : cmethod = CompressionNameToMethod(compression);
22781 [ + + ]: 115 : if (!CompressionMethodIsValid(cmethod))
22782 [ + - ]: 8 : ereport(ERROR,
22783 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
22784 : : errmsg("invalid compression method \"%s\"", compression)));
22785 : :
22786 : 107 : return cmethod;
22787 : : }
22788 : :
22789 : : /*
22790 : : * resolve column storage specification
22791 : : */
22792 : : static char
22793 : 249 : GetAttributeStorage(Oid atttypid, const char *storagemode)
22794 : : {
22795 : 249 : char cstorage = 0;
22796 : :
22797 [ + + ]: 249 : if (pg_strcasecmp(storagemode, "plain") == 0)
22798 : 38 : cstorage = TYPSTORAGE_PLAIN;
22799 [ + + ]: 211 : else if (pg_strcasecmp(storagemode, "external") == 0)
22800 : 145 : cstorage = TYPSTORAGE_EXTERNAL;
22801 [ + + ]: 66 : else if (pg_strcasecmp(storagemode, "extended") == 0)
22802 : 41 : cstorage = TYPSTORAGE_EXTENDED;
22803 [ + + ]: 25 : else if (pg_strcasecmp(storagemode, "main") == 0)
22804 : 21 : cstorage = TYPSTORAGE_MAIN;
22805 [ + - ]: 4 : else if (pg_strcasecmp(storagemode, "default") == 0)
22806 : 4 : cstorage = get_typstorage(atttypid);
22807 : : else
22808 [ # # ]: 0 : ereport(ERROR,
22809 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
22810 : : errmsg("invalid storage type \"%s\"",
22811 : : storagemode)));
22812 : :
22813 : : /*
22814 : : * safety check: do not allow toasted storage modes unless column datatype
22815 : : * is TOAST-aware.
22816 : : */
22817 [ + + + + ]: 249 : if (!(cstorage == TYPSTORAGE_PLAIN || TypeIsToastable(atttypid)))
22818 [ + - ]: 4 : ereport(ERROR,
22819 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
22820 : : errmsg("column data type %s can only have storage PLAIN",
22821 : : format_type_be(atttypid))));
22822 : :
22823 : 245 : return cstorage;
22824 : : }
|