Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * heap.c
4 : * code to create and destroy POSTGRES heap relations
5 : *
6 : * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 : * Portions Copyright (c) 1994, Regents of the University of California
8 : *
9 : *
10 : * IDENTIFICATION
11 : * src/backend/catalog/heap.c
12 : *
13 : *
14 : * INTERFACE ROUTINES
15 : * heap_create() - Create an uncataloged heap relation
16 : * heap_create_with_catalog() - Create a cataloged relation
17 : * heap_drop_with_catalog() - Removes named relation from catalogs
18 : *
19 : * NOTES
20 : * this code taken from access/heap/create.c, which contains
21 : * the old heap_create_with_catalog, amcreate, and amdestroy.
22 : * those routines will soon call these routines using the function
23 : * manager,
24 : * just like the poorly named "NewXXX" routines do. The
25 : * "New" routines are all going to die soon, once and for all!
26 : * -cim 1/13/91
27 : *
28 : *-------------------------------------------------------------------------
29 : */
30 : #include "postgres.h"
31 :
32 : #include "access/genam.h"
33 : #include "access/multixact.h"
34 : #include "access/relation.h"
35 : #include "access/table.h"
36 : #include "access/tableam.h"
37 : #include "catalog/binary_upgrade.h"
38 : #include "catalog/catalog.h"
39 : #include "catalog/heap.h"
40 : #include "catalog/index.h"
41 : #include "catalog/objectaccess.h"
42 : #include "catalog/partition.h"
43 : #include "catalog/pg_am.h"
44 : #include "catalog/pg_attrdef.h"
45 : #include "catalog/pg_collation.h"
46 : #include "catalog/pg_constraint.h"
47 : #include "catalog/pg_foreign_table.h"
48 : #include "catalog/pg_inherits.h"
49 : #include "catalog/pg_namespace.h"
50 : #include "catalog/pg_opclass.h"
51 : #include "catalog/pg_partitioned_table.h"
52 : #include "catalog/pg_statistic.h"
53 : #include "catalog/pg_subscription_rel.h"
54 : #include "catalog/pg_tablespace.h"
55 : #include "catalog/pg_type.h"
56 : #include "catalog/storage.h"
57 : #include "commands/tablecmds.h"
58 : #include "commands/typecmds.h"
59 : #include "common/int.h"
60 : #include "miscadmin.h"
61 : #include "nodes/nodeFuncs.h"
62 : #include "optimizer/optimizer.h"
63 : #include "parser/parse_coerce.h"
64 : #include "parser/parse_collate.h"
65 : #include "parser/parse_expr.h"
66 : #include "parser/parse_relation.h"
67 : #include "parser/parsetree.h"
68 : #include "partitioning/partdesc.h"
69 : #include "pgstat.h"
70 : #include "storage/lmgr.h"
71 : #include "storage/predicate.h"
72 : #include "utils/builtins.h"
73 : #include "utils/fmgroids.h"
74 : #include "utils/inval.h"
75 : #include "utils/lsyscache.h"
76 : #include "utils/syscache.h"
77 :
78 :
79 : /* Potentially set by pg_upgrade_support functions */
80 : Oid binary_upgrade_next_heap_pg_class_oid = InvalidOid;
81 : Oid binary_upgrade_next_toast_pg_class_oid = InvalidOid;
82 : RelFileNumber binary_upgrade_next_heap_pg_class_relfilenumber = InvalidRelFileNumber;
83 : RelFileNumber binary_upgrade_next_toast_pg_class_relfilenumber = InvalidRelFileNumber;
84 :
85 : static void AddNewRelationTuple(Relation pg_class_desc,
86 : Relation new_rel_desc,
87 : Oid new_rel_oid,
88 : Oid new_type_oid,
89 : Oid reloftype,
90 : Oid relowner,
91 : char relkind,
92 : TransactionId relfrozenxid,
93 : TransactionId relminmxid,
94 : Datum relacl,
95 : Datum reloptions);
96 : static ObjectAddress AddNewRelationType(const char *typeName,
97 : Oid typeNamespace,
98 : Oid new_rel_oid,
99 : char new_rel_kind,
100 : Oid ownerid,
101 : Oid new_row_type,
102 : Oid new_array_type);
103 : static void RelationRemoveInheritance(Oid relid);
104 : static Oid StoreRelCheck(Relation rel, const char *ccname, Node *expr,
105 : bool is_enforced, bool is_validated, bool is_local,
106 : int16 inhcount, bool is_no_inherit, bool is_internal);
107 : static void StoreConstraints(Relation rel, List *cooked_constraints,
108 : bool is_internal);
109 : static bool MergeWithExistingConstraint(Relation rel, const char *ccname, Node *expr,
110 : bool allow_merge, bool is_local,
111 : bool is_enforced,
112 : bool is_initially_valid,
113 : bool is_no_inherit);
114 : static void SetRelationNumChecks(Relation rel, int numchecks);
115 : static Node *cookConstraint(ParseState *pstate,
116 : Node *raw_constraint,
117 : char *relname);
118 :
119 :
120 : /* ----------------------------------------------------------------
121 : * XXX UGLY HARD CODED BADNESS FOLLOWS XXX
122 : *
123 : * these should all be moved to someplace in the lib/catalog
124 : * module, if not obliterated first.
125 : * ----------------------------------------------------------------
126 : */
127 :
128 :
129 : /*
130 : * Note:
131 : * Should the system special case these attributes in the future?
132 : * Advantage: consume much less space in the ATTRIBUTE relation.
133 : * Disadvantage: special cases will be all over the place.
134 : */
135 :
136 : /*
137 : * The initializers below do not include trailing variable length fields,
138 : * but that's OK - we're never going to reference anything beyond the
139 : * fixed-size portion of the structure anyway. Fields that can default
140 : * to zeroes are also not mentioned.
141 : */
142 :
143 : static const FormData_pg_attribute a1 = {
144 : .attname = {"ctid"},
145 : .atttypid = TIDOID,
146 : .attlen = sizeof(ItemPointerData),
147 : .attnum = SelfItemPointerAttributeNumber,
148 : .atttypmod = -1,
149 : .attbyval = false,
150 : .attalign = TYPALIGN_SHORT,
151 : .attstorage = TYPSTORAGE_PLAIN,
152 : .attnotnull = true,
153 : .attislocal = true,
154 : };
155 :
156 : static const FormData_pg_attribute a2 = {
157 : .attname = {"xmin"},
158 : .atttypid = XIDOID,
159 : .attlen = sizeof(TransactionId),
160 : .attnum = MinTransactionIdAttributeNumber,
161 : .atttypmod = -1,
162 : .attbyval = true,
163 : .attalign = TYPALIGN_INT,
164 : .attstorage = TYPSTORAGE_PLAIN,
165 : .attnotnull = true,
166 : .attislocal = true,
167 : };
168 :
169 : static const FormData_pg_attribute a3 = {
170 : .attname = {"cmin"},
171 : .atttypid = CIDOID,
172 : .attlen = sizeof(CommandId),
173 : .attnum = MinCommandIdAttributeNumber,
174 : .atttypmod = -1,
175 : .attbyval = true,
176 : .attalign = TYPALIGN_INT,
177 : .attstorage = TYPSTORAGE_PLAIN,
178 : .attnotnull = true,
179 : .attislocal = true,
180 : };
181 :
182 : static const FormData_pg_attribute a4 = {
183 : .attname = {"xmax"},
184 : .atttypid = XIDOID,
185 : .attlen = sizeof(TransactionId),
186 : .attnum = MaxTransactionIdAttributeNumber,
187 : .atttypmod = -1,
188 : .attbyval = true,
189 : .attalign = TYPALIGN_INT,
190 : .attstorage = TYPSTORAGE_PLAIN,
191 : .attnotnull = true,
192 : .attislocal = true,
193 : };
194 :
195 : static const FormData_pg_attribute a5 = {
196 : .attname = {"cmax"},
197 : .atttypid = CIDOID,
198 : .attlen = sizeof(CommandId),
199 : .attnum = MaxCommandIdAttributeNumber,
200 : .atttypmod = -1,
201 : .attbyval = true,
202 : .attalign = TYPALIGN_INT,
203 : .attstorage = TYPSTORAGE_PLAIN,
204 : .attnotnull = true,
205 : .attislocal = true,
206 : };
207 :
208 : /*
209 : * We decided to call this attribute "tableoid" rather than say
210 : * "classoid" on the basis that in the future there may be more than one
211 : * table of a particular class/type. In any case table is still the word
212 : * used in SQL.
213 : */
214 : static const FormData_pg_attribute a6 = {
215 : .attname = {"tableoid"},
216 : .atttypid = OIDOID,
217 : .attlen = sizeof(Oid),
218 : .attnum = TableOidAttributeNumber,
219 : .atttypmod = -1,
220 : .attbyval = true,
221 : .attalign = TYPALIGN_INT,
222 : .attstorage = TYPSTORAGE_PLAIN,
223 : .attnotnull = true,
224 : .attislocal = true,
225 : };
226 :
227 : static const FormData_pg_attribute *const SysAtt[] = {&a1, &a2, &a3, &a4, &a5, &a6};
228 :
229 : /*
230 : * This function returns a Form_pg_attribute pointer for a system attribute.
231 : * Note that we elog if the presented attno is invalid, which would only
232 : * happen if there's a problem upstream.
233 : */
234 : const FormData_pg_attribute *
235 27684 : SystemAttributeDefinition(AttrNumber attno)
236 : {
237 27684 : if (attno >= 0 || attno < -(int) lengthof(SysAtt))
238 0 : elog(ERROR, "invalid system attribute number %d", attno);
239 27684 : return SysAtt[-attno - 1];
240 : }
241 :
242 : /*
243 : * If the given name is a system attribute name, return a Form_pg_attribute
244 : * pointer for a prototype definition. If not, return NULL.
245 : */
246 : const FormData_pg_attribute *
247 325524 : SystemAttributeByName(const char *attname)
248 : {
249 : int j;
250 :
251 2181856 : for (j = 0; j < (int) lengthof(SysAtt); j++)
252 : {
253 1884056 : const FormData_pg_attribute *att = SysAtt[j];
254 :
255 1884056 : if (strcmp(NameStr(att->attname), attname) == 0)
256 27724 : return att;
257 : }
258 :
259 297800 : return NULL;
260 : }
261 :
262 :
263 : /* ----------------------------------------------------------------
264 : * XXX END OF UGLY HARD CODED BADNESS XXX
265 : * ---------------------------------------------------------------- */
266 :
267 :
268 : /* ----------------------------------------------------------------
269 : * heap_create - Create an uncataloged heap relation
270 : *
271 : * Note API change: the caller must now always provide the OID
272 : * to use for the relation. The relfilenumber may be (and in
273 : * the simplest cases is) left unspecified.
274 : *
275 : * create_storage indicates whether or not to create the storage.
276 : * However, even if create_storage is true, no storage will be
277 : * created if the relkind is one that doesn't have storage.
278 : *
279 : * rel->rd_rel is initialized by RelationBuildLocalRelation,
280 : * and is mostly zeroes at return.
281 : * ----------------------------------------------------------------
282 : */
283 : Relation
284 126436 : heap_create(const char *relname,
285 : Oid relnamespace,
286 : Oid reltablespace,
287 : Oid relid,
288 : RelFileNumber relfilenumber,
289 : Oid accessmtd,
290 : TupleDesc tupDesc,
291 : char relkind,
292 : char relpersistence,
293 : bool shared_relation,
294 : bool mapped_relation,
295 : bool allow_system_table_mods,
296 : TransactionId *relfrozenxid,
297 : MultiXactId *relminmxid,
298 : bool create_storage)
299 : {
300 : Relation rel;
301 :
302 : /* The caller must have provided an OID for the relation. */
303 : Assert(OidIsValid(relid));
304 :
305 : /*
306 : * Don't allow creating relations in pg_catalog directly, even though it
307 : * is allowed to move user defined relations there. Semantics with search
308 : * paths including pg_catalog are too confusing for now.
309 : *
310 : * But allow creating indexes on relations in pg_catalog even if
311 : * allow_system_table_mods = off, upper layers already guarantee it's on a
312 : * user defined relation, not a system one.
313 : */
314 198246 : if (!allow_system_table_mods &&
315 154786 : ((IsCatalogNamespace(relnamespace) && relkind != RELKIND_INDEX) ||
316 71802 : IsToastNamespace(relnamespace)) &&
317 8 : IsNormalProcessingMode())
318 8 : ereport(ERROR,
319 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
320 : errmsg("permission denied to create \"%s.%s\"",
321 : get_namespace_name(relnamespace), relname),
322 : errdetail("System catalog modifications are currently disallowed.")));
323 :
324 126428 : *relfrozenxid = InvalidTransactionId;
325 126428 : *relminmxid = InvalidMultiXactId;
326 :
327 : /*
328 : * Force reltablespace to zero if the relation kind does not support
329 : * tablespaces. This is mainly just for cleanliness' sake.
330 : */
331 126428 : if (!RELKIND_HAS_TABLESPACE(relkind))
332 20490 : reltablespace = InvalidOid;
333 :
334 : /* Don't create storage for relkinds without physical storage. */
335 126428 : if (!RELKIND_HAS_STORAGE(relkind))
336 25440 : create_storage = false;
337 : else
338 : {
339 : /*
340 : * If relfilenumber is unspecified by the caller then create storage
341 : * with oid same as relid.
342 : */
343 100988 : if (!RelFileNumberIsValid(relfilenumber))
344 98136 : relfilenumber = relid;
345 : }
346 :
347 : /*
348 : * Never allow a pg_class entry to explicitly specify the database's
349 : * default tablespace in reltablespace; force it to zero instead. This
350 : * ensures that if the database is cloned with a different default
351 : * tablespace, the pg_class entry will still match where CREATE DATABASE
352 : * will put the physically copied relation.
353 : *
354 : * Yes, this is a bit of a hack.
355 : */
356 126428 : if (reltablespace == MyDatabaseTableSpace)
357 6 : reltablespace = InvalidOid;
358 :
359 : /*
360 : * build the relcache entry.
361 : */
362 126428 : rel = RelationBuildLocalRelation(relname,
363 : relnamespace,
364 : tupDesc,
365 : relid,
366 : accessmtd,
367 : relfilenumber,
368 : reltablespace,
369 : shared_relation,
370 : mapped_relation,
371 : relpersistence,
372 : relkind);
373 :
374 : /*
375 : * Have the storage manager create the relation's disk file, if needed.
376 : *
377 : * For tables, the AM callback creates both the main and the init fork.
378 : * For others, only the main fork is created; the other forks will be
379 : * created on demand.
380 : */
381 126428 : if (create_storage)
382 : {
383 100914 : if (RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind))
384 56124 : table_relation_set_new_filelocator(rel, &rel->rd_locator,
385 : relpersistence,
386 : relfrozenxid, relminmxid);
387 44790 : else if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
388 44790 : RelationCreateStorage(rel->rd_locator, relpersistence, true);
389 : else
390 : Assert(false);
391 : }
392 :
393 : /*
394 : * If a tablespace is specified, removal of that tablespace is normally
395 : * protected by the existence of a physical file; but for relations with
396 : * no files, add a pg_shdepend entry to account for that.
397 : */
398 126428 : if (!create_storage && reltablespace != InvalidOid)
399 106 : recordDependencyOnTablespace(RelationRelationId, relid,
400 : reltablespace);
401 :
402 : /* ensure that stats are dropped if transaction aborts */
403 126428 : pgstat_create_relation(rel);
404 :
405 126428 : return rel;
406 : }
407 :
408 : /* ----------------------------------------------------------------
409 : * heap_create_with_catalog - Create a cataloged relation
410 : *
411 : * this is done in multiple steps:
412 : *
413 : * 1) CheckAttributeNamesTypes() is used to make certain the tuple
414 : * descriptor contains a valid set of attribute names and types
415 : *
416 : * 2) pg_class is opened and get_relname_relid()
417 : * performs a scan to ensure that no relation with the
418 : * same name already exists.
419 : *
420 : * 3) heap_create() is called to create the new relation on disk.
421 : *
422 : * 4) TypeCreate() is called to define a new type corresponding
423 : * to the new relation.
424 : *
425 : * 5) AddNewRelationTuple() is called to register the
426 : * relation in pg_class.
427 : *
428 : * 6) AddNewAttributeTuples() is called to register the
429 : * new relation's schema in pg_attribute.
430 : *
431 : * 7) StoreConstraints() is called - vadim 08/22/97
432 : *
433 : * 8) the relations are closed and the new relation's oid
434 : * is returned.
435 : *
436 : * ----------------------------------------------------------------
437 : */
438 :
439 : /* --------------------------------
440 : * CheckAttributeNamesTypes
441 : *
442 : * this is used to make certain the tuple descriptor contains a
443 : * valid set of attribute names and datatypes. a problem simply
444 : * generates ereport(ERROR) which aborts the current transaction.
445 : *
446 : * relkind is the relkind of the relation to be created.
447 : * flags controls which datatypes are allowed, cf CheckAttributeType.
448 : * --------------------------------
449 : */
450 : void
451 81828 : CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind,
452 : int flags)
453 : {
454 : int i;
455 : int j;
456 81828 : int natts = tupdesc->natts;
457 :
458 : /* Sanity check on column count */
459 81828 : if (natts < 0 || natts > MaxHeapAttributeNumber)
460 0 : ereport(ERROR,
461 : (errcode(ERRCODE_TOO_MANY_COLUMNS),
462 : errmsg("tables can have at most %d columns",
463 : MaxHeapAttributeNumber)));
464 :
465 : /*
466 : * first check for collision with system attribute names
467 : *
468 : * Skip this for a view or type relation, since those don't have system
469 : * attributes.
470 : */
471 81828 : if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
472 : {
473 254774 : for (i = 0; i < natts; i++)
474 : {
475 192076 : Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
476 :
477 192076 : if (SystemAttributeByName(NameStr(attr->attname)) != NULL)
478 0 : ereport(ERROR,
479 : (errcode(ERRCODE_DUPLICATE_COLUMN),
480 : errmsg("column name \"%s\" conflicts with a system column name",
481 : NameStr(attr->attname))));
482 : }
483 : }
484 :
485 : /*
486 : * next check for repeated attribute names
487 : */
488 334588 : for (i = 1; i < natts; i++)
489 : {
490 6735314 : for (j = 0; j < i; j++)
491 : {
492 6482554 : if (strcmp(NameStr(TupleDescAttr(tupdesc, j)->attname),
493 6482554 : NameStr(TupleDescAttr(tupdesc, i)->attname)) == 0)
494 0 : ereport(ERROR,
495 : (errcode(ERRCODE_DUPLICATE_COLUMN),
496 : errmsg("column name \"%s\" specified more than once",
497 : NameStr(TupleDescAttr(tupdesc, j)->attname))));
498 : }
499 : }
500 :
501 : /*
502 : * next check the attribute types
503 : */
504 413210 : for (i = 0; i < natts; i++)
505 : {
506 331396 : CheckAttributeType(NameStr(TupleDescAttr(tupdesc, i)->attname),
507 331396 : TupleDescAttr(tupdesc, i)->atttypid,
508 331396 : TupleDescAttr(tupdesc, i)->attcollation,
509 : NIL, /* assume we're creating a new rowtype */
510 : flags);
511 : }
512 81814 : }
513 :
514 : /* --------------------------------
515 : * CheckAttributeType
516 : *
517 : * Verify that the proposed datatype of an attribute is legal.
518 : * This is needed mainly because there are types (and pseudo-types)
519 : * in the catalogs that we do not support as elements of real tuples.
520 : * We also check some other properties required of a table column.
521 : *
522 : * If the attribute is being proposed for addition to an existing table or
523 : * composite type, pass a one-element list of the rowtype OID as
524 : * containing_rowtypes. When checking a to-be-created rowtype, it's
525 : * sufficient to pass NIL, because there could not be any recursive reference
526 : * to a not-yet-existing rowtype.
527 : *
528 : * flags is a bitmask controlling which datatypes we allow. For the most
529 : * part, pseudo-types are disallowed as attribute types, but there are some
530 : * exceptions: ANYARRAYOID, RECORDOID, and RECORDARRAYOID can be allowed
531 : * in some cases. (This works because values of those type classes are
532 : * self-identifying to some extent. However, RECORDOID and RECORDARRAYOID
533 : * are reliably identifiable only within a session, since the identity info
534 : * may use a typmod that is only locally assigned. The caller is expected
535 : * to know whether these cases are safe.)
536 : *
537 : * flags can also control the phrasing of the error messages. If
538 : * CHKATYPE_IS_PARTKEY is specified, "attname" should be a partition key
539 : * column number as text, not a real column name.
540 : * --------------------------------
541 : */
542 : void
543 410892 : CheckAttributeType(const char *attname,
544 : Oid atttypid, Oid attcollation,
545 : List *containing_rowtypes,
546 : int flags)
547 : {
548 410892 : char att_typtype = get_typtype(atttypid);
549 : Oid att_typelem;
550 :
551 : /* since this function recurses, it could be driven to stack overflow */
552 410892 : check_stack_depth();
553 :
554 410892 : if (att_typtype == TYPTYPE_PSEUDO)
555 : {
556 : /*
557 : * We disallow pseudo-type columns, with the exception of ANYARRAY,
558 : * RECORD, and RECORD[] when the caller says that those are OK.
559 : *
560 : * We don't need to worry about recursive containment for RECORD and
561 : * RECORD[] because (a) no named composite type should be allowed to
562 : * contain those, and (b) two "anonymous" record types couldn't be
563 : * considered to be the same type, so infinite recursion isn't
564 : * possible.
565 : */
566 1674 : if (!((atttypid == ANYARRAYOID && (flags & CHKATYPE_ANYARRAY)) ||
567 24 : (atttypid == RECORDOID && (flags & CHKATYPE_ANYRECORD)) ||
568 6 : (atttypid == RECORDARRAYOID && (flags & CHKATYPE_ANYRECORD))))
569 : {
570 32 : if (flags & CHKATYPE_IS_PARTKEY)
571 12 : ereport(ERROR,
572 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
573 : /* translator: first %s is an integer not a name */
574 : errmsg("partition key column %s has pseudo-type %s",
575 : attname, format_type_be(atttypid))));
576 : else
577 20 : ereport(ERROR,
578 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
579 : errmsg("column \"%s\" has pseudo-type %s",
580 : attname, format_type_be(atttypid))));
581 : }
582 : }
583 409230 : else if (att_typtype == TYPTYPE_DOMAIN)
584 : {
585 : /*
586 : * If it's a domain, recurse to check its base type.
587 : */
588 59382 : CheckAttributeType(attname, getBaseType(atttypid), attcollation,
589 : containing_rowtypes,
590 : flags);
591 : }
592 349848 : else if (att_typtype == TYPTYPE_COMPOSITE)
593 : {
594 : /*
595 : * For a composite type, recurse into its attributes.
596 : */
597 : Relation relation;
598 : TupleDesc tupdesc;
599 : int i;
600 :
601 : /*
602 : * Check for self-containment. Eventually we might be able to allow
603 : * this (just return without complaint, if so) but it's not clear how
604 : * many other places would require anti-recursion defenses before it
605 : * would be safe to allow tables to contain their own rowtype.
606 : */
607 710 : if (list_member_oid(containing_rowtypes, atttypid))
608 36 : ereport(ERROR,
609 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
610 : errmsg("composite type %s cannot be made a member of itself",
611 : format_type_be(atttypid))));
612 :
613 674 : containing_rowtypes = lappend_oid(containing_rowtypes, atttypid);
614 :
615 674 : relation = relation_open(get_typ_typrelid(atttypid), AccessShareLock);
616 :
617 674 : tupdesc = RelationGetDescr(relation);
618 :
619 4864 : for (i = 0; i < tupdesc->natts; i++)
620 : {
621 4202 : Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
622 :
623 4202 : if (attr->attisdropped)
624 2 : continue;
625 4200 : CheckAttributeType(NameStr(attr->attname),
626 : attr->atttypid, attr->attcollation,
627 : containing_rowtypes,
628 : flags & ~CHKATYPE_IS_PARTKEY);
629 : }
630 :
631 662 : relation_close(relation, AccessShareLock);
632 :
633 662 : containing_rowtypes = list_delete_last(containing_rowtypes);
634 : }
635 349138 : else if (att_typtype == TYPTYPE_RANGE)
636 : {
637 : /*
638 : * If it's a range, recurse to check its subtype.
639 : */
640 1884 : CheckAttributeType(attname, get_range_subtype(atttypid),
641 : get_range_collation(atttypid),
642 : containing_rowtypes,
643 : flags);
644 : }
645 347254 : else if (OidIsValid((att_typelem = get_element_type(atttypid))))
646 : {
647 : /*
648 : * Must recurse into array types, too, in case they are composite.
649 : */
650 9274 : CheckAttributeType(attname, att_typelem, attcollation,
651 : containing_rowtypes,
652 : flags);
653 : }
654 :
655 : /*
656 : * This might not be strictly invalid per SQL standard, but it is pretty
657 : * useless, and it cannot be dumped, so we must disallow it.
658 : */
659 410788 : if (!OidIsValid(attcollation) && type_is_collatable(atttypid))
660 : {
661 0 : if (flags & CHKATYPE_IS_PARTKEY)
662 0 : ereport(ERROR,
663 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
664 : /* translator: first %s is an integer not a name */
665 : errmsg("no collation was derived for partition key column %s with collatable type %s",
666 : attname, format_type_be(atttypid)),
667 : errhint("Use the COLLATE clause to set the collation explicitly.")));
668 : else
669 0 : ereport(ERROR,
670 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
671 : errmsg("no collation was derived for column \"%s\" with collatable type %s",
672 : attname, format_type_be(atttypid)),
673 : errhint("Use the COLLATE clause to set the collation explicitly.")));
674 : }
675 410788 : }
676 :
677 : /*
678 : * InsertPgAttributeTuples
679 : * Construct and insert a set of tuples in pg_attribute.
680 : *
681 : * Caller has already opened and locked pg_attribute. tupdesc contains the
682 : * attributes to insert. tupdesc_extra supplies the values for certain
683 : * variable-length/nullable pg_attribute fields and must contain the same
684 : * number of elements as tupdesc or be NULL. The other variable-length fields
685 : * of pg_attribute are always initialized to null values.
686 : *
687 : * indstate is the index state for CatalogTupleInsertWithInfo. It can be
688 : * passed as NULL, in which case we'll fetch the necessary info. (Don't do
689 : * this when inserting multiple attributes, because it's a tad more
690 : * expensive.)
691 : *
692 : * new_rel_oid is the relation OID assigned to the attributes inserted.
693 : * If set to InvalidOid, the relation OID from tupdesc is used instead.
694 : */
695 : void
696 191194 : InsertPgAttributeTuples(Relation pg_attribute_rel,
697 : TupleDesc tupdesc,
698 : Oid new_rel_oid,
699 : const FormExtraData_pg_attribute tupdesc_extra[],
700 : CatalogIndexState indstate)
701 : {
702 : TupleTableSlot **slot;
703 : TupleDesc td;
704 : int nslots;
705 191194 : int natts = 0;
706 191194 : int slotCount = 0;
707 191194 : bool close_index = false;
708 :
709 191194 : td = RelationGetDescr(pg_attribute_rel);
710 :
711 : /* Initialize the number of slots to use */
712 191194 : nslots = Min(tupdesc->natts,
713 : (MAX_CATALOG_MULTI_INSERT_BYTES / sizeof(FormData_pg_attribute)));
714 191194 : slot = palloc(sizeof(TupleTableSlot *) * nslots);
715 969210 : for (int i = 0; i < nslots; i++)
716 778016 : slot[i] = MakeSingleTupleTableSlot(td, &TTSOpsHeapTuple);
717 :
718 972786 : while (natts < tupdesc->natts)
719 : {
720 781592 : Form_pg_attribute attrs = TupleDescAttr(tupdesc, natts);
721 781592 : const FormExtraData_pg_attribute *attrs_extra = tupdesc_extra ? &tupdesc_extra[natts] : NULL;
722 :
723 781592 : ExecClearTuple(slot[slotCount]);
724 :
725 781592 : memset(slot[slotCount]->tts_isnull, false,
726 781592 : slot[slotCount]->tts_tupleDescriptor->natts * sizeof(bool));
727 :
728 781592 : if (new_rel_oid != InvalidOid)
729 708016 : slot[slotCount]->tts_values[Anum_pg_attribute_attrelid - 1] = ObjectIdGetDatum(new_rel_oid);
730 : else
731 73576 : slot[slotCount]->tts_values[Anum_pg_attribute_attrelid - 1] = ObjectIdGetDatum(attrs->attrelid);
732 :
733 781592 : slot[slotCount]->tts_values[Anum_pg_attribute_attname - 1] = NameGetDatum(&attrs->attname);
734 781592 : slot[slotCount]->tts_values[Anum_pg_attribute_atttypid - 1] = ObjectIdGetDatum(attrs->atttypid);
735 781592 : slot[slotCount]->tts_values[Anum_pg_attribute_attlen - 1] = Int16GetDatum(attrs->attlen);
736 781592 : slot[slotCount]->tts_values[Anum_pg_attribute_attnum - 1] = Int16GetDatum(attrs->attnum);
737 781592 : slot[slotCount]->tts_values[Anum_pg_attribute_atttypmod - 1] = Int32GetDatum(attrs->atttypmod);
738 781592 : slot[slotCount]->tts_values[Anum_pg_attribute_attndims - 1] = Int16GetDatum(attrs->attndims);
739 781592 : slot[slotCount]->tts_values[Anum_pg_attribute_attbyval - 1] = BoolGetDatum(attrs->attbyval);
740 781592 : slot[slotCount]->tts_values[Anum_pg_attribute_attalign - 1] = CharGetDatum(attrs->attalign);
741 781592 : slot[slotCount]->tts_values[Anum_pg_attribute_attstorage - 1] = CharGetDatum(attrs->attstorage);
742 781592 : slot[slotCount]->tts_values[Anum_pg_attribute_attcompression - 1] = CharGetDatum(attrs->attcompression);
743 781592 : slot[slotCount]->tts_values[Anum_pg_attribute_attnotnull - 1] = BoolGetDatum(attrs->attnotnull);
744 781592 : slot[slotCount]->tts_values[Anum_pg_attribute_atthasdef - 1] = BoolGetDatum(attrs->atthasdef);
745 781592 : slot[slotCount]->tts_values[Anum_pg_attribute_atthasmissing - 1] = BoolGetDatum(attrs->atthasmissing);
746 781592 : slot[slotCount]->tts_values[Anum_pg_attribute_attidentity - 1] = CharGetDatum(attrs->attidentity);
747 781592 : slot[slotCount]->tts_values[Anum_pg_attribute_attgenerated - 1] = CharGetDatum(attrs->attgenerated);
748 781592 : slot[slotCount]->tts_values[Anum_pg_attribute_attisdropped - 1] = BoolGetDatum(attrs->attisdropped);
749 781592 : slot[slotCount]->tts_values[Anum_pg_attribute_attislocal - 1] = BoolGetDatum(attrs->attislocal);
750 781592 : slot[slotCount]->tts_values[Anum_pg_attribute_attinhcount - 1] = Int16GetDatum(attrs->attinhcount);
751 781592 : slot[slotCount]->tts_values[Anum_pg_attribute_attcollation - 1] = ObjectIdGetDatum(attrs->attcollation);
752 781592 : if (attrs_extra)
753 : {
754 40140 : slot[slotCount]->tts_values[Anum_pg_attribute_attstattarget - 1] = attrs_extra->attstattarget.value;
755 40140 : slot[slotCount]->tts_isnull[Anum_pg_attribute_attstattarget - 1] = attrs_extra->attstattarget.isnull;
756 :
757 40140 : slot[slotCount]->tts_values[Anum_pg_attribute_attoptions - 1] = attrs_extra->attoptions.value;
758 40140 : slot[slotCount]->tts_isnull[Anum_pg_attribute_attoptions - 1] = attrs_extra->attoptions.isnull;
759 : }
760 : else
761 : {
762 741452 : slot[slotCount]->tts_isnull[Anum_pg_attribute_attstattarget - 1] = true;
763 741452 : slot[slotCount]->tts_isnull[Anum_pg_attribute_attoptions - 1] = true;
764 : }
765 :
766 : /*
767 : * The remaining fields are not set for new columns.
768 : */
769 781592 : slot[slotCount]->tts_isnull[Anum_pg_attribute_attacl - 1] = true;
770 781592 : slot[slotCount]->tts_isnull[Anum_pg_attribute_attfdwoptions - 1] = true;
771 781592 : slot[slotCount]->tts_isnull[Anum_pg_attribute_attmissingval - 1] = true;
772 :
773 781592 : ExecStoreVirtualTuple(slot[slotCount]);
774 781592 : slotCount++;
775 :
776 : /*
777 : * If slots are full or the end of processing has been reached, insert
778 : * a batch of tuples.
779 : */
780 781592 : if (slotCount == nslots || natts == tupdesc->natts - 1)
781 : {
782 : /* fetch index info only when we know we need it */
783 188016 : if (!indstate)
784 : {
785 2446 : indstate = CatalogOpenIndexes(pg_attribute_rel);
786 2446 : close_index = true;
787 : }
788 :
789 : /* insert the new tuples and update the indexes */
790 188016 : CatalogTuplesMultiInsertWithInfo(pg_attribute_rel, slot, slotCount,
791 : indstate);
792 188016 : slotCount = 0;
793 : }
794 :
795 781592 : natts++;
796 : }
797 :
798 191194 : if (close_index)
799 2446 : CatalogCloseIndexes(indstate);
800 969210 : for (int i = 0; i < nslots; i++)
801 778016 : ExecDropSingleTupleTableSlot(slot[i]);
802 191194 : pfree(slot);
803 191194 : }
804 :
805 : /* --------------------------------
806 : * AddNewAttributeTuples
807 : *
808 : * this registers the new relation's schema by adding
809 : * tuples to pg_attribute.
810 : * --------------------------------
811 : */
812 : static void
813 81020 : AddNewAttributeTuples(Oid new_rel_oid,
814 : TupleDesc tupdesc,
815 : char relkind)
816 : {
817 : Relation rel;
818 : CatalogIndexState indstate;
819 81020 : int natts = tupdesc->natts;
820 : ObjectAddress myself,
821 : referenced;
822 :
823 : /*
824 : * open pg_attribute and its indexes.
825 : */
826 81020 : rel = table_open(AttributeRelationId, RowExclusiveLock);
827 :
828 81020 : indstate = CatalogOpenIndexes(rel);
829 :
830 81020 : InsertPgAttributeTuples(rel, tupdesc, new_rel_oid, NULL, indstate);
831 :
832 : /* add dependencies on their datatypes and collations */
833 410510 : for (int i = 0; i < natts; i++)
834 : {
835 329490 : Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
836 :
837 : /* Add dependency info */
838 329490 : ObjectAddressSubSet(myself, RelationRelationId, new_rel_oid, i + 1);
839 329490 : ObjectAddressSet(referenced, TypeRelationId, attr->atttypid);
840 329490 : recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
841 :
842 : /* The default collation is pinned, so don't bother recording it */
843 329490 : if (OidIsValid(attr->attcollation) &&
844 100926 : attr->attcollation != DEFAULT_COLLATION_OID)
845 : {
846 73284 : ObjectAddressSet(referenced, CollationRelationId,
847 : attr->attcollation);
848 73284 : recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
849 : }
850 : }
851 :
852 : /*
853 : * Next we add the system attributes. Skip all for a view or type
854 : * relation. We don't bother with making datatype dependencies here,
855 : * since presumably all these types are pinned.
856 : */
857 81020 : if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE)
858 : {
859 : TupleDesc td;
860 :
861 62680 : td = CreateTupleDesc(lengthof(SysAtt), (FormData_pg_attribute **) &SysAtt);
862 :
863 62680 : InsertPgAttributeTuples(rel, td, new_rel_oid, NULL, indstate);
864 62680 : FreeTupleDesc(td);
865 : }
866 :
867 : /*
868 : * clean up
869 : */
870 81020 : CatalogCloseIndexes(indstate);
871 :
872 81020 : table_close(rel, RowExclusiveLock);
873 81020 : }
874 :
875 : /* --------------------------------
876 : * InsertPgClassTuple
877 : *
878 : * Construct and insert a new tuple in pg_class.
879 : *
880 : * Caller has already opened and locked pg_class.
881 : * Tuple data is taken from new_rel_desc->rd_rel, except for the
882 : * variable-width fields which are not present in a cached reldesc.
883 : * relacl and reloptions are passed in Datum form (to avoid having
884 : * to reference the data types in heap.h). Pass (Datum) 0 to set them
885 : * to NULL.
886 : * --------------------------------
887 : */
888 : void
889 126068 : InsertPgClassTuple(Relation pg_class_desc,
890 : Relation new_rel_desc,
891 : Oid new_rel_oid,
892 : Datum relacl,
893 : Datum reloptions)
894 : {
895 126068 : Form_pg_class rd_rel = new_rel_desc->rd_rel;
896 : Datum values[Natts_pg_class];
897 : bool nulls[Natts_pg_class];
898 : HeapTuple tup;
899 :
900 : /* This is a tad tedious, but way cleaner than what we used to do... */
901 126068 : memset(values, 0, sizeof(values));
902 126068 : memset(nulls, false, sizeof(nulls));
903 :
904 126068 : values[Anum_pg_class_oid - 1] = ObjectIdGetDatum(new_rel_oid);
905 126068 : values[Anum_pg_class_relname - 1] = NameGetDatum(&rd_rel->relname);
906 126068 : values[Anum_pg_class_relnamespace - 1] = ObjectIdGetDatum(rd_rel->relnamespace);
907 126068 : values[Anum_pg_class_reltype - 1] = ObjectIdGetDatum(rd_rel->reltype);
908 126068 : values[Anum_pg_class_reloftype - 1] = ObjectIdGetDatum(rd_rel->reloftype);
909 126068 : values[Anum_pg_class_relowner - 1] = ObjectIdGetDatum(rd_rel->relowner);
910 126068 : values[Anum_pg_class_relam - 1] = ObjectIdGetDatum(rd_rel->relam);
911 126068 : values[Anum_pg_class_relfilenode - 1] = ObjectIdGetDatum(rd_rel->relfilenode);
912 126068 : values[Anum_pg_class_reltablespace - 1] = ObjectIdGetDatum(rd_rel->reltablespace);
913 126068 : values[Anum_pg_class_relpages - 1] = Int32GetDatum(rd_rel->relpages);
914 126068 : values[Anum_pg_class_reltuples - 1] = Float4GetDatum(rd_rel->reltuples);
915 126068 : values[Anum_pg_class_relallvisible - 1] = Int32GetDatum(rd_rel->relallvisible);
916 126068 : values[Anum_pg_class_reltoastrelid - 1] = ObjectIdGetDatum(rd_rel->reltoastrelid);
917 126068 : values[Anum_pg_class_relhasindex - 1] = BoolGetDatum(rd_rel->relhasindex);
918 126068 : values[Anum_pg_class_relisshared - 1] = BoolGetDatum(rd_rel->relisshared);
919 126068 : values[Anum_pg_class_relpersistence - 1] = CharGetDatum(rd_rel->relpersistence);
920 126068 : values[Anum_pg_class_relkind - 1] = CharGetDatum(rd_rel->relkind);
921 126068 : values[Anum_pg_class_relnatts - 1] = Int16GetDatum(rd_rel->relnatts);
922 126068 : values[Anum_pg_class_relchecks - 1] = Int16GetDatum(rd_rel->relchecks);
923 126068 : values[Anum_pg_class_relhasrules - 1] = BoolGetDatum(rd_rel->relhasrules);
924 126068 : values[Anum_pg_class_relhastriggers - 1] = BoolGetDatum(rd_rel->relhastriggers);
925 126068 : values[Anum_pg_class_relrowsecurity - 1] = BoolGetDatum(rd_rel->relrowsecurity);
926 126068 : values[Anum_pg_class_relforcerowsecurity - 1] = BoolGetDatum(rd_rel->relforcerowsecurity);
927 126068 : values[Anum_pg_class_relhassubclass - 1] = BoolGetDatum(rd_rel->relhassubclass);
928 126068 : values[Anum_pg_class_relispopulated - 1] = BoolGetDatum(rd_rel->relispopulated);
929 126068 : values[Anum_pg_class_relreplident - 1] = CharGetDatum(rd_rel->relreplident);
930 126068 : values[Anum_pg_class_relispartition - 1] = BoolGetDatum(rd_rel->relispartition);
931 126068 : values[Anum_pg_class_relrewrite - 1] = ObjectIdGetDatum(rd_rel->relrewrite);
932 126068 : values[Anum_pg_class_relfrozenxid - 1] = TransactionIdGetDatum(rd_rel->relfrozenxid);
933 126068 : values[Anum_pg_class_relminmxid - 1] = MultiXactIdGetDatum(rd_rel->relminmxid);
934 126068 : if (relacl != (Datum) 0)
935 132 : values[Anum_pg_class_relacl - 1] = relacl;
936 : else
937 125936 : nulls[Anum_pg_class_relacl - 1] = true;
938 126068 : if (reloptions != (Datum) 0)
939 1472 : values[Anum_pg_class_reloptions - 1] = reloptions;
940 : else
941 124596 : nulls[Anum_pg_class_reloptions - 1] = true;
942 :
943 : /* relpartbound is set by updating this tuple, if necessary */
944 126068 : nulls[Anum_pg_class_relpartbound - 1] = true;
945 :
946 126068 : tup = heap_form_tuple(RelationGetDescr(pg_class_desc), values, nulls);
947 :
948 : /* finally insert the new tuple, update the indexes, and clean up */
949 126068 : CatalogTupleInsert(pg_class_desc, tup);
950 :
951 126068 : heap_freetuple(tup);
952 126068 : }
953 :
954 : /* --------------------------------
955 : * AddNewRelationTuple
956 : *
957 : * this registers the new relation in the catalogs by
958 : * adding a tuple to pg_class.
959 : * --------------------------------
960 : */
961 : static void
962 81020 : AddNewRelationTuple(Relation pg_class_desc,
963 : Relation new_rel_desc,
964 : Oid new_rel_oid,
965 : Oid new_type_oid,
966 : Oid reloftype,
967 : Oid relowner,
968 : char relkind,
969 : TransactionId relfrozenxid,
970 : TransactionId relminmxid,
971 : Datum relacl,
972 : Datum reloptions)
973 : {
974 : Form_pg_class new_rel_reltup;
975 :
976 : /*
977 : * first we update some of the information in our uncataloged relation's
978 : * relation descriptor.
979 : */
980 81020 : new_rel_reltup = new_rel_desc->rd_rel;
981 :
982 : /* The relation is empty */
983 81020 : new_rel_reltup->relpages = 0;
984 81020 : new_rel_reltup->reltuples = -1;
985 81020 : new_rel_reltup->relallvisible = 0;
986 :
987 : /* Sequences always have a known size */
988 81020 : if (relkind == RELKIND_SEQUENCE)
989 : {
990 1716 : new_rel_reltup->relpages = 1;
991 1716 : new_rel_reltup->reltuples = 1;
992 : }
993 :
994 81020 : new_rel_reltup->relfrozenxid = relfrozenxid;
995 81020 : new_rel_reltup->relminmxid = relminmxid;
996 81020 : new_rel_reltup->relowner = relowner;
997 81020 : new_rel_reltup->reltype = new_type_oid;
998 81020 : new_rel_reltup->reloftype = reloftype;
999 :
1000 : /* relispartition is always set by updating this tuple later */
1001 81020 : new_rel_reltup->relispartition = false;
1002 :
1003 : /* fill rd_att's type ID with something sane even if reltype is zero */
1004 81020 : new_rel_desc->rd_att->tdtypeid = new_type_oid ? new_type_oid : RECORDOID;
1005 81020 : new_rel_desc->rd_att->tdtypmod = -1;
1006 :
1007 : /* Now build and insert the tuple */
1008 81020 : InsertPgClassTuple(pg_class_desc, new_rel_desc, new_rel_oid,
1009 : relacl, reloptions);
1010 81020 : }
1011 :
1012 :
1013 : /* --------------------------------
1014 : * AddNewRelationType -
1015 : *
1016 : * define a composite type corresponding to the new relation
1017 : * --------------------------------
1018 : */
1019 : static ObjectAddress
1020 62586 : AddNewRelationType(const char *typeName,
1021 : Oid typeNamespace,
1022 : Oid new_rel_oid,
1023 : char new_rel_kind,
1024 : Oid ownerid,
1025 : Oid new_row_type,
1026 : Oid new_array_type)
1027 : {
1028 : return
1029 62586 : TypeCreate(new_row_type, /* optional predetermined OID */
1030 : typeName, /* type name */
1031 : typeNamespace, /* type namespace */
1032 : new_rel_oid, /* relation oid */
1033 : new_rel_kind, /* relation kind */
1034 : ownerid, /* owner's ID */
1035 : -1, /* internal size (varlena) */
1036 : TYPTYPE_COMPOSITE, /* type-type (composite) */
1037 : TYPCATEGORY_COMPOSITE, /* type-category (ditto) */
1038 : false, /* composite types are never preferred */
1039 : DEFAULT_TYPDELIM, /* default array delimiter */
1040 : F_RECORD_IN, /* input procedure */
1041 : F_RECORD_OUT, /* output procedure */
1042 : F_RECORD_RECV, /* receive procedure */
1043 : F_RECORD_SEND, /* send procedure */
1044 : InvalidOid, /* typmodin procedure - none */
1045 : InvalidOid, /* typmodout procedure - none */
1046 : InvalidOid, /* analyze procedure - default */
1047 : InvalidOid, /* subscript procedure - none */
1048 : InvalidOid, /* array element type - irrelevant */
1049 : false, /* this is not an array type */
1050 : new_array_type, /* array type if any */
1051 : InvalidOid, /* domain base type - irrelevant */
1052 : NULL, /* default value - none */
1053 : NULL, /* default binary representation */
1054 : false, /* passed by reference */
1055 : TYPALIGN_DOUBLE, /* alignment - must be the largest! */
1056 : TYPSTORAGE_EXTENDED, /* fully TOASTable */
1057 : -1, /* typmod */
1058 : 0, /* array dimensions for typBaseType */
1059 : false, /* Type NOT NULL */
1060 : InvalidOid); /* rowtypes never have a collation */
1061 : }
1062 :
1063 : /* --------------------------------
1064 : * heap_create_with_catalog
1065 : *
1066 : * creates a new cataloged relation. see comments above.
1067 : *
1068 : * Arguments:
1069 : * relname: name to give to new rel
1070 : * relnamespace: OID of namespace it goes in
1071 : * reltablespace: OID of tablespace it goes in
1072 : * relid: OID to assign to new rel, or InvalidOid to select a new OID
1073 : * reltypeid: OID to assign to rel's rowtype, or InvalidOid to select one
1074 : * reloftypeid: if a typed table, OID of underlying type; else InvalidOid
1075 : * ownerid: OID of new rel's owner
1076 : * accessmtd: OID of new rel's access method
1077 : * tupdesc: tuple descriptor (source of column definitions)
1078 : * cooked_constraints: list of precooked check constraints and defaults
1079 : * relkind: relkind for new rel
1080 : * relpersistence: rel's persistence status (permanent, temp, or unlogged)
1081 : * shared_relation: true if it's to be a shared relation
1082 : * mapped_relation: true if the relation will use the relfilenumber map
1083 : * oncommit: ON COMMIT marking (only relevant if it's a temp table)
1084 : * reloptions: reloptions in Datum form, or (Datum) 0 if none
1085 : * use_user_acl: true if should look for user-defined default permissions;
1086 : * if false, relacl is always set NULL
1087 : * allow_system_table_mods: true to allow creation in system namespaces
1088 : * is_internal: is this a system-generated catalog?
1089 : *
1090 : * Output parameters:
1091 : * typaddress: if not null, gets the object address of the new pg_type entry
1092 : * (this must be null if the relkind is one that doesn't get a pg_type entry)
1093 : *
1094 : * Returns the OID of the new relation
1095 : * --------------------------------
1096 : */
1097 : Oid
1098 81044 : heap_create_with_catalog(const char *relname,
1099 : Oid relnamespace,
1100 : Oid reltablespace,
1101 : Oid relid,
1102 : Oid reltypeid,
1103 : Oid reloftypeid,
1104 : Oid ownerid,
1105 : Oid accessmtd,
1106 : TupleDesc tupdesc,
1107 : List *cooked_constraints,
1108 : char relkind,
1109 : char relpersistence,
1110 : bool shared_relation,
1111 : bool mapped_relation,
1112 : OnCommitAction oncommit,
1113 : Datum reloptions,
1114 : bool use_user_acl,
1115 : bool allow_system_table_mods,
1116 : bool is_internal,
1117 : Oid relrewrite,
1118 : ObjectAddress *typaddress)
1119 : {
1120 : Relation pg_class_desc;
1121 : Relation new_rel_desc;
1122 : Acl *relacl;
1123 : Oid existing_relid;
1124 : Oid old_type_oid;
1125 : Oid new_type_oid;
1126 :
1127 : /* By default set to InvalidOid unless overridden by binary-upgrade */
1128 81044 : RelFileNumber relfilenumber = InvalidRelFileNumber;
1129 : TransactionId relfrozenxid;
1130 : MultiXactId relminmxid;
1131 :
1132 81044 : pg_class_desc = table_open(RelationRelationId, RowExclusiveLock);
1133 :
1134 : /*
1135 : * sanity checks
1136 : */
1137 : Assert(IsNormalProcessingMode() || IsBootstrapProcessingMode());
1138 :
1139 : /*
1140 : * Validate proposed tupdesc for the desired relkind. If
1141 : * allow_system_table_mods is on, allow ANYARRAY to be used; this is a
1142 : * hack to allow creating pg_statistic and cloning it during VACUUM FULL.
1143 : */
1144 81044 : CheckAttributeNamesTypes(tupdesc, relkind,
1145 : allow_system_table_mods ? CHKATYPE_ANYARRAY : 0);
1146 :
1147 : /*
1148 : * This would fail later on anyway, if the relation already exists. But
1149 : * by catching it here we can emit a nicer error message.
1150 : */
1151 81030 : existing_relid = get_relname_relid(relname, relnamespace);
1152 81030 : if (existing_relid != InvalidOid)
1153 2 : ereport(ERROR,
1154 : (errcode(ERRCODE_DUPLICATE_TABLE),
1155 : errmsg("relation \"%s\" already exists", relname)));
1156 :
1157 : /*
1158 : * Since we are going to create a rowtype as well, also check for
1159 : * collision with an existing type name. If there is one and it's an
1160 : * autogenerated array, we can rename it out of the way; otherwise we can
1161 : * at least give a good error message.
1162 : */
1163 81028 : old_type_oid = GetSysCacheOid2(TYPENAMENSP, Anum_pg_type_oid,
1164 : CStringGetDatum(relname),
1165 : ObjectIdGetDatum(relnamespace));
1166 81028 : if (OidIsValid(old_type_oid))
1167 : {
1168 2 : if (!moveArrayTypeName(old_type_oid, relname, relnamespace))
1169 0 : ereport(ERROR,
1170 : (errcode(ERRCODE_DUPLICATE_OBJECT),
1171 : errmsg("type \"%s\" already exists", relname),
1172 : errhint("A relation has an associated type of the same name, "
1173 : "so you must use a name that doesn't conflict "
1174 : "with any existing type.")));
1175 : }
1176 :
1177 : /*
1178 : * Shared relations must be in pg_global (last-ditch check)
1179 : */
1180 81028 : if (shared_relation && reltablespace != GLOBALTABLESPACE_OID)
1181 0 : elog(ERROR, "shared relations must be placed in pg_global tablespace");
1182 :
1183 : /*
1184 : * Allocate an OID for the relation, unless we were told what to use.
1185 : *
1186 : * The OID will be the relfilenumber as well, so make sure it doesn't
1187 : * collide with either pg_class OIDs or existing physical files.
1188 : */
1189 81028 : if (!OidIsValid(relid))
1190 : {
1191 : /* Use binary-upgrade override for pg_class.oid and relfilenumber */
1192 72388 : if (IsBinaryUpgrade)
1193 : {
1194 : /*
1195 : * Indexes are not supported here; they use
1196 : * binary_upgrade_next_index_pg_class_oid.
1197 : */
1198 : Assert(relkind != RELKIND_INDEX);
1199 : Assert(relkind != RELKIND_PARTITIONED_INDEX);
1200 :
1201 2080 : if (relkind == RELKIND_TOASTVALUE)
1202 : {
1203 : /* There might be no TOAST table, so we have to test for it. */
1204 528 : if (OidIsValid(binary_upgrade_next_toast_pg_class_oid))
1205 : {
1206 528 : relid = binary_upgrade_next_toast_pg_class_oid;
1207 528 : binary_upgrade_next_toast_pg_class_oid = InvalidOid;
1208 :
1209 528 : if (!RelFileNumberIsValid(binary_upgrade_next_toast_pg_class_relfilenumber))
1210 0 : ereport(ERROR,
1211 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1212 : errmsg("toast relfilenumber value not set when in binary upgrade mode")));
1213 :
1214 528 : relfilenumber = binary_upgrade_next_toast_pg_class_relfilenumber;
1215 528 : binary_upgrade_next_toast_pg_class_relfilenumber = InvalidRelFileNumber;
1216 : }
1217 : }
1218 : else
1219 : {
1220 1552 : if (!OidIsValid(binary_upgrade_next_heap_pg_class_oid))
1221 0 : ereport(ERROR,
1222 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1223 : errmsg("pg_class heap OID value not set when in binary upgrade mode")));
1224 :
1225 1552 : relid = binary_upgrade_next_heap_pg_class_oid;
1226 1552 : binary_upgrade_next_heap_pg_class_oid = InvalidOid;
1227 :
1228 1552 : if (RELKIND_HAS_STORAGE(relkind))
1229 : {
1230 1258 : if (!RelFileNumberIsValid(binary_upgrade_next_heap_pg_class_relfilenumber))
1231 0 : ereport(ERROR,
1232 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1233 : errmsg("relfilenumber value not set when in binary upgrade mode")));
1234 :
1235 1258 : relfilenumber = binary_upgrade_next_heap_pg_class_relfilenumber;
1236 1258 : binary_upgrade_next_heap_pg_class_relfilenumber = InvalidRelFileNumber;
1237 : }
1238 : }
1239 : }
1240 :
1241 72388 : if (!OidIsValid(relid))
1242 70308 : relid = GetNewRelFileNumber(reltablespace, pg_class_desc,
1243 : relpersistence);
1244 : }
1245 :
1246 : /*
1247 : * Other sessions' catalog scans can't find this until we commit. Hence,
1248 : * it doesn't hurt to hold AccessExclusiveLock. Do it here so callers
1249 : * can't accidentally vary in their lock mode or acquisition timing.
1250 : */
1251 81028 : LockRelationOid(relid, AccessExclusiveLock);
1252 :
1253 : /*
1254 : * Determine the relation's initial permissions.
1255 : */
1256 81028 : if (use_user_acl)
1257 : {
1258 56874 : switch (relkind)
1259 : {
1260 51684 : case RELKIND_RELATION:
1261 : case RELKIND_VIEW:
1262 : case RELKIND_MATVIEW:
1263 : case RELKIND_FOREIGN_TABLE:
1264 : case RELKIND_PARTITIONED_TABLE:
1265 51684 : relacl = get_user_default_acl(OBJECT_TABLE, ownerid,
1266 : relnamespace);
1267 51684 : break;
1268 1716 : case RELKIND_SEQUENCE:
1269 1716 : relacl = get_user_default_acl(OBJECT_SEQUENCE, ownerid,
1270 : relnamespace);
1271 1716 : break;
1272 3474 : default:
1273 3474 : relacl = NULL;
1274 3474 : break;
1275 : }
1276 : }
1277 : else
1278 24154 : relacl = NULL;
1279 :
1280 : /*
1281 : * Create the relcache entry (mostly dummy at this point) and the physical
1282 : * disk file. (If we fail further down, it's the smgr's responsibility to
1283 : * remove the disk file again.)
1284 : *
1285 : * NB: Note that passing create_storage = true is correct even for binary
1286 : * upgrade. The storage we create here will be replaced later, but we
1287 : * need to have something on disk in the meanwhile.
1288 : */
1289 81028 : new_rel_desc = heap_create(relname,
1290 : relnamespace,
1291 : reltablespace,
1292 : relid,
1293 : relfilenumber,
1294 : accessmtd,
1295 : tupdesc,
1296 : relkind,
1297 : relpersistence,
1298 : shared_relation,
1299 : mapped_relation,
1300 : allow_system_table_mods,
1301 : &relfrozenxid,
1302 : &relminmxid,
1303 : true);
1304 :
1305 : Assert(relid == RelationGetRelid(new_rel_desc));
1306 :
1307 81020 : new_rel_desc->rd_rel->relrewrite = relrewrite;
1308 :
1309 : /*
1310 : * Decide whether to create a pg_type entry for the relation's rowtype.
1311 : * These types are made except where the use of a relation as such is an
1312 : * implementation detail: toast tables, sequences and indexes.
1313 : */
1314 143606 : if (!(relkind == RELKIND_SEQUENCE ||
1315 62586 : relkind == RELKIND_TOASTVALUE ||
1316 : relkind == RELKIND_INDEX ||
1317 : relkind == RELKIND_PARTITIONED_INDEX))
1318 62586 : {
1319 : Oid new_array_oid;
1320 : ObjectAddress new_type_addr;
1321 : char *relarrayname;
1322 :
1323 : /*
1324 : * We'll make an array over the composite type, too. For largely
1325 : * historical reasons, the array type's OID is assigned first.
1326 : */
1327 62586 : new_array_oid = AssignTypeArrayOid();
1328 :
1329 : /*
1330 : * Make the pg_type entry for the composite type. The OID of the
1331 : * composite type can be preselected by the caller, but if reltypeid
1332 : * is InvalidOid, we'll generate a new OID for it.
1333 : *
1334 : * NOTE: we could get a unique-index failure here, in case someone
1335 : * else is creating the same type name in parallel but hadn't
1336 : * committed yet when we checked for a duplicate name above.
1337 : */
1338 62586 : new_type_addr = AddNewRelationType(relname,
1339 : relnamespace,
1340 : relid,
1341 : relkind,
1342 : ownerid,
1343 : reltypeid,
1344 : new_array_oid);
1345 62586 : new_type_oid = new_type_addr.objectId;
1346 62586 : if (typaddress)
1347 3474 : *typaddress = new_type_addr;
1348 :
1349 : /* Now create the array type. */
1350 62586 : relarrayname = makeArrayTypeName(relname, relnamespace);
1351 :
1352 62586 : TypeCreate(new_array_oid, /* force the type's OID to this */
1353 : relarrayname, /* Array type name */
1354 : relnamespace, /* Same namespace as parent */
1355 : InvalidOid, /* Not composite, no relationOid */
1356 : 0, /* relkind, also N/A here */
1357 : ownerid, /* owner's ID */
1358 : -1, /* Internal size (varlena) */
1359 : TYPTYPE_BASE, /* Not composite - typelem is */
1360 : TYPCATEGORY_ARRAY, /* type-category (array) */
1361 : false, /* array types are never preferred */
1362 : DEFAULT_TYPDELIM, /* default array delimiter */
1363 : F_ARRAY_IN, /* array input proc */
1364 : F_ARRAY_OUT, /* array output proc */
1365 : F_ARRAY_RECV, /* array recv (bin) proc */
1366 : F_ARRAY_SEND, /* array send (bin) proc */
1367 : InvalidOid, /* typmodin procedure - none */
1368 : InvalidOid, /* typmodout procedure - none */
1369 : F_ARRAY_TYPANALYZE, /* array analyze procedure */
1370 : F_ARRAY_SUBSCRIPT_HANDLER, /* array subscript procedure */
1371 : new_type_oid, /* array element type - the rowtype */
1372 : true, /* yes, this is an array type */
1373 : InvalidOid, /* this has no array type */
1374 : InvalidOid, /* domain base type - irrelevant */
1375 : NULL, /* default value - none */
1376 : NULL, /* default binary representation */
1377 : false, /* passed by reference */
1378 : TYPALIGN_DOUBLE, /* alignment - must be the largest! */
1379 : TYPSTORAGE_EXTENDED, /* fully TOASTable */
1380 : -1, /* typmod */
1381 : 0, /* array dimensions for typBaseType */
1382 : false, /* Type NOT NULL */
1383 : InvalidOid); /* rowtypes never have a collation */
1384 :
1385 62586 : pfree(relarrayname);
1386 : }
1387 : else
1388 : {
1389 : /* Caller should not be expecting a type to be created. */
1390 : Assert(reltypeid == InvalidOid);
1391 : Assert(typaddress == NULL);
1392 :
1393 18434 : new_type_oid = InvalidOid;
1394 : }
1395 :
1396 : /*
1397 : * now create an entry in pg_class for the relation.
1398 : *
1399 : * NOTE: we could get a unique-index failure here, in case someone else is
1400 : * creating the same relation name in parallel but hadn't committed yet
1401 : * when we checked for a duplicate name above.
1402 : */
1403 81020 : AddNewRelationTuple(pg_class_desc,
1404 : new_rel_desc,
1405 : relid,
1406 : new_type_oid,
1407 : reloftypeid,
1408 : ownerid,
1409 : relkind,
1410 : relfrozenxid,
1411 : relminmxid,
1412 : PointerGetDatum(relacl),
1413 : reloptions);
1414 :
1415 : /*
1416 : * now add tuples to pg_attribute for the attributes in our new relation.
1417 : */
1418 81020 : AddNewAttributeTuples(relid, new_rel_desc->rd_att, relkind);
1419 :
1420 : /*
1421 : * Make a dependency link to force the relation to be deleted if its
1422 : * namespace is. Also make a dependency link to its owner, as well as
1423 : * dependencies for any roles mentioned in the default ACL.
1424 : *
1425 : * For composite types, these dependencies are tracked for the pg_type
1426 : * entry, so we needn't record them here. Likewise, TOAST tables don't
1427 : * need a namespace dependency (they live in a pinned namespace) nor an
1428 : * owner dependency (they depend indirectly through the parent table), nor
1429 : * should they have any ACL entries. The same applies for extension
1430 : * dependencies.
1431 : *
1432 : * Also, skip this in bootstrap mode, since we don't make dependencies
1433 : * while bootstrapping.
1434 : */
1435 81020 : if (relkind != RELKIND_COMPOSITE_TYPE &&
1436 60828 : relkind != RELKIND_TOASTVALUE &&
1437 60828 : !IsBootstrapProcessingMode())
1438 : {
1439 : ObjectAddress myself,
1440 : referenced;
1441 : ObjectAddresses *addrs;
1442 :
1443 55428 : ObjectAddressSet(myself, RelationRelationId, relid);
1444 :
1445 55428 : recordDependencyOnOwner(RelationRelationId, relid, ownerid);
1446 :
1447 55428 : recordDependencyOnNewAcl(RelationRelationId, relid, 0, ownerid, relacl);
1448 :
1449 55428 : recordDependencyOnCurrentExtension(&myself, false);
1450 :
1451 55428 : addrs = new_object_addresses();
1452 :
1453 55428 : ObjectAddressSet(referenced, NamespaceRelationId, relnamespace);
1454 55428 : add_exact_object_address(&referenced, addrs);
1455 :
1456 55428 : if (reloftypeid)
1457 : {
1458 68 : ObjectAddressSet(referenced, TypeRelationId, reloftypeid);
1459 68 : add_exact_object_address(&referenced, addrs);
1460 : }
1461 :
1462 : /*
1463 : * Make a dependency link to force the relation to be deleted if its
1464 : * access method is.
1465 : *
1466 : * No need to add an explicit dependency for the toast table, as the
1467 : * main table depends on it. Partitioned tables may not have an
1468 : * access method set.
1469 : */
1470 55428 : if ((RELKIND_HAS_TABLE_AM(relkind) && relkind != RELKIND_TOASTVALUE) ||
1471 4766 : (relkind == RELKIND_PARTITIONED_TABLE && OidIsValid(accessmtd)))
1472 : {
1473 33664 : ObjectAddressSet(referenced, AccessMethodRelationId, accessmtd);
1474 33664 : add_exact_object_address(&referenced, addrs);
1475 : }
1476 :
1477 55428 : record_object_address_dependencies(&myself, addrs, DEPENDENCY_NORMAL);
1478 55428 : free_object_addresses(addrs);
1479 : }
1480 :
1481 : /* Post creation hook for new relation */
1482 81020 : InvokeObjectPostCreateHookArg(RelationRelationId, relid, 0, is_internal);
1483 :
1484 : /*
1485 : * Store any supplied CHECK constraints and defaults.
1486 : *
1487 : * NB: this may do a CommandCounterIncrement and rebuild the relcache
1488 : * entry, so the relation must be valid and self-consistent at this point.
1489 : * In particular, there are not yet constraints and defaults anywhere.
1490 : */
1491 81020 : StoreConstraints(new_rel_desc, cooked_constraints, is_internal);
1492 :
1493 : /*
1494 : * If there's a special on-commit action, remember it
1495 : */
1496 81020 : if (oncommit != ONCOMMIT_NOOP)
1497 166 : register_on_commit_action(relid, oncommit);
1498 :
1499 : /*
1500 : * ok, the relation has been cataloged, so close our relations and return
1501 : * the OID of the newly created relation.
1502 : */
1503 81020 : table_close(new_rel_desc, NoLock); /* do not unlock till end of xact */
1504 81020 : table_close(pg_class_desc, RowExclusiveLock);
1505 :
1506 81020 : return relid;
1507 : }
1508 :
1509 : /*
1510 : * RelationRemoveInheritance
1511 : *
1512 : * Formerly, this routine checked for child relations and aborted the
1513 : * deletion if any were found. Now we rely on the dependency mechanism
1514 : * to check for or delete child relations. By the time we get here,
1515 : * there are no children and we need only remove any pg_inherits rows
1516 : * linking this relation to its parent(s).
1517 : */
1518 : static void
1519 45446 : RelationRemoveInheritance(Oid relid)
1520 : {
1521 : Relation catalogRelation;
1522 : SysScanDesc scan;
1523 : ScanKeyData key;
1524 : HeapTuple tuple;
1525 :
1526 45446 : catalogRelation = table_open(InheritsRelationId, RowExclusiveLock);
1527 :
1528 45446 : ScanKeyInit(&key,
1529 : Anum_pg_inherits_inhrelid,
1530 : BTEqualStrategyNumber, F_OIDEQ,
1531 : ObjectIdGetDatum(relid));
1532 :
1533 45446 : scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId, true,
1534 : NULL, 1, &key);
1535 :
1536 53996 : while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1537 8550 : CatalogTupleDelete(catalogRelation, &tuple->t_self);
1538 :
1539 45446 : systable_endscan(scan);
1540 45446 : table_close(catalogRelation, RowExclusiveLock);
1541 45446 : }
1542 :
1543 : /*
1544 : * DeleteRelationTuple
1545 : *
1546 : * Remove pg_class row for the given relid.
1547 : *
1548 : * Note: this is shared by relation deletion and index deletion. It's
1549 : * not intended for use anyplace else.
1550 : */
1551 : void
1552 68496 : DeleteRelationTuple(Oid relid)
1553 : {
1554 : Relation pg_class_desc;
1555 : HeapTuple tup;
1556 :
1557 : /* Grab an appropriate lock on the pg_class relation */
1558 68496 : pg_class_desc = table_open(RelationRelationId, RowExclusiveLock);
1559 :
1560 68496 : tup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1561 68496 : if (!HeapTupleIsValid(tup))
1562 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
1563 :
1564 : /* delete the relation tuple from pg_class, and finish up */
1565 68496 : CatalogTupleDelete(pg_class_desc, &tup->t_self);
1566 :
1567 68496 : ReleaseSysCache(tup);
1568 :
1569 68496 : table_close(pg_class_desc, RowExclusiveLock);
1570 68496 : }
1571 :
1572 : /*
1573 : * DeleteAttributeTuples
1574 : *
1575 : * Remove pg_attribute rows for the given relid.
1576 : *
1577 : * Note: this is shared by relation deletion and index deletion. It's
1578 : * not intended for use anyplace else.
1579 : */
1580 : void
1581 68496 : DeleteAttributeTuples(Oid relid)
1582 : {
1583 : Relation attrel;
1584 : SysScanDesc scan;
1585 : ScanKeyData key[1];
1586 : HeapTuple atttup;
1587 :
1588 : /* Grab an appropriate lock on the pg_attribute relation */
1589 68496 : attrel = table_open(AttributeRelationId, RowExclusiveLock);
1590 :
1591 : /* Use the index to scan only attributes of the target relation */
1592 68496 : ScanKeyInit(&key[0],
1593 : Anum_pg_attribute_attrelid,
1594 : BTEqualStrategyNumber, F_OIDEQ,
1595 : ObjectIdGetDatum(relid));
1596 :
1597 68496 : scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
1598 : NULL, 1, key);
1599 :
1600 : /* Delete all the matching tuples */
1601 450048 : while ((atttup = systable_getnext(scan)) != NULL)
1602 381552 : CatalogTupleDelete(attrel, &atttup->t_self);
1603 :
1604 : /* Clean up after the scan */
1605 68496 : systable_endscan(scan);
1606 68496 : table_close(attrel, RowExclusiveLock);
1607 68496 : }
1608 :
1609 : /*
1610 : * DeleteSystemAttributeTuples
1611 : *
1612 : * Remove pg_attribute rows for system columns of the given relid.
1613 : *
1614 : * Note: this is only used when converting a table to a view. Views don't
1615 : * have system columns, so we should remove them from pg_attribute.
1616 : */
1617 : void
1618 0 : DeleteSystemAttributeTuples(Oid relid)
1619 : {
1620 : Relation attrel;
1621 : SysScanDesc scan;
1622 : ScanKeyData key[2];
1623 : HeapTuple atttup;
1624 :
1625 : /* Grab an appropriate lock on the pg_attribute relation */
1626 0 : attrel = table_open(AttributeRelationId, RowExclusiveLock);
1627 :
1628 : /* Use the index to scan only system attributes of the target relation */
1629 0 : ScanKeyInit(&key[0],
1630 : Anum_pg_attribute_attrelid,
1631 : BTEqualStrategyNumber, F_OIDEQ,
1632 : ObjectIdGetDatum(relid));
1633 0 : ScanKeyInit(&key[1],
1634 : Anum_pg_attribute_attnum,
1635 : BTLessEqualStrategyNumber, F_INT2LE,
1636 : Int16GetDatum(0));
1637 :
1638 0 : scan = systable_beginscan(attrel, AttributeRelidNumIndexId, true,
1639 : NULL, 2, key);
1640 :
1641 : /* Delete all the matching tuples */
1642 0 : while ((atttup = systable_getnext(scan)) != NULL)
1643 0 : CatalogTupleDelete(attrel, &atttup->t_self);
1644 :
1645 : /* Clean up after the scan */
1646 0 : systable_endscan(scan);
1647 0 : table_close(attrel, RowExclusiveLock);
1648 0 : }
1649 :
1650 : /*
1651 : * RemoveAttributeById
1652 : *
1653 : * This is the guts of ALTER TABLE DROP COLUMN: actually mark the attribute
1654 : * deleted in pg_attribute. We also remove pg_statistic entries for it.
1655 : * (Everything else needed, such as getting rid of any pg_attrdef entry,
1656 : * is handled by dependency.c.)
1657 : */
1658 : void
1659 1996 : RemoveAttributeById(Oid relid, AttrNumber attnum)
1660 : {
1661 : Relation rel;
1662 : Relation attr_rel;
1663 : HeapTuple tuple;
1664 : Form_pg_attribute attStruct;
1665 : char newattname[NAMEDATALEN];
1666 1996 : Datum valuesAtt[Natts_pg_attribute] = {0};
1667 1996 : bool nullsAtt[Natts_pg_attribute] = {0};
1668 1996 : bool replacesAtt[Natts_pg_attribute] = {0};
1669 :
1670 : /*
1671 : * Grab an exclusive lock on the target table, which we will NOT release
1672 : * until end of transaction. (In the simple case where we are directly
1673 : * dropping this column, ATExecDropColumn already did this ... but when
1674 : * cascading from a drop of some other object, we may not have any lock.)
1675 : */
1676 1996 : rel = relation_open(relid, AccessExclusiveLock);
1677 :
1678 1996 : attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
1679 :
1680 1996 : tuple = SearchSysCacheCopy2(ATTNUM,
1681 : ObjectIdGetDatum(relid),
1682 : Int16GetDatum(attnum));
1683 1996 : if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1684 0 : elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1685 : attnum, relid);
1686 1996 : attStruct = (Form_pg_attribute) GETSTRUCT(tuple);
1687 :
1688 : /* Mark the attribute as dropped */
1689 1996 : attStruct->attisdropped = true;
1690 :
1691 : /*
1692 : * Set the type OID to invalid. A dropped attribute's type link cannot be
1693 : * relied on (once the attribute is dropped, the type might be too).
1694 : * Fortunately we do not need the type row --- the only really essential
1695 : * information is the type's typlen and typalign, which are preserved in
1696 : * the attribute's attlen and attalign. We set atttypid to zero here as a
1697 : * means of catching code that incorrectly expects it to be valid.
1698 : */
1699 1996 : attStruct->atttypid = InvalidOid;
1700 :
1701 : /* Remove any not-null constraint the column may have */
1702 1996 : attStruct->attnotnull = false;
1703 :
1704 : /* Unset this so no one tries to look up the generation expression */
1705 1996 : attStruct->attgenerated = '\0';
1706 :
1707 : /*
1708 : * Change the column name to something that isn't likely to conflict
1709 : */
1710 1996 : snprintf(newattname, sizeof(newattname),
1711 : "........pg.dropped.%d........", attnum);
1712 1996 : namestrcpy(&(attStruct->attname), newattname);
1713 :
1714 : /* Clear the missing value */
1715 1996 : attStruct->atthasmissing = false;
1716 1996 : nullsAtt[Anum_pg_attribute_attmissingval - 1] = true;
1717 1996 : replacesAtt[Anum_pg_attribute_attmissingval - 1] = true;
1718 :
1719 : /*
1720 : * Clear the other nullable fields. This saves some space in pg_attribute
1721 : * and removes no longer useful information.
1722 : */
1723 1996 : nullsAtt[Anum_pg_attribute_attstattarget - 1] = true;
1724 1996 : replacesAtt[Anum_pg_attribute_attstattarget - 1] = true;
1725 1996 : nullsAtt[Anum_pg_attribute_attacl - 1] = true;
1726 1996 : replacesAtt[Anum_pg_attribute_attacl - 1] = true;
1727 1996 : nullsAtt[Anum_pg_attribute_attoptions - 1] = true;
1728 1996 : replacesAtt[Anum_pg_attribute_attoptions - 1] = true;
1729 1996 : nullsAtt[Anum_pg_attribute_attfdwoptions - 1] = true;
1730 1996 : replacesAtt[Anum_pg_attribute_attfdwoptions - 1] = true;
1731 :
1732 1996 : tuple = heap_modify_tuple(tuple, RelationGetDescr(attr_rel),
1733 : valuesAtt, nullsAtt, replacesAtt);
1734 :
1735 1996 : CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
1736 :
1737 : /*
1738 : * Because updating the pg_attribute row will trigger a relcache flush for
1739 : * the target relation, we need not do anything else to notify other
1740 : * backends of the change.
1741 : */
1742 :
1743 1996 : table_close(attr_rel, RowExclusiveLock);
1744 :
1745 1996 : RemoveStatistics(relid, attnum);
1746 :
1747 1996 : relation_close(rel, NoLock);
1748 1996 : }
1749 :
1750 : /*
1751 : * heap_drop_with_catalog - removes specified relation from catalogs
1752 : *
1753 : * Note that this routine is not responsible for dropping objects that are
1754 : * linked to the pg_class entry via dependencies (for example, indexes and
1755 : * constraints). Those are deleted by the dependency-tracing logic in
1756 : * dependency.c before control gets here. In general, therefore, this routine
1757 : * should never be called directly; go through performDeletion() instead.
1758 : */
1759 : void
1760 45446 : heap_drop_with_catalog(Oid relid)
1761 : {
1762 : Relation rel;
1763 : HeapTuple tuple;
1764 45446 : Oid parentOid = InvalidOid,
1765 45446 : defaultPartOid = InvalidOid;
1766 :
1767 : /*
1768 : * To drop a partition safely, we must grab exclusive lock on its parent,
1769 : * because another backend might be about to execute a query on the parent
1770 : * table. If it relies on previously cached partition descriptor, then it
1771 : * could attempt to access the just-dropped relation as its partition. We
1772 : * must therefore take a table lock strong enough to prevent all queries
1773 : * on the table from proceeding until we commit and send out a
1774 : * shared-cache-inval notice that will make them update their partition
1775 : * descriptors.
1776 : */
1777 45446 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1778 45446 : if (!HeapTupleIsValid(tuple))
1779 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
1780 45446 : if (((Form_pg_class) GETSTRUCT(tuple))->relispartition)
1781 : {
1782 : /*
1783 : * We have to lock the parent if the partition is being detached,
1784 : * because it's possible that some query still has a partition
1785 : * descriptor that includes this partition.
1786 : */
1787 6842 : parentOid = get_partition_parent(relid, true);
1788 6842 : LockRelationOid(parentOid, AccessExclusiveLock);
1789 :
1790 : /*
1791 : * If this is not the default partition, dropping it will change the
1792 : * default partition's partition constraint, so we must lock it.
1793 : */
1794 6842 : defaultPartOid = get_default_partition_oid(parentOid);
1795 6842 : if (OidIsValid(defaultPartOid) && relid != defaultPartOid)
1796 374 : LockRelationOid(defaultPartOid, AccessExclusiveLock);
1797 : }
1798 :
1799 45446 : ReleaseSysCache(tuple);
1800 :
1801 : /*
1802 : * Open and lock the relation.
1803 : */
1804 45446 : rel = relation_open(relid, AccessExclusiveLock);
1805 :
1806 : /*
1807 : * There can no longer be anyone *else* touching the relation, but we
1808 : * might still have open queries or cursors, or pending trigger events, in
1809 : * our own session.
1810 : */
1811 45446 : CheckTableNotInUse(rel, "DROP TABLE");
1812 :
1813 : /*
1814 : * This effectively deletes all rows in the table, and may be done in a
1815 : * serializable transaction. In that case we must record a rw-conflict in
1816 : * to this transaction from each transaction holding a predicate lock on
1817 : * the table.
1818 : */
1819 45446 : CheckTableForSerializableConflictIn(rel);
1820 :
1821 : /*
1822 : * Delete pg_foreign_table tuple first.
1823 : */
1824 45446 : if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1825 : {
1826 : Relation ftrel;
1827 : HeapTuple fttuple;
1828 :
1829 232 : ftrel = table_open(ForeignTableRelationId, RowExclusiveLock);
1830 :
1831 232 : fttuple = SearchSysCache1(FOREIGNTABLEREL, ObjectIdGetDatum(relid));
1832 232 : if (!HeapTupleIsValid(fttuple))
1833 0 : elog(ERROR, "cache lookup failed for foreign table %u", relid);
1834 :
1835 232 : CatalogTupleDelete(ftrel, &fttuple->t_self);
1836 :
1837 232 : ReleaseSysCache(fttuple);
1838 232 : table_close(ftrel, RowExclusiveLock);
1839 : }
1840 :
1841 : /*
1842 : * If a partitioned table, delete the pg_partitioned_table tuple.
1843 : */
1844 45446 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1845 3730 : RemovePartitionKeyByRelId(relid);
1846 :
1847 : /*
1848 : * If the relation being dropped is the default partition itself,
1849 : * invalidate its entry in pg_partitioned_table.
1850 : */
1851 45446 : if (relid == defaultPartOid)
1852 410 : update_default_partition_oid(parentOid, InvalidOid);
1853 :
1854 : /*
1855 : * Schedule unlinking of the relation's physical files at commit.
1856 : */
1857 45446 : if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
1858 36186 : RelationDropStorage(rel);
1859 :
1860 : /* ensure that stats are dropped if transaction commits */
1861 45446 : pgstat_drop_relation(rel);
1862 :
1863 : /*
1864 : * Close relcache entry, but *keep* AccessExclusiveLock on the relation
1865 : * until transaction commit. This ensures no one else will try to do
1866 : * something with the doomed relation.
1867 : */
1868 45446 : relation_close(rel, NoLock);
1869 :
1870 : /*
1871 : * Remove any associated relation synchronization states.
1872 : */
1873 45446 : RemoveSubscriptionRel(InvalidOid, relid);
1874 :
1875 : /*
1876 : * Forget any ON COMMIT action for the rel
1877 : */
1878 45446 : remove_on_commit_action(relid);
1879 :
1880 : /*
1881 : * Flush the relation from the relcache. We want to do this before
1882 : * starting to remove catalog entries, just to be certain that no relcache
1883 : * entry rebuild will happen partway through. (That should not really
1884 : * matter, since we don't do CommandCounterIncrement here, but let's be
1885 : * safe.)
1886 : */
1887 45446 : RelationForgetRelation(relid);
1888 :
1889 : /*
1890 : * remove inheritance information
1891 : */
1892 45446 : RelationRemoveInheritance(relid);
1893 :
1894 : /*
1895 : * delete statistics
1896 : */
1897 45446 : RemoveStatistics(relid, 0);
1898 :
1899 : /*
1900 : * delete attribute tuples
1901 : */
1902 45446 : DeleteAttributeTuples(relid);
1903 :
1904 : /*
1905 : * delete relation tuple
1906 : */
1907 45446 : DeleteRelationTuple(relid);
1908 :
1909 45446 : if (OidIsValid(parentOid))
1910 : {
1911 : /*
1912 : * If this is not the default partition, the partition constraint of
1913 : * the default partition has changed to include the portion of the key
1914 : * space previously covered by the dropped partition.
1915 : */
1916 6842 : if (OidIsValid(defaultPartOid) && relid != defaultPartOid)
1917 374 : CacheInvalidateRelcacheByRelid(defaultPartOid);
1918 :
1919 : /*
1920 : * Invalidate the parent's relcache so that the partition is no longer
1921 : * included in its partition descriptor.
1922 : */
1923 6842 : CacheInvalidateRelcacheByRelid(parentOid);
1924 : /* keep the lock */
1925 : }
1926 45446 : }
1927 :
1928 :
1929 : /*
1930 : * RelationClearMissing
1931 : *
1932 : * Set atthasmissing and attmissingval to false/null for all attributes
1933 : * where they are currently set. This can be safely and usefully done if
1934 : * the table is rewritten (e.g. by VACUUM FULL or CLUSTER) where we know there
1935 : * are no rows left with less than a full complement of attributes.
1936 : *
1937 : * The caller must have an AccessExclusive lock on the relation.
1938 : */
1939 : void
1940 2440 : RelationClearMissing(Relation rel)
1941 : {
1942 : Relation attr_rel;
1943 2440 : Oid relid = RelationGetRelid(rel);
1944 2440 : int natts = RelationGetNumberOfAttributes(rel);
1945 : int attnum;
1946 : Datum repl_val[Natts_pg_attribute];
1947 : bool repl_null[Natts_pg_attribute];
1948 : bool repl_repl[Natts_pg_attribute];
1949 : Form_pg_attribute attrtuple;
1950 : HeapTuple tuple,
1951 : newtuple;
1952 :
1953 2440 : memset(repl_val, 0, sizeof(repl_val));
1954 2440 : memset(repl_null, false, sizeof(repl_null));
1955 2440 : memset(repl_repl, false, sizeof(repl_repl));
1956 :
1957 2440 : repl_val[Anum_pg_attribute_atthasmissing - 1] = BoolGetDatum(false);
1958 2440 : repl_null[Anum_pg_attribute_attmissingval - 1] = true;
1959 :
1960 2440 : repl_repl[Anum_pg_attribute_atthasmissing - 1] = true;
1961 2440 : repl_repl[Anum_pg_attribute_attmissingval - 1] = true;
1962 :
1963 :
1964 : /* Get a lock on pg_attribute */
1965 2440 : attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
1966 :
1967 : /* process each non-system attribute, including any dropped columns */
1968 8892 : for (attnum = 1; attnum <= natts; attnum++)
1969 : {
1970 6452 : tuple = SearchSysCache2(ATTNUM,
1971 : ObjectIdGetDatum(relid),
1972 : Int16GetDatum(attnum));
1973 6452 : if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
1974 0 : elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1975 : attnum, relid);
1976 :
1977 6452 : attrtuple = (Form_pg_attribute) GETSTRUCT(tuple);
1978 :
1979 : /* ignore any where atthasmissing is not true */
1980 6452 : if (attrtuple->atthasmissing)
1981 : {
1982 96 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(attr_rel),
1983 : repl_val, repl_null, repl_repl);
1984 :
1985 96 : CatalogTupleUpdate(attr_rel, &newtuple->t_self, newtuple);
1986 :
1987 96 : heap_freetuple(newtuple);
1988 : }
1989 :
1990 6452 : ReleaseSysCache(tuple);
1991 : }
1992 :
1993 : /*
1994 : * Our update of the pg_attribute rows will force a relcache rebuild, so
1995 : * there's nothing else to do here.
1996 : */
1997 2440 : table_close(attr_rel, RowExclusiveLock);
1998 2440 : }
1999 :
2000 : /*
2001 : * SetAttrMissing
2002 : *
2003 : * Set the missing value of a single attribute. This should only be used by
2004 : * binary upgrade. Takes an AccessExclusive lock on the relation owning the
2005 : * attribute.
2006 : */
2007 : void
2008 4 : SetAttrMissing(Oid relid, char *attname, char *value)
2009 : {
2010 4 : Datum valuesAtt[Natts_pg_attribute] = {0};
2011 4 : bool nullsAtt[Natts_pg_attribute] = {0};
2012 4 : bool replacesAtt[Natts_pg_attribute] = {0};
2013 : Datum missingval;
2014 : Form_pg_attribute attStruct;
2015 : Relation attrrel,
2016 : tablerel;
2017 : HeapTuple atttup,
2018 : newtup;
2019 :
2020 : /* lock the table the attribute belongs to */
2021 4 : tablerel = table_open(relid, AccessExclusiveLock);
2022 :
2023 : /* Don't do anything unless it's a plain table */
2024 4 : if (tablerel->rd_rel->relkind != RELKIND_RELATION)
2025 : {
2026 0 : table_close(tablerel, AccessExclusiveLock);
2027 0 : return;
2028 : }
2029 :
2030 : /* Lock the attribute row and get the data */
2031 4 : attrrel = table_open(AttributeRelationId, RowExclusiveLock);
2032 4 : atttup = SearchSysCacheAttName(relid, attname);
2033 4 : if (!HeapTupleIsValid(atttup))
2034 0 : elog(ERROR, "cache lookup failed for attribute %s of relation %u",
2035 : attname, relid);
2036 4 : attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
2037 :
2038 : /* get an array value from the value string */
2039 4 : missingval = OidFunctionCall3(F_ARRAY_IN,
2040 : CStringGetDatum(value),
2041 : ObjectIdGetDatum(attStruct->atttypid),
2042 : Int32GetDatum(attStruct->atttypmod));
2043 :
2044 : /* update the tuple - set atthasmissing and attmissingval */
2045 4 : valuesAtt[Anum_pg_attribute_atthasmissing - 1] = BoolGetDatum(true);
2046 4 : replacesAtt[Anum_pg_attribute_atthasmissing - 1] = true;
2047 4 : valuesAtt[Anum_pg_attribute_attmissingval - 1] = missingval;
2048 4 : replacesAtt[Anum_pg_attribute_attmissingval - 1] = true;
2049 :
2050 4 : newtup = heap_modify_tuple(atttup, RelationGetDescr(attrrel),
2051 : valuesAtt, nullsAtt, replacesAtt);
2052 4 : CatalogTupleUpdate(attrrel, &newtup->t_self, newtup);
2053 :
2054 : /* clean up */
2055 4 : ReleaseSysCache(atttup);
2056 4 : table_close(attrrel, RowExclusiveLock);
2057 4 : table_close(tablerel, AccessExclusiveLock);
2058 : }
2059 :
2060 : /*
2061 : * Store a check-constraint expression for the given relation.
2062 : *
2063 : * Caller is responsible for updating the count of constraints
2064 : * in the pg_class entry for the relation.
2065 : *
2066 : * The OID of the new constraint is returned.
2067 : */
2068 : static Oid
2069 2532 : StoreRelCheck(Relation rel, const char *ccname, Node *expr,
2070 : bool is_enforced, bool is_validated, bool is_local,
2071 : int16 inhcount, bool is_no_inherit, bool is_internal)
2072 : {
2073 : char *ccbin;
2074 : List *varList;
2075 : int keycount;
2076 : int16 *attNos;
2077 : Oid constrOid;
2078 :
2079 : /*
2080 : * Flatten expression to string form for storage.
2081 : */
2082 2532 : ccbin = nodeToString(expr);
2083 :
2084 : /*
2085 : * Find columns of rel that are used in expr
2086 : *
2087 : * NB: pull_var_clause is okay here only because we don't allow subselects
2088 : * in check constraints; it would fail to examine the contents of
2089 : * subselects.
2090 : */
2091 2532 : varList = pull_var_clause(expr, 0);
2092 2532 : keycount = list_length(varList);
2093 :
2094 2532 : if (keycount > 0)
2095 : {
2096 : ListCell *vl;
2097 2518 : int i = 0;
2098 :
2099 2518 : attNos = (int16 *) palloc(keycount * sizeof(int16));
2100 5660 : foreach(vl, varList)
2101 : {
2102 3142 : Var *var = (Var *) lfirst(vl);
2103 : int j;
2104 :
2105 3386 : for (j = 0; j < i; j++)
2106 644 : if (attNos[j] == var->varattno)
2107 400 : break;
2108 3142 : if (j == i)
2109 2742 : attNos[i++] = var->varattno;
2110 : }
2111 2518 : keycount = i;
2112 : }
2113 : else
2114 14 : attNos = NULL;
2115 :
2116 : /*
2117 : * Partitioned tables do not contain any rows themselves, so a NO INHERIT
2118 : * constraint makes no sense.
2119 : */
2120 2532 : if (is_no_inherit &&
2121 112 : rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2122 24 : ereport(ERROR,
2123 : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2124 : errmsg("cannot add NO INHERIT constraint to partitioned table \"%s\"",
2125 : RelationGetRelationName(rel))));
2126 :
2127 : /*
2128 : * Create the Check Constraint
2129 : */
2130 : constrOid =
2131 2508 : CreateConstraintEntry(ccname, /* Constraint Name */
2132 2508 : RelationGetNamespace(rel), /* namespace */
2133 : CONSTRAINT_CHECK, /* Constraint Type */
2134 : false, /* Is Deferrable */
2135 : false, /* Is Deferred */
2136 : is_enforced, /* Is Enforced */
2137 : is_validated,
2138 : InvalidOid, /* no parent constraint */
2139 : RelationGetRelid(rel), /* relation */
2140 : attNos, /* attrs in the constraint */
2141 : keycount, /* # key attrs in the constraint */
2142 : keycount, /* # total attrs in the constraint */
2143 : InvalidOid, /* not a domain constraint */
2144 : InvalidOid, /* no associated index */
2145 : InvalidOid, /* Foreign key fields */
2146 : NULL,
2147 : NULL,
2148 : NULL,
2149 : NULL,
2150 : 0,
2151 : ' ',
2152 : ' ',
2153 : NULL,
2154 : 0,
2155 : ' ',
2156 : NULL, /* not an exclusion constraint */
2157 : expr, /* Tree form of check constraint */
2158 : ccbin, /* Binary form of check constraint */
2159 : is_local, /* conislocal */
2160 : inhcount, /* coninhcount */
2161 : is_no_inherit, /* connoinherit */
2162 : false, /* conperiod */
2163 : is_internal); /* internally constructed? */
2164 :
2165 2508 : pfree(ccbin);
2166 :
2167 2508 : return constrOid;
2168 : }
2169 :
2170 : /*
2171 : * Store a not-null constraint for the given relation
2172 : *
2173 : * The OID of the new constraint is returned.
2174 : */
2175 : static Oid
2176 22890 : StoreRelNotNull(Relation rel, const char *nnname, AttrNumber attnum,
2177 : bool is_validated, bool is_local, int inhcount,
2178 : bool is_no_inherit)
2179 : {
2180 : Oid constrOid;
2181 :
2182 : Assert(attnum > InvalidAttrNumber);
2183 :
2184 : constrOid =
2185 22890 : CreateConstraintEntry(nnname,
2186 22890 : RelationGetNamespace(rel),
2187 : CONSTRAINT_NOTNULL,
2188 : false,
2189 : false,
2190 : true, /* Is Enforced */
2191 : is_validated,
2192 : InvalidOid,
2193 : RelationGetRelid(rel),
2194 : &attnum,
2195 : 1,
2196 : 1,
2197 : InvalidOid, /* not a domain constraint */
2198 : InvalidOid, /* no associated index */
2199 : InvalidOid, /* Foreign key fields */
2200 : NULL,
2201 : NULL,
2202 : NULL,
2203 : NULL,
2204 : 0,
2205 : ' ',
2206 : ' ',
2207 : NULL,
2208 : 0,
2209 : ' ',
2210 : NULL, /* not an exclusion constraint */
2211 : NULL,
2212 : NULL,
2213 : is_local,
2214 : inhcount,
2215 : is_no_inherit,
2216 : false,
2217 : false);
2218 22890 : return constrOid;
2219 : }
2220 :
2221 : /*
2222 : * Store defaults and CHECK constraints (passed as a list of CookedConstraint).
2223 : *
2224 : * Each CookedConstraint struct is modified to store the new catalog tuple OID.
2225 : *
2226 : * NOTE: only pre-cooked expressions will be passed this way, which is to
2227 : * say expressions inherited from an existing relation. Newly parsed
2228 : * expressions can be added later, by direct calls to StoreAttrDefault
2229 : * and StoreRelCheck (see AddRelationNewConstraints()).
2230 : */
2231 : static void
2232 81020 : StoreConstraints(Relation rel, List *cooked_constraints, bool is_internal)
2233 : {
2234 81020 : int numchecks = 0;
2235 : ListCell *lc;
2236 :
2237 81020 : if (cooked_constraints == NIL)
2238 80518 : return; /* nothing to do */
2239 :
2240 : /*
2241 : * Deparsing of constraint expressions will fail unless the just-created
2242 : * pg_attribute tuples for this relation are made visible. So, bump the
2243 : * command counter. CAUTION: this will cause a relcache entry rebuild.
2244 : */
2245 502 : CommandCounterIncrement();
2246 :
2247 1276 : foreach(lc, cooked_constraints)
2248 : {
2249 774 : CookedConstraint *con = (CookedConstraint *) lfirst(lc);
2250 :
2251 774 : switch (con->contype)
2252 : {
2253 344 : case CONSTR_DEFAULT:
2254 344 : con->conoid = StoreAttrDefault(rel, con->attnum, con->expr,
2255 : is_internal, false);
2256 344 : break;
2257 430 : case CONSTR_CHECK:
2258 430 : con->conoid =
2259 430 : StoreRelCheck(rel, con->name, con->expr,
2260 430 : con->is_enforced, !con->skip_validation,
2261 430 : con->is_local, con->inhcount,
2262 430 : con->is_no_inherit, is_internal);
2263 430 : numchecks++;
2264 430 : break;
2265 :
2266 0 : default:
2267 0 : elog(ERROR, "unrecognized constraint type: %d",
2268 : (int) con->contype);
2269 : }
2270 : }
2271 :
2272 502 : if (numchecks > 0)
2273 220 : SetRelationNumChecks(rel, numchecks);
2274 : }
2275 :
2276 : /*
2277 : * AddRelationNewConstraints
2278 : *
2279 : * Add new column default expressions and/or constraint check expressions
2280 : * to an existing relation. This is defined to do both for efficiency in
2281 : * DefineRelation, but of course you can do just one or the other by passing
2282 : * empty lists.
2283 : *
2284 : * rel: relation to be modified
2285 : * newColDefaults: list of RawColumnDefault structures
2286 : * newConstraints: list of Constraint nodes
2287 : * allow_merge: true if check constraints may be merged with existing ones
2288 : * is_local: true if definition is local, false if it's inherited
2289 : * is_internal: true if result of some internal process, not a user request
2290 : * queryString: used during expression transformation of default values and
2291 : * cooked CHECK constraints
2292 : *
2293 : * All entries in newColDefaults will be processed. Entries in newConstraints
2294 : * will be processed only if they are CONSTR_CHECK or CONSTR_NOTNULL types.
2295 : *
2296 : * Returns a list of CookedConstraint nodes that shows the cooked form of
2297 : * the default and constraint expressions added to the relation.
2298 : *
2299 : * NB: caller should have opened rel with some self-conflicting lock mode,
2300 : * and should hold that lock till end of transaction; for normal cases that'll
2301 : * be AccessExclusiveLock, but if caller knows that the constraint is already
2302 : * enforced by some other means, it can be ShareUpdateExclusiveLock. Also, we
2303 : * assume the caller has done a CommandCounterIncrement if necessary to make
2304 : * the relation's catalog tuples visible.
2305 : */
2306 : List *
2307 14628 : AddRelationNewConstraints(Relation rel,
2308 : List *newColDefaults,
2309 : List *newConstraints,
2310 : bool allow_merge,
2311 : bool is_local,
2312 : bool is_internal,
2313 : const char *queryString)
2314 : {
2315 14628 : List *cookedConstraints = NIL;
2316 : TupleDesc tupleDesc;
2317 : TupleConstr *oldconstr;
2318 : int numoldchecks;
2319 : ParseState *pstate;
2320 : ParseNamespaceItem *nsitem;
2321 : int numchecks;
2322 : List *checknames;
2323 : List *nnnames;
2324 : Node *expr;
2325 : CookedConstraint *cooked;
2326 :
2327 : /*
2328 : * Get info about existing constraints.
2329 : */
2330 14628 : tupleDesc = RelationGetDescr(rel);
2331 14628 : oldconstr = tupleDesc->constr;
2332 14628 : if (oldconstr)
2333 12588 : numoldchecks = oldconstr->num_check;
2334 : else
2335 2040 : numoldchecks = 0;
2336 :
2337 : /*
2338 : * Create a dummy ParseState and insert the target relation as its sole
2339 : * rangetable entry. We need a ParseState for transformExpr.
2340 : */
2341 14628 : pstate = make_parsestate(NULL);
2342 14628 : pstate->p_sourcetext = queryString;
2343 14628 : nsitem = addRangeTableEntryForRelation(pstate,
2344 : rel,
2345 : AccessShareLock,
2346 : NULL,
2347 : false,
2348 : true);
2349 14628 : addNSItemToQuery(pstate, nsitem, true, true, true);
2350 :
2351 : /*
2352 : * Process column default expressions.
2353 : */
2354 32564 : foreach_ptr(RawColumnDefault, colDef, newColDefaults)
2355 : {
2356 3548 : Form_pg_attribute atp = TupleDescAttr(rel->rd_att, colDef->attnum - 1);
2357 : Oid defOid;
2358 :
2359 3548 : expr = cookDefault(pstate, colDef->raw_default,
2360 : atp->atttypid, atp->atttypmod,
2361 3548 : NameStr(atp->attname),
2362 3548 : atp->attgenerated);
2363 :
2364 : /*
2365 : * If the expression is just a NULL constant, we do not bother to make
2366 : * an explicit pg_attrdef entry, since the default behavior is
2367 : * equivalent. This applies to column defaults, but not for
2368 : * generation expressions.
2369 : *
2370 : * Note a nonobvious property of this test: if the column is of a
2371 : * domain type, what we'll get is not a bare null Const but a
2372 : * CoerceToDomain expr, so we will not discard the default. This is
2373 : * critical because the column default needs to be retained to
2374 : * override any default that the domain might have.
2375 : */
2376 3428 : if (expr == NULL ||
2377 3428 : (!colDef->generated &&
2378 2576 : IsA(expr, Const) &&
2379 1262 : castNode(Const, expr)->constisnull))
2380 122 : continue;
2381 :
2382 : /* If the DEFAULT is volatile we cannot use a missing value */
2383 3866 : if (colDef->missingMode &&
2384 560 : contain_volatile_functions_after_planning((Expr *) expr))
2385 78 : colDef->missingMode = false;
2386 :
2387 3306 : defOid = StoreAttrDefault(rel, colDef->attnum, expr, is_internal,
2388 3306 : colDef->missingMode);
2389 :
2390 3306 : cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2391 3306 : cooked->contype = CONSTR_DEFAULT;
2392 3306 : cooked->conoid = defOid;
2393 3306 : cooked->name = NULL;
2394 3306 : cooked->attnum = colDef->attnum;
2395 3306 : cooked->expr = expr;
2396 3306 : cooked->is_enforced = true;
2397 3306 : cooked->skip_validation = false;
2398 3306 : cooked->is_local = is_local;
2399 3306 : cooked->inhcount = is_local ? 0 : 1;
2400 3306 : cooked->is_no_inherit = false;
2401 3306 : cookedConstraints = lappend(cookedConstraints, cooked);
2402 : }
2403 :
2404 : /*
2405 : * Process constraint expressions.
2406 : */
2407 14508 : numchecks = numoldchecks;
2408 14508 : checknames = NIL;
2409 14508 : nnnames = NIL;
2410 40302 : foreach_node(Constraint, cdef, newConstraints)
2411 : {
2412 : Oid constrOid;
2413 :
2414 11586 : if (cdef->contype == CONSTR_CHECK)
2415 : {
2416 : char *ccname;
2417 :
2418 2310 : if (cdef->raw_expr != NULL)
2419 : {
2420 : Assert(cdef->cooked_expr == NULL);
2421 :
2422 : /*
2423 : * Transform raw parsetree to executable expression, and
2424 : * verify it's valid as a CHECK constraint.
2425 : */
2426 2056 : expr = cookConstraint(pstate, cdef->raw_expr,
2427 2056 : RelationGetRelationName(rel));
2428 : }
2429 : else
2430 : {
2431 : Assert(cdef->cooked_expr != NULL);
2432 :
2433 : /*
2434 : * Here, we assume the parser will only pass us valid CHECK
2435 : * expressions, so we do no particular checking.
2436 : */
2437 254 : expr = stringToNode(cdef->cooked_expr);
2438 : }
2439 :
2440 : /*
2441 : * Check name uniqueness, or generate a name if none was given.
2442 : */
2443 2280 : if (cdef->conname != NULL)
2444 : {
2445 1606 : ccname = cdef->conname;
2446 : /* Check against other new constraints */
2447 : /* Needed because we don't do CommandCounterIncrement in loop */
2448 3322 : foreach_ptr(char, chkname, checknames)
2449 : {
2450 110 : if (strcmp(chkname, ccname) == 0)
2451 0 : ereport(ERROR,
2452 : (errcode(ERRCODE_DUPLICATE_OBJECT),
2453 : errmsg("check constraint \"%s\" already exists",
2454 : ccname)));
2455 : }
2456 :
2457 : /* save name for future checks */
2458 1606 : checknames = lappend(checknames, ccname);
2459 :
2460 : /*
2461 : * Check against pre-existing constraints. If we are allowed
2462 : * to merge with an existing constraint, there's no more to do
2463 : * here. (We omit the duplicate constraint from the result,
2464 : * which is what ATAddCheckNNConstraint wants.)
2465 : */
2466 1558 : if (MergeWithExistingConstraint(rel, ccname, expr,
2467 : allow_merge, is_local,
2468 1606 : cdef->is_enforced,
2469 1606 : cdef->initially_valid,
2470 1606 : cdef->is_no_inherit))
2471 130 : continue;
2472 : }
2473 : else
2474 : {
2475 : /*
2476 : * When generating a name, we want to create "tab_col_check"
2477 : * for a column constraint and "tab_check" for a table
2478 : * constraint. We no longer have any info about the syntactic
2479 : * positioning of the constraint phrase, so we approximate
2480 : * this by seeing whether the expression references more than
2481 : * one column. (If the user played by the rules, the result
2482 : * is the same...)
2483 : *
2484 : * Note: pull_var_clause() doesn't descend into sublinks, but
2485 : * we eliminated those above; and anyway this only needs to be
2486 : * an approximate answer.
2487 : */
2488 : List *vars;
2489 : char *colname;
2490 :
2491 674 : vars = pull_var_clause(expr, 0);
2492 :
2493 : /* eliminate duplicates */
2494 674 : vars = list_union(NIL, vars);
2495 :
2496 674 : if (list_length(vars) == 1)
2497 602 : colname = get_attname(RelationGetRelid(rel),
2498 602 : ((Var *) linitial(vars))->varattno,
2499 : true);
2500 : else
2501 72 : colname = NULL;
2502 :
2503 674 : ccname = ChooseConstraintName(RelationGetRelationName(rel),
2504 : colname,
2505 : "check",
2506 674 : RelationGetNamespace(rel),
2507 : checknames);
2508 :
2509 : /* save name for future checks */
2510 674 : checknames = lappend(checknames, ccname);
2511 : }
2512 :
2513 : /*
2514 : * OK, store it.
2515 : */
2516 : constrOid =
2517 2102 : StoreRelCheck(rel, ccname, expr, cdef->is_enforced,
2518 2102 : cdef->initially_valid, is_local,
2519 2102 : is_local ? 0 : 1, cdef->is_no_inherit,
2520 : is_internal);
2521 :
2522 2078 : numchecks++;
2523 :
2524 2078 : cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2525 2078 : cooked->contype = CONSTR_CHECK;
2526 2078 : cooked->conoid = constrOid;
2527 2078 : cooked->name = ccname;
2528 2078 : cooked->attnum = 0;
2529 2078 : cooked->expr = expr;
2530 2078 : cooked->is_enforced = cdef->is_enforced;
2531 2078 : cooked->skip_validation = cdef->skip_validation;
2532 2078 : cooked->is_local = is_local;
2533 2078 : cooked->inhcount = is_local ? 0 : 1;
2534 2078 : cooked->is_no_inherit = cdef->is_no_inherit;
2535 2078 : cookedConstraints = lappend(cookedConstraints, cooked);
2536 : }
2537 9276 : else if (cdef->contype == CONSTR_NOTNULL)
2538 : {
2539 : CookedConstraint *nncooked;
2540 : AttrNumber colnum;
2541 9276 : int16 inhcount = is_local ? 0 : 1;
2542 : char *nnname;
2543 :
2544 : /* Determine which column to modify */
2545 9276 : colnum = get_attnum(RelationGetRelid(rel), strVal(linitial(cdef->keys)));
2546 9276 : if (colnum == InvalidAttrNumber)
2547 18 : ereport(ERROR,
2548 : errcode(ERRCODE_UNDEFINED_COLUMN),
2549 : errmsg("column \"%s\" of relation \"%s\" does not exist",
2550 : strVal(linitial(cdef->keys)), RelationGetRelationName(rel)));
2551 9258 : if (colnum < InvalidAttrNumber)
2552 0 : ereport(ERROR,
2553 : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2554 : errmsg("cannot add not-null constraint on system column \"%s\"",
2555 : strVal(linitial(cdef->keys))));
2556 :
2557 : /*
2558 : * If the column already has a not-null constraint, we don't want
2559 : * to add another one; just adjust inheritance status as needed.
2560 : */
2561 9234 : if (AdjustNotNullInheritance(RelationGetRelid(rel), colnum,
2562 9258 : is_local, cdef->is_no_inherit))
2563 524 : continue;
2564 :
2565 : /*
2566 : * If a constraint name is specified, check that it isn't already
2567 : * used. Otherwise, choose a non-conflicting one ourselves.
2568 : */
2569 8710 : if (cdef->conname)
2570 : {
2571 842 : if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
2572 : RelationGetRelid(rel),
2573 842 : cdef->conname))
2574 6 : ereport(ERROR,
2575 : errcode(ERRCODE_DUPLICATE_OBJECT),
2576 : errmsg("constraint \"%s\" for relation \"%s\" already exists",
2577 : cdef->conname, RelationGetRelationName(rel)));
2578 836 : nnname = cdef->conname;
2579 : }
2580 : else
2581 15736 : nnname = ChooseConstraintName(RelationGetRelationName(rel),
2582 7868 : strVal(linitial(cdef->keys)),
2583 : "not_null",
2584 7868 : RelationGetNamespace(rel),
2585 : nnnames);
2586 8704 : nnnames = lappend(nnnames, nnname);
2587 :
2588 : constrOid =
2589 8704 : StoreRelNotNull(rel, nnname, colnum,
2590 8704 : cdef->initially_valid,
2591 : is_local,
2592 : inhcount,
2593 8704 : cdef->is_no_inherit);
2594 :
2595 8704 : nncooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
2596 8704 : nncooked->contype = CONSTR_NOTNULL;
2597 8704 : nncooked->conoid = constrOid;
2598 8704 : nncooked->name = nnname;
2599 8704 : nncooked->attnum = colnum;
2600 8704 : nncooked->expr = NULL;
2601 8704 : nncooked->is_enforced = true;
2602 8704 : nncooked->skip_validation = cdef->skip_validation;
2603 8704 : nncooked->is_local = is_local;
2604 8704 : nncooked->inhcount = inhcount;
2605 8704 : nncooked->is_no_inherit = cdef->is_no_inherit;
2606 :
2607 8704 : cookedConstraints = lappend(cookedConstraints, nncooked);
2608 : }
2609 : }
2610 :
2611 : /*
2612 : * Update the count of constraints in the relation's pg_class tuple. We do
2613 : * this even if there was no change, in order to ensure that an SI update
2614 : * message is sent out for the pg_class tuple, which will force other
2615 : * backends to rebuild their relcache entries for the rel. (This is
2616 : * critical if we added defaults but not constraints.)
2617 : */
2618 14358 : SetRelationNumChecks(rel, numchecks);
2619 :
2620 14358 : return cookedConstraints;
2621 : }
2622 :
2623 : /*
2624 : * Check for a pre-existing check constraint that conflicts with a proposed
2625 : * new one, and either adjust its conislocal/coninhcount settings or throw
2626 : * error as needed.
2627 : *
2628 : * Returns true if merged (constraint is a duplicate), or false if it's
2629 : * got a so-far-unique name, or throws error if conflict.
2630 : *
2631 : * XXX See MergeConstraintsIntoExisting too if you change this code.
2632 : */
2633 : static bool
2634 1606 : MergeWithExistingConstraint(Relation rel, const char *ccname, Node *expr,
2635 : bool allow_merge, bool is_local,
2636 : bool is_enforced,
2637 : bool is_initially_valid,
2638 : bool is_no_inherit)
2639 : {
2640 : bool found;
2641 : Relation conDesc;
2642 : SysScanDesc conscan;
2643 : ScanKeyData skey[3];
2644 : HeapTuple tup;
2645 :
2646 : /* Search for a pg_constraint entry with same name and relation */
2647 1606 : conDesc = table_open(ConstraintRelationId, RowExclusiveLock);
2648 :
2649 1606 : found = false;
2650 :
2651 1606 : ScanKeyInit(&skey[0],
2652 : Anum_pg_constraint_conrelid,
2653 : BTEqualStrategyNumber, F_OIDEQ,
2654 : ObjectIdGetDatum(RelationGetRelid(rel)));
2655 1606 : ScanKeyInit(&skey[1],
2656 : Anum_pg_constraint_contypid,
2657 : BTEqualStrategyNumber, F_OIDEQ,
2658 : ObjectIdGetDatum(InvalidOid));
2659 1606 : ScanKeyInit(&skey[2],
2660 : Anum_pg_constraint_conname,
2661 : BTEqualStrategyNumber, F_NAMEEQ,
2662 : CStringGetDatum(ccname));
2663 :
2664 1606 : conscan = systable_beginscan(conDesc, ConstraintRelidTypidNameIndexId, true,
2665 : NULL, 3, skey);
2666 :
2667 : /* There can be at most one matching row */
2668 1606 : if (HeapTupleIsValid(tup = systable_getnext(conscan)))
2669 : {
2670 178 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tup);
2671 :
2672 : /* Found it. Conflicts if not identical check constraint */
2673 178 : if (con->contype == CONSTRAINT_CHECK)
2674 : {
2675 : Datum val;
2676 : bool isnull;
2677 :
2678 172 : val = fastgetattr(tup,
2679 : Anum_pg_constraint_conbin,
2680 : conDesc->rd_att, &isnull);
2681 172 : if (isnull)
2682 0 : elog(ERROR, "null conbin for rel %s",
2683 : RelationGetRelationName(rel));
2684 172 : if (equal(expr, stringToNode(TextDatumGetCString(val))))
2685 166 : found = true;
2686 : }
2687 :
2688 : /*
2689 : * If the existing constraint is purely inherited (no local
2690 : * definition) then interpret addition of a local constraint as a
2691 : * legal merge. This allows ALTER ADD CONSTRAINT on parent and child
2692 : * tables to be given in either order with same end state. However if
2693 : * the relation is a partition, all inherited constraints are always
2694 : * non-local, including those that were merged.
2695 : */
2696 178 : if (is_local && !con->conislocal && !rel->rd_rel->relispartition)
2697 96 : allow_merge = true;
2698 :
2699 178 : if (!found || !allow_merge)
2700 12 : ereport(ERROR,
2701 : (errcode(ERRCODE_DUPLICATE_OBJECT),
2702 : errmsg("constraint \"%s\" for relation \"%s\" already exists",
2703 : ccname, RelationGetRelationName(rel))));
2704 :
2705 : /* If the child constraint is "no inherit" then cannot merge */
2706 166 : if (con->connoinherit)
2707 0 : ereport(ERROR,
2708 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2709 : errmsg("constraint \"%s\" conflicts with non-inherited constraint on relation \"%s\"",
2710 : ccname, RelationGetRelationName(rel))));
2711 :
2712 : /*
2713 : * Must not change an existing inherited constraint to "no inherit"
2714 : * status. That's because inherited constraints should be able to
2715 : * propagate to lower-level children.
2716 : */
2717 166 : if (con->coninhcount > 0 && is_no_inherit)
2718 6 : ereport(ERROR,
2719 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2720 : errmsg("constraint \"%s\" conflicts with inherited constraint on relation \"%s\"",
2721 : ccname, RelationGetRelationName(rel))));
2722 :
2723 : /*
2724 : * If the child constraint is "not valid" then cannot merge with a
2725 : * valid parent constraint.
2726 : */
2727 160 : if (is_initially_valid && con->conenforced && !con->convalidated)
2728 6 : ereport(ERROR,
2729 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2730 : errmsg("constraint \"%s\" conflicts with NOT VALID constraint on relation \"%s\"",
2731 : ccname, RelationGetRelationName(rel))));
2732 :
2733 : /*
2734 : * A non-enforced child constraint cannot be merged with an enforced
2735 : * parent constraint. However, the reverse is allowed, where the child
2736 : * constraint is enforced.
2737 : */
2738 154 : if ((!is_local && is_enforced && !con->conenforced) ||
2739 96 : (is_local && !is_enforced && con->conenforced))
2740 24 : ereport(ERROR,
2741 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2742 : errmsg("constraint \"%s\" conflicts with NOT ENFORCED constraint on relation \"%s\"",
2743 : ccname, RelationGetRelationName(rel))));
2744 :
2745 : /* OK to update the tuple */
2746 130 : ereport(NOTICE,
2747 : (errmsg("merging constraint \"%s\" with inherited definition",
2748 : ccname)));
2749 :
2750 130 : tup = heap_copytuple(tup);
2751 130 : con = (Form_pg_constraint) GETSTRUCT(tup);
2752 :
2753 : /*
2754 : * In case of partitions, an inherited constraint must be inherited
2755 : * only once since it cannot have multiple parents and it is never
2756 : * considered local.
2757 : */
2758 130 : if (rel->rd_rel->relispartition)
2759 : {
2760 12 : con->coninhcount = 1;
2761 12 : con->conislocal = false;
2762 : }
2763 : else
2764 : {
2765 118 : if (is_local)
2766 72 : con->conislocal = true;
2767 46 : else if (pg_add_s16_overflow(con->coninhcount, 1,
2768 : &con->coninhcount))
2769 0 : ereport(ERROR,
2770 : errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2771 : errmsg("too many inheritance parents"));
2772 : }
2773 :
2774 130 : if (is_no_inherit)
2775 : {
2776 : Assert(is_local);
2777 0 : con->connoinherit = true;
2778 : }
2779 :
2780 : /*
2781 : * If the child constraint is required to be enforced while the parent
2782 : * constraint is not, this should be allowed by marking the child
2783 : * constraint as enforced. In the reverse case, an error would have
2784 : * already been thrown before reaching this point.
2785 : */
2786 130 : if (is_enforced && !con->conenforced)
2787 : {
2788 : Assert(is_local);
2789 12 : con->conenforced = true;
2790 12 : con->convalidated = true;
2791 : }
2792 :
2793 130 : CatalogTupleUpdate(conDesc, &tup->t_self, tup);
2794 : }
2795 :
2796 1558 : systable_endscan(conscan);
2797 1558 : table_close(conDesc, RowExclusiveLock);
2798 :
2799 1558 : return found;
2800 : }
2801 :
2802 : /*
2803 : * Create the not-null constraints when creating a new relation
2804 : *
2805 : * These come from two sources: the 'constraints' list (of Constraint) is
2806 : * specified directly by the user; the 'old_notnulls' list (of
2807 : * CookedConstraint) comes from inheritance. We create one constraint
2808 : * for each column, giving priority to user-specified ones, and setting
2809 : * inhcount according to how many parents cause each column to get a
2810 : * not-null constraint. If a user-specified name clashes with another
2811 : * user-specified name, an error is raised.
2812 : *
2813 : * Returns a list of AttrNumber for columns that need to have the attnotnull
2814 : * flag set.
2815 : */
2816 : List *
2817 56248 : AddRelationNotNullConstraints(Relation rel, List *constraints,
2818 : List *old_notnulls)
2819 : {
2820 : List *givennames;
2821 : List *nnnames;
2822 56248 : List *nncols = NIL;
2823 :
2824 : /*
2825 : * We track two lists of names: nnnames keeps all the constraint names,
2826 : * givennames tracks user-generated names. The distinction is important,
2827 : * because we must raise error for user-generated name conflicts, but for
2828 : * system-generated name conflicts we just generate another.
2829 : */
2830 56248 : nnnames = NIL;
2831 56248 : givennames = NIL;
2832 :
2833 : /*
2834 : * First, create all not-null constraints that are directly specified by
2835 : * the user. Note that inheritance might have given us another source for
2836 : * each, so we must scan the old_notnulls list and increment inhcount for
2837 : * each element with identical attnum. We delete from there any element
2838 : * that we process.
2839 : *
2840 : * We don't use foreach() here because we have two nested loops over the
2841 : * constraint list, with possible element deletions in the inner one. If
2842 : * we used foreach_delete_current() it could only fix up the state of one
2843 : * of the loops, so it seems cleaner to use looping over list indexes for
2844 : * both loops. Note that any deletion will happen beyond where the outer
2845 : * loop is, so its index never needs adjustment.
2846 : */
2847 68520 : for (int outerpos = 0; outerpos < list_length(constraints); outerpos++)
2848 : {
2849 : Constraint *constr;
2850 : AttrNumber attnum;
2851 : char *conname;
2852 12350 : int inhcount = 0;
2853 :
2854 12350 : constr = list_nth_node(Constraint, constraints, outerpos);
2855 :
2856 : Assert(constr->contype == CONSTR_NOTNULL);
2857 :
2858 12350 : attnum = get_attnum(RelationGetRelid(rel),
2859 12350 : strVal(linitial(constr->keys)));
2860 12350 : if (attnum == InvalidAttrNumber)
2861 0 : ereport(ERROR,
2862 : errcode(ERRCODE_UNDEFINED_COLUMN),
2863 : errmsg("column \"%s\" of relation \"%s\" does not exist",
2864 : strVal(linitial(constr->keys)),
2865 : RelationGetRelationName(rel)));
2866 12350 : if (attnum < InvalidAttrNumber)
2867 0 : ereport(ERROR,
2868 : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2869 : errmsg("cannot add not-null constraint on system column \"%s\"",
2870 : strVal(linitial(constr->keys))));
2871 :
2872 : /*
2873 : * A column can only have one not-null constraint, so discard any
2874 : * additional ones that appear for columns we already saw; but check
2875 : * that the NO INHERIT flags match.
2876 : */
2877 16370 : for (int restpos = outerpos + 1; restpos < list_length(constraints);)
2878 : {
2879 : Constraint *other;
2880 :
2881 4080 : other = list_nth_node(Constraint, constraints, restpos);
2882 4080 : if (strcmp(strVal(linitial(constr->keys)),
2883 4080 : strVal(linitial(other->keys))) == 0)
2884 : {
2885 96 : if (other->is_no_inherit != constr->is_no_inherit)
2886 42 : ereport(ERROR,
2887 : errcode(ERRCODE_SYNTAX_ERROR),
2888 : errmsg("conflicting NO INHERIT declaration for not-null constraint on column \"%s\"",
2889 : strVal(linitial(constr->keys))));
2890 :
2891 : /*
2892 : * Preserve constraint name if one is specified, but raise an
2893 : * error if conflicting ones are specified.
2894 : */
2895 54 : if (other->conname)
2896 : {
2897 36 : if (!constr->conname)
2898 12 : constr->conname = pstrdup(other->conname);
2899 24 : else if (strcmp(constr->conname, other->conname) != 0)
2900 18 : ereport(ERROR,
2901 : errcode(ERRCODE_SYNTAX_ERROR),
2902 : errmsg("conflicting not-null constraint names \"%s\" and \"%s\"",
2903 : constr->conname, other->conname));
2904 : }
2905 :
2906 : /* XXX do we need to verify any other fields? */
2907 36 : constraints = list_delete_nth_cell(constraints, restpos);
2908 : }
2909 : else
2910 3984 : restpos++;
2911 : }
2912 :
2913 : /*
2914 : * Search in the list of inherited constraints for any entries on the
2915 : * same column; determine an inheritance count from that. Also, if at
2916 : * least one parent has a constraint for this column, then we must not
2917 : * accept a user specification for a NO INHERIT one. Any constraint
2918 : * from parents that we process here is deleted from the list: we no
2919 : * longer need to process it in the loop below.
2920 : */
2921 24732 : foreach_ptr(CookedConstraint, old, old_notnulls)
2922 : {
2923 176 : if (old->attnum == attnum)
2924 : {
2925 : /*
2926 : * If we get a constraint from the parent, having a local NO
2927 : * INHERIT one doesn't work.
2928 : */
2929 146 : if (constr->is_no_inherit)
2930 12 : ereport(ERROR,
2931 : (errcode(ERRCODE_DATATYPE_MISMATCH),
2932 : errmsg("cannot define not-null constraint on column \"%s\" with NO INHERIT",
2933 : strVal(linitial(constr->keys))),
2934 : errdetail("The column has an inherited not-null constraint.")));
2935 :
2936 134 : inhcount++;
2937 134 : old_notnulls = foreach_delete_current(old_notnulls, old);
2938 : }
2939 : }
2940 :
2941 : /*
2942 : * Determine a constraint name, which may have been specified by the
2943 : * user, or raise an error if a conflict exists with another
2944 : * user-specified name.
2945 : */
2946 12278 : if (constr->conname)
2947 : {
2948 1294 : foreach_ptr(char, thisname, givennames)
2949 : {
2950 114 : if (strcmp(thisname, constr->conname) == 0)
2951 6 : ereport(ERROR,
2952 : errcode(ERRCODE_DUPLICATE_OBJECT),
2953 : errmsg("constraint \"%s\" for relation \"%s\" already exists",
2954 : constr->conname,
2955 : RelationGetRelationName(rel)));
2956 : }
2957 :
2958 590 : conname = constr->conname;
2959 590 : givennames = lappend(givennames, conname);
2960 : }
2961 : else
2962 11682 : conname = ChooseConstraintName(RelationGetRelationName(rel),
2963 11682 : get_attname(RelationGetRelid(rel),
2964 : attnum, false),
2965 : "not_null",
2966 11682 : RelationGetNamespace(rel),
2967 : nnnames);
2968 12272 : nnnames = lappend(nnnames, conname);
2969 :
2970 12272 : StoreRelNotNull(rel, conname,
2971 : attnum, true, true,
2972 12272 : inhcount, constr->is_no_inherit);
2973 :
2974 12272 : nncols = lappend_int(nncols, attnum);
2975 : }
2976 :
2977 : /*
2978 : * If any column remains in the old_notnulls list, we must create a not-
2979 : * null constraint marked not-local for that column. Because multiple
2980 : * parents could specify a not-null constraint for the same column, we
2981 : * must count how many there are and set an appropriate inhcount
2982 : * accordingly, deleting elements we've already processed.
2983 : *
2984 : * We don't use foreach() here because we have two nested loops over the
2985 : * constraint list, with possible element deletions in the inner one. If
2986 : * we used foreach_delete_current() it could only fix up the state of one
2987 : * of the loops, so it seems cleaner to use looping over list indexes for
2988 : * both loops. Note that any deletion will happen beyond where the outer
2989 : * loop is, so its index never needs adjustment.
2990 : */
2991 58084 : for (int outerpos = 0; outerpos < list_length(old_notnulls); outerpos++)
2992 : {
2993 : CookedConstraint *cooked;
2994 1914 : char *conname = NULL;
2995 1914 : int inhcount = 1;
2996 :
2997 1914 : cooked = (CookedConstraint *) list_nth(old_notnulls, outerpos);
2998 : Assert(cooked->contype == CONSTR_NOTNULL);
2999 : Assert(cooked->name);
3000 :
3001 : /*
3002 : * Preserve the first non-conflicting constraint name we come across.
3003 : */
3004 1914 : if (conname == NULL)
3005 1914 : conname = cooked->name;
3006 :
3007 2380 : for (int restpos = outerpos + 1; restpos < list_length(old_notnulls);)
3008 : {
3009 : CookedConstraint *other;
3010 :
3011 466 : other = (CookedConstraint *) list_nth(old_notnulls, restpos);
3012 : Assert(other->name);
3013 466 : if (other->attnum == cooked->attnum)
3014 : {
3015 32 : if (conname == NULL)
3016 0 : conname = other->name;
3017 :
3018 32 : inhcount++;
3019 32 : old_notnulls = list_delete_nth_cell(old_notnulls, restpos);
3020 : }
3021 : else
3022 434 : restpos++;
3023 : }
3024 :
3025 : /* If we got a name, make sure it isn't one we've already used */
3026 1914 : if (conname != NULL)
3027 : {
3028 4280 : foreach_ptr(char, thisname, nnnames)
3029 : {
3030 458 : if (strcmp(thisname, conname) == 0)
3031 : {
3032 6 : conname = NULL;
3033 6 : break;
3034 : }
3035 : }
3036 : }
3037 :
3038 : /* and choose a name, if needed */
3039 1914 : if (conname == NULL)
3040 6 : conname = ChooseConstraintName(RelationGetRelationName(rel),
3041 6 : get_attname(RelationGetRelid(rel),
3042 6 : cooked->attnum, false),
3043 : "not_null",
3044 6 : RelationGetNamespace(rel),
3045 : nnnames);
3046 1914 : nnnames = lappend(nnnames, conname);
3047 :
3048 : /* ignore the origin constraint's is_local and inhcount */
3049 1914 : StoreRelNotNull(rel, conname, cooked->attnum, true,
3050 : false, inhcount, false);
3051 :
3052 1914 : nncols = lappend_int(nncols, cooked->attnum);
3053 : }
3054 :
3055 56170 : return nncols;
3056 : }
3057 :
3058 : /*
3059 : * Update the count of constraints in the relation's pg_class tuple.
3060 : *
3061 : * Caller had better hold exclusive lock on the relation.
3062 : *
3063 : * An important side effect is that a SI update message will be sent out for
3064 : * the pg_class tuple, which will force other backends to rebuild their
3065 : * relcache entries for the rel. Also, this backend will rebuild its
3066 : * own relcache entry at the next CommandCounterIncrement.
3067 : */
3068 : static void
3069 14578 : SetRelationNumChecks(Relation rel, int numchecks)
3070 : {
3071 : Relation relrel;
3072 : HeapTuple reltup;
3073 : Form_pg_class relStruct;
3074 :
3075 14578 : relrel = table_open(RelationRelationId, RowExclusiveLock);
3076 14578 : reltup = SearchSysCacheCopy1(RELOID,
3077 : ObjectIdGetDatum(RelationGetRelid(rel)));
3078 14578 : if (!HeapTupleIsValid(reltup))
3079 0 : elog(ERROR, "cache lookup failed for relation %u",
3080 : RelationGetRelid(rel));
3081 14578 : relStruct = (Form_pg_class) GETSTRUCT(reltup);
3082 :
3083 14578 : if (relStruct->relchecks != numchecks)
3084 : {
3085 2168 : relStruct->relchecks = numchecks;
3086 :
3087 2168 : CatalogTupleUpdate(relrel, &reltup->t_self, reltup);
3088 : }
3089 : else
3090 : {
3091 : /* Skip the disk update, but force relcache inval anyway */
3092 12410 : CacheInvalidateRelcache(rel);
3093 : }
3094 :
3095 14578 : heap_freetuple(reltup);
3096 14578 : table_close(relrel, RowExclusiveLock);
3097 14578 : }
3098 :
3099 : /*
3100 : * Check for references to generated columns
3101 : */
3102 : static bool
3103 2932 : check_nested_generated_walker(Node *node, void *context)
3104 : {
3105 2932 : ParseState *pstate = context;
3106 :
3107 2932 : if (node == NULL)
3108 0 : return false;
3109 2932 : else if (IsA(node, Var))
3110 : {
3111 1088 : Var *var = (Var *) node;
3112 : Oid relid;
3113 : AttrNumber attnum;
3114 :
3115 1088 : relid = rt_fetch(var->varno, pstate->p_rtable)->relid;
3116 1088 : if (!OidIsValid(relid))
3117 0 : return false; /* XXX shouldn't we raise an error? */
3118 :
3119 1088 : attnum = var->varattno;
3120 :
3121 1088 : if (attnum > 0 && get_attgenerated(relid, attnum))
3122 18 : ereport(ERROR,
3123 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3124 : errmsg("cannot use generated column \"%s\" in column generation expression",
3125 : get_attname(relid, attnum, false)),
3126 : errdetail("A generated column cannot reference another generated column."),
3127 : parser_errposition(pstate, var->location)));
3128 : /* A whole-row Var is necessarily self-referential, so forbid it */
3129 1070 : if (attnum == 0)
3130 6 : ereport(ERROR,
3131 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3132 : errmsg("cannot use whole-row variable in column generation expression"),
3133 : errdetail("This would cause the generated column to depend on its own value."),
3134 : parser_errposition(pstate, var->location)));
3135 : /* System columns were already checked in the parser */
3136 :
3137 1064 : return false;
3138 : }
3139 : else
3140 1844 : return expression_tree_walker(node, check_nested_generated_walker,
3141 : context);
3142 : }
3143 :
3144 : static void
3145 882 : check_nested_generated(ParseState *pstate, Node *node)
3146 : {
3147 882 : check_nested_generated_walker(node, pstate);
3148 858 : }
3149 :
3150 : /*
3151 : * Take a raw default and convert it to a cooked format ready for
3152 : * storage.
3153 : *
3154 : * Parse state should be set up to recognize any vars that might appear
3155 : * in the expression. (Even though we plan to reject vars, it's more
3156 : * user-friendly to give the correct error message than "unknown var".)
3157 : *
3158 : * If atttypid is not InvalidOid, coerce the expression to the specified
3159 : * type (and typmod atttypmod). attname is only needed in this case:
3160 : * it is used in the error message, if any.
3161 : */
3162 : Node *
3163 3696 : cookDefault(ParseState *pstate,
3164 : Node *raw_default,
3165 : Oid atttypid,
3166 : int32 atttypmod,
3167 : const char *attname,
3168 : char attgenerated)
3169 : {
3170 : Node *expr;
3171 :
3172 : Assert(raw_default != NULL);
3173 :
3174 : /*
3175 : * Transform raw parsetree to executable expression.
3176 : */
3177 3696 : expr = transformExpr(pstate, raw_default, attgenerated ? EXPR_KIND_GENERATED_COLUMN : EXPR_KIND_COLUMN_DEFAULT);
3178 :
3179 3606 : if (attgenerated)
3180 : {
3181 : /* Disallow refs to other generated columns */
3182 882 : check_nested_generated(pstate, expr);
3183 :
3184 : /* Disallow mutable functions */
3185 858 : if (contain_mutable_functions_after_planning((Expr *) expr))
3186 6 : ereport(ERROR,
3187 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3188 : errmsg("generation expression is not immutable")));
3189 : }
3190 : else
3191 : {
3192 : /*
3193 : * For a default expression, transformExpr() should have rejected
3194 : * column references.
3195 : */
3196 : Assert(!contain_var_clause(expr));
3197 : }
3198 :
3199 : /*
3200 : * Coerce the expression to the correct type and typmod, if given. This
3201 : * should match the parser's processing of non-defaulted expressions ---
3202 : * see transformAssignedExpr().
3203 : */
3204 3576 : if (OidIsValid(atttypid))
3205 : {
3206 3576 : Oid type_id = exprType(expr);
3207 :
3208 3576 : expr = coerce_to_target_type(pstate, expr, type_id,
3209 : atttypid, atttypmod,
3210 : COERCION_ASSIGNMENT,
3211 : COERCE_IMPLICIT_CAST,
3212 : -1);
3213 3570 : if (expr == NULL)
3214 0 : ereport(ERROR,
3215 : (errcode(ERRCODE_DATATYPE_MISMATCH),
3216 : errmsg("column \"%s\" is of type %s"
3217 : " but default expression is of type %s",
3218 : attname,
3219 : format_type_be(atttypid),
3220 : format_type_be(type_id)),
3221 : errhint("You will need to rewrite or cast the expression.")));
3222 : }
3223 :
3224 : /*
3225 : * Finally, take care of collations in the finished expression.
3226 : */
3227 3570 : assign_expr_collations(pstate, expr);
3228 :
3229 3570 : return expr;
3230 : }
3231 :
3232 : /*
3233 : * Take a raw CHECK constraint expression and convert it to a cooked format
3234 : * ready for storage.
3235 : *
3236 : * Parse state must be set up to recognize any vars that might appear
3237 : * in the expression.
3238 : */
3239 : static Node *
3240 2056 : cookConstraint(ParseState *pstate,
3241 : Node *raw_constraint,
3242 : char *relname)
3243 : {
3244 : Node *expr;
3245 :
3246 : /*
3247 : * Transform raw parsetree to executable expression.
3248 : */
3249 2056 : expr = transformExpr(pstate, raw_constraint, EXPR_KIND_CHECK_CONSTRAINT);
3250 :
3251 : /*
3252 : * Make sure it yields a boolean result.
3253 : */
3254 2026 : expr = coerce_to_boolean(pstate, expr, "CHECK");
3255 :
3256 : /*
3257 : * Take care of collations.
3258 : */
3259 2026 : assign_expr_collations(pstate, expr);
3260 :
3261 : /*
3262 : * Make sure no outside relations are referred to (this is probably dead
3263 : * code now that add_missing_from is history).
3264 : */
3265 2026 : if (list_length(pstate->p_rtable) != 1)
3266 0 : ereport(ERROR,
3267 : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3268 : errmsg("only table \"%s\" can be referenced in check constraint",
3269 : relname)));
3270 :
3271 2026 : return expr;
3272 : }
3273 :
3274 : /*
3275 : * CopyStatistics --- copy entries in pg_statistic from one rel to another
3276 : */
3277 : void
3278 502 : CopyStatistics(Oid fromrelid, Oid torelid)
3279 : {
3280 : HeapTuple tup;
3281 : SysScanDesc scan;
3282 : ScanKeyData key[1];
3283 : Relation statrel;
3284 502 : CatalogIndexState indstate = NULL;
3285 :
3286 502 : statrel = table_open(StatisticRelationId, RowExclusiveLock);
3287 :
3288 : /* Now search for stat records */
3289 502 : ScanKeyInit(&key[0],
3290 : Anum_pg_statistic_starelid,
3291 : BTEqualStrategyNumber, F_OIDEQ,
3292 : ObjectIdGetDatum(fromrelid));
3293 :
3294 502 : scan = systable_beginscan(statrel, StatisticRelidAttnumInhIndexId,
3295 : true, NULL, 1, key);
3296 :
3297 508 : while (HeapTupleIsValid((tup = systable_getnext(scan))))
3298 : {
3299 : Form_pg_statistic statform;
3300 :
3301 : /* make a modifiable copy */
3302 6 : tup = heap_copytuple(tup);
3303 6 : statform = (Form_pg_statistic) GETSTRUCT(tup);
3304 :
3305 : /* update the copy of the tuple and insert it */
3306 6 : statform->starelid = torelid;
3307 :
3308 : /* fetch index information when we know we need it */
3309 6 : if (indstate == NULL)
3310 6 : indstate = CatalogOpenIndexes(statrel);
3311 :
3312 6 : CatalogTupleInsertWithInfo(statrel, tup, indstate);
3313 :
3314 6 : heap_freetuple(tup);
3315 : }
3316 :
3317 502 : systable_endscan(scan);
3318 :
3319 502 : if (indstate != NULL)
3320 6 : CatalogCloseIndexes(indstate);
3321 502 : table_close(statrel, RowExclusiveLock);
3322 502 : }
3323 :
3324 : /*
3325 : * RemoveStatistics --- remove entries in pg_statistic for a rel or column
3326 : *
3327 : * If attnum is zero, remove all entries for rel; else remove only the one(s)
3328 : * for that column.
3329 : */
3330 : void
3331 49202 : RemoveStatistics(Oid relid, AttrNumber attnum)
3332 : {
3333 : Relation pgstatistic;
3334 : SysScanDesc scan;
3335 : ScanKeyData key[2];
3336 : int nkeys;
3337 : HeapTuple tuple;
3338 :
3339 49202 : pgstatistic = table_open(StatisticRelationId, RowExclusiveLock);
3340 :
3341 49202 : ScanKeyInit(&key[0],
3342 : Anum_pg_statistic_starelid,
3343 : BTEqualStrategyNumber, F_OIDEQ,
3344 : ObjectIdGetDatum(relid));
3345 :
3346 49202 : if (attnum == 0)
3347 46188 : nkeys = 1;
3348 : else
3349 : {
3350 3014 : ScanKeyInit(&key[1],
3351 : Anum_pg_statistic_staattnum,
3352 : BTEqualStrategyNumber, F_INT2EQ,
3353 : Int16GetDatum(attnum));
3354 3014 : nkeys = 2;
3355 : }
3356 :
3357 49202 : scan = systable_beginscan(pgstatistic, StatisticRelidAttnumInhIndexId, true,
3358 : NULL, nkeys, key);
3359 :
3360 : /* we must loop even when attnum != 0, in case of inherited stats */
3361 52424 : while (HeapTupleIsValid(tuple = systable_getnext(scan)))
3362 3222 : CatalogTupleDelete(pgstatistic, &tuple->t_self);
3363 :
3364 49202 : systable_endscan(scan);
3365 :
3366 49202 : table_close(pgstatistic, RowExclusiveLock);
3367 49202 : }
3368 :
3369 :
3370 : /*
3371 : * RelationTruncateIndexes - truncate all indexes associated
3372 : * with the heap relation to zero tuples.
3373 : *
3374 : * The routine will truncate and then reconstruct the indexes on
3375 : * the specified relation. Caller must hold exclusive lock on rel.
3376 : */
3377 : static void
3378 576 : RelationTruncateIndexes(Relation heapRelation)
3379 : {
3380 : ListCell *indlist;
3381 :
3382 : /* Ask the relcache to produce a list of the indexes of the rel */
3383 780 : foreach(indlist, RelationGetIndexList(heapRelation))
3384 : {
3385 204 : Oid indexId = lfirst_oid(indlist);
3386 : Relation currentIndex;
3387 : IndexInfo *indexInfo;
3388 :
3389 : /* Open the index relation; use exclusive lock, just to be sure */
3390 204 : currentIndex = index_open(indexId, AccessExclusiveLock);
3391 :
3392 : /*
3393 : * Fetch info needed for index_build. Since we know there are no
3394 : * tuples that actually need indexing, we can use a dummy IndexInfo.
3395 : * This is slightly cheaper to build, but the real point is to avoid
3396 : * possibly running user-defined code in index expressions or
3397 : * predicates. We might be getting invoked during ON COMMIT
3398 : * processing, and we don't want to run any such code then.
3399 : */
3400 204 : indexInfo = BuildDummyIndexInfo(currentIndex);
3401 :
3402 : /*
3403 : * Now truncate the actual file (and discard buffers).
3404 : */
3405 204 : RelationTruncate(currentIndex, 0);
3406 :
3407 : /* Initialize the index and rebuild */
3408 : /* Note: we do not need to re-establish pkey setting */
3409 204 : index_build(heapRelation, currentIndex, indexInfo, true, false);
3410 :
3411 : /* We're done with this index */
3412 204 : index_close(currentIndex, NoLock);
3413 : }
3414 576 : }
3415 :
3416 : /*
3417 : * heap_truncate
3418 : *
3419 : * This routine deletes all data within all the specified relations.
3420 : *
3421 : * This is not transaction-safe! There is another, transaction-safe
3422 : * implementation in commands/tablecmds.c. We now use this only for
3423 : * ON COMMIT truncation of temporary tables, where it doesn't matter.
3424 : */
3425 : void
3426 334 : heap_truncate(List *relids)
3427 : {
3428 334 : List *relations = NIL;
3429 : ListCell *cell;
3430 :
3431 : /* Open relations for processing, and grab exclusive access on each */
3432 734 : foreach(cell, relids)
3433 : {
3434 400 : Oid rid = lfirst_oid(cell);
3435 : Relation rel;
3436 :
3437 400 : rel = table_open(rid, AccessExclusiveLock);
3438 400 : relations = lappend(relations, rel);
3439 : }
3440 :
3441 : /* Don't allow truncate on tables that are referenced by foreign keys */
3442 334 : heap_truncate_check_FKs(relations, true);
3443 :
3444 : /* OK to do it */
3445 716 : foreach(cell, relations)
3446 : {
3447 388 : Relation rel = lfirst(cell);
3448 :
3449 : /* Truncate the relation */
3450 388 : heap_truncate_one_rel(rel);
3451 :
3452 : /* Close the relation, but keep exclusive lock on it until commit */
3453 388 : table_close(rel, NoLock);
3454 : }
3455 328 : }
3456 :
3457 : /*
3458 : * heap_truncate_one_rel
3459 : *
3460 : * This routine deletes all data within the specified relation.
3461 : *
3462 : * This is not transaction-safe, because the truncation is done immediately
3463 : * and cannot be rolled back later. Caller is responsible for having
3464 : * checked permissions etc, and must have obtained AccessExclusiveLock.
3465 : */
3466 : void
3467 478 : heap_truncate_one_rel(Relation rel)
3468 : {
3469 : Oid toastrelid;
3470 :
3471 : /*
3472 : * Truncate the relation. Partitioned tables have no storage, so there is
3473 : * nothing to do for them here.
3474 : */
3475 478 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
3476 24 : return;
3477 :
3478 : /* Truncate the underlying relation */
3479 454 : table_relation_nontransactional_truncate(rel);
3480 :
3481 : /* If the relation has indexes, truncate the indexes too */
3482 454 : RelationTruncateIndexes(rel);
3483 :
3484 : /* If there is a toast table, truncate that too */
3485 454 : toastrelid = rel->rd_rel->reltoastrelid;
3486 454 : if (OidIsValid(toastrelid))
3487 : {
3488 122 : Relation toastrel = table_open(toastrelid, AccessExclusiveLock);
3489 :
3490 122 : table_relation_nontransactional_truncate(toastrel);
3491 122 : RelationTruncateIndexes(toastrel);
3492 : /* keep the lock... */
3493 122 : table_close(toastrel, NoLock);
3494 : }
3495 : }
3496 :
3497 : /*
3498 : * heap_truncate_check_FKs
3499 : * Check for foreign keys referencing a list of relations that
3500 : * are to be truncated, and raise error if there are any
3501 : *
3502 : * We disallow such FKs (except self-referential ones) since the whole point
3503 : * of TRUNCATE is to not scan the individual rows to be thrown away.
3504 : *
3505 : * This is split out so it can be shared by both implementations of truncate.
3506 : * Caller should already hold a suitable lock on the relations.
3507 : *
3508 : * tempTables is only used to select an appropriate error message.
3509 : */
3510 : void
3511 1900 : heap_truncate_check_FKs(List *relations, bool tempTables)
3512 : {
3513 1900 : List *oids = NIL;
3514 : List *dependents;
3515 : ListCell *cell;
3516 :
3517 : /*
3518 : * Build a list of OIDs of the interesting relations.
3519 : *
3520 : * If a relation has no triggers, then it can neither have FKs nor be
3521 : * referenced by a FK from another table, so we can ignore it. For
3522 : * partitioned tables, FKs have no triggers, so we must include them
3523 : * anyway.
3524 : */
3525 6010 : foreach(cell, relations)
3526 : {
3527 4110 : Relation rel = lfirst(cell);
3528 :
3529 4110 : if (rel->rd_rel->relhastriggers ||
3530 2722 : rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
3531 1872 : oids = lappend_oid(oids, RelationGetRelid(rel));
3532 : }
3533 :
3534 : /*
3535 : * Fast path: if no relation has triggers, none has FKs either.
3536 : */
3537 1900 : if (oids == NIL)
3538 1176 : return;
3539 :
3540 : /*
3541 : * Otherwise, must scan pg_constraint. We make one pass with all the
3542 : * relations considered; if this finds nothing, then all is well.
3543 : */
3544 724 : dependents = heap_truncate_find_FKs(oids);
3545 724 : if (dependents == NIL)
3546 644 : return;
3547 :
3548 : /*
3549 : * Otherwise we repeat the scan once per relation to identify a particular
3550 : * pair of relations to complain about. This is pretty slow, but
3551 : * performance shouldn't matter much in a failure path. The reason for
3552 : * doing things this way is to ensure that the message produced is not
3553 : * dependent on chance row locations within pg_constraint.
3554 : */
3555 104 : foreach(cell, oids)
3556 : {
3557 104 : Oid relid = lfirst_oid(cell);
3558 : ListCell *cell2;
3559 :
3560 104 : dependents = heap_truncate_find_FKs(list_make1_oid(relid));
3561 :
3562 164 : foreach(cell2, dependents)
3563 : {
3564 140 : Oid relid2 = lfirst_oid(cell2);
3565 :
3566 140 : if (!list_member_oid(oids, relid2))
3567 : {
3568 80 : char *relname = get_rel_name(relid);
3569 80 : char *relname2 = get_rel_name(relid2);
3570 :
3571 80 : if (tempTables)
3572 6 : ereport(ERROR,
3573 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3574 : errmsg("unsupported ON COMMIT and foreign key combination"),
3575 : errdetail("Table \"%s\" references \"%s\", but they do not have the same ON COMMIT setting.",
3576 : relname2, relname)));
3577 : else
3578 74 : ereport(ERROR,
3579 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3580 : errmsg("cannot truncate a table referenced in a foreign key constraint"),
3581 : errdetail("Table \"%s\" references \"%s\".",
3582 : relname2, relname),
3583 : errhint("Truncate table \"%s\" at the same time, "
3584 : "or use TRUNCATE ... CASCADE.",
3585 : relname2)));
3586 : }
3587 : }
3588 : }
3589 : }
3590 :
3591 : /*
3592 : * heap_truncate_find_FKs
3593 : * Find relations having foreign keys referencing any of the given rels
3594 : *
3595 : * Input and result are both lists of relation OIDs. The result contains
3596 : * no duplicates, does *not* include any rels that were already in the input
3597 : * list, and is sorted in OID order. (The last property is enforced mainly
3598 : * to guarantee consistent behavior in the regression tests; we don't want
3599 : * behavior to change depending on chance locations of rows in pg_constraint.)
3600 : *
3601 : * Note: caller should already have appropriate lock on all rels mentioned
3602 : * in relationIds. Since adding or dropping an FK requires exclusive lock
3603 : * on both rels, this ensures that the answer will be stable.
3604 : */
3605 : List *
3606 908 : heap_truncate_find_FKs(List *relationIds)
3607 : {
3608 908 : List *result = NIL;
3609 : List *oids;
3610 : List *parent_cons;
3611 : ListCell *cell;
3612 : ScanKeyData key;
3613 : Relation fkeyRel;
3614 : SysScanDesc fkeyScan;
3615 : HeapTuple tuple;
3616 : bool restart;
3617 :
3618 908 : oids = list_copy(relationIds);
3619 :
3620 : /*
3621 : * Must scan pg_constraint. Right now, it is a seqscan because there is
3622 : * no available index on confrelid.
3623 : */
3624 908 : fkeyRel = table_open(ConstraintRelationId, AccessShareLock);
3625 :
3626 932 : restart:
3627 932 : restart = false;
3628 932 : parent_cons = NIL;
3629 :
3630 932 : fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
3631 : NULL, 0, NULL);
3632 :
3633 424910 : while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
3634 : {
3635 423978 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
3636 :
3637 : /* Not a foreign key */
3638 423978 : if (con->contype != CONSTRAINT_FOREIGN)
3639 387664 : continue;
3640 :
3641 : /* Not referencing one of our list of tables */
3642 36314 : if (!list_member_oid(oids, con->confrelid))
3643 35188 : continue;
3644 :
3645 : /*
3646 : * If this constraint has a parent constraint which we have not seen
3647 : * yet, keep track of it for the second loop, below. Tracking parent
3648 : * constraints allows us to climb up to the top-level constraint and
3649 : * look for all possible relations referencing the partitioned table.
3650 : */
3651 1126 : if (OidIsValid(con->conparentid) &&
3652 384 : !list_member_oid(parent_cons, con->conparentid))
3653 168 : parent_cons = lappend_oid(parent_cons, con->conparentid);
3654 :
3655 : /*
3656 : * Add referencer to result, unless present in input list. (Don't
3657 : * worry about dupes: we'll fix that below).
3658 : */
3659 1126 : if (!list_member_oid(relationIds, con->conrelid))
3660 500 : result = lappend_oid(result, con->conrelid);
3661 : }
3662 :
3663 932 : systable_endscan(fkeyScan);
3664 :
3665 : /*
3666 : * Process each parent constraint we found to add the list of referenced
3667 : * relations by them to the oids list. If we do add any new such
3668 : * relations, redo the first loop above. Also, if we see that the parent
3669 : * constraint in turn has a parent, add that so that we process all
3670 : * relations in a single additional pass.
3671 : */
3672 1112 : foreach(cell, parent_cons)
3673 : {
3674 180 : Oid parent = lfirst_oid(cell);
3675 :
3676 180 : ScanKeyInit(&key,
3677 : Anum_pg_constraint_oid,
3678 : BTEqualStrategyNumber, F_OIDEQ,
3679 : ObjectIdGetDatum(parent));
3680 :
3681 180 : fkeyScan = systable_beginscan(fkeyRel, ConstraintOidIndexId,
3682 : true, NULL, 1, &key);
3683 :
3684 180 : tuple = systable_getnext(fkeyScan);
3685 180 : if (HeapTupleIsValid(tuple))
3686 : {
3687 180 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
3688 :
3689 : /*
3690 : * pg_constraint rows always appear for partitioned hierarchies
3691 : * this way: on the each side of the constraint, one row appears
3692 : * for each partition that points to the top-most table on the
3693 : * other side.
3694 : *
3695 : * Because of this arrangement, we can correctly catch all
3696 : * relevant relations by adding to 'parent_cons' all rows with
3697 : * valid conparentid, and to the 'oids' list all rows with a zero
3698 : * conparentid. If any oids are added to 'oids', redo the first
3699 : * loop above by setting 'restart'.
3700 : */
3701 180 : if (OidIsValid(con->conparentid))
3702 54 : parent_cons = list_append_unique_oid(parent_cons,
3703 : con->conparentid);
3704 126 : else if (!list_member_oid(oids, con->confrelid))
3705 : {
3706 24 : oids = lappend_oid(oids, con->confrelid);
3707 24 : restart = true;
3708 : }
3709 : }
3710 :
3711 180 : systable_endscan(fkeyScan);
3712 : }
3713 :
3714 932 : list_free(parent_cons);
3715 932 : if (restart)
3716 24 : goto restart;
3717 :
3718 908 : table_close(fkeyRel, AccessShareLock);
3719 908 : list_free(oids);
3720 :
3721 : /* Now sort and de-duplicate the result list */
3722 908 : list_sort(result, list_oid_cmp);
3723 908 : list_deduplicate_oid(result);
3724 :
3725 908 : return result;
3726 : }
3727 :
3728 : /*
3729 : * StorePartitionKey
3730 : * Store information about the partition key rel into the catalog
3731 : */
3732 : void
3733 4652 : StorePartitionKey(Relation rel,
3734 : char strategy,
3735 : int16 partnatts,
3736 : AttrNumber *partattrs,
3737 : List *partexprs,
3738 : Oid *partopclass,
3739 : Oid *partcollation)
3740 : {
3741 : int i;
3742 : int2vector *partattrs_vec;
3743 : oidvector *partopclass_vec;
3744 : oidvector *partcollation_vec;
3745 : Datum partexprDatum;
3746 : Relation pg_partitioned_table;
3747 : HeapTuple tuple;
3748 : Datum values[Natts_pg_partitioned_table];
3749 4652 : bool nulls[Natts_pg_partitioned_table] = {0};
3750 : ObjectAddress myself;
3751 : ObjectAddress referenced;
3752 : ObjectAddresses *addrs;
3753 :
3754 : Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3755 :
3756 : /* Copy the partition attribute numbers, opclass OIDs into arrays */
3757 4652 : partattrs_vec = buildint2vector(partattrs, partnatts);
3758 4652 : partopclass_vec = buildoidvector(partopclass, partnatts);
3759 4652 : partcollation_vec = buildoidvector(partcollation, partnatts);
3760 :
3761 : /* Convert the expressions (if any) to a text datum */
3762 4652 : if (partexprs)
3763 : {
3764 : char *exprString;
3765 :
3766 214 : exprString = nodeToString(partexprs);
3767 214 : partexprDatum = CStringGetTextDatum(exprString);
3768 214 : pfree(exprString);
3769 : }
3770 : else
3771 4438 : partexprDatum = (Datum) 0;
3772 :
3773 4652 : pg_partitioned_table = table_open(PartitionedRelationId, RowExclusiveLock);
3774 :
3775 : /* Only this can ever be NULL */
3776 4652 : if (!partexprDatum)
3777 4438 : nulls[Anum_pg_partitioned_table_partexprs - 1] = true;
3778 :
3779 4652 : values[Anum_pg_partitioned_table_partrelid - 1] = ObjectIdGetDatum(RelationGetRelid(rel));
3780 4652 : values[Anum_pg_partitioned_table_partstrat - 1] = CharGetDatum(strategy);
3781 4652 : values[Anum_pg_partitioned_table_partnatts - 1] = Int16GetDatum(partnatts);
3782 4652 : values[Anum_pg_partitioned_table_partdefid - 1] = ObjectIdGetDatum(InvalidOid);
3783 4652 : values[Anum_pg_partitioned_table_partattrs - 1] = PointerGetDatum(partattrs_vec);
3784 4652 : values[Anum_pg_partitioned_table_partclass - 1] = PointerGetDatum(partopclass_vec);
3785 4652 : values[Anum_pg_partitioned_table_partcollation - 1] = PointerGetDatum(partcollation_vec);
3786 4652 : values[Anum_pg_partitioned_table_partexprs - 1] = partexprDatum;
3787 :
3788 4652 : tuple = heap_form_tuple(RelationGetDescr(pg_partitioned_table), values, nulls);
3789 :
3790 4652 : CatalogTupleInsert(pg_partitioned_table, tuple);
3791 4652 : table_close(pg_partitioned_table, RowExclusiveLock);
3792 :
3793 : /* Mark this relation as dependent on a few things as follows */
3794 4652 : addrs = new_object_addresses();
3795 4652 : ObjectAddressSet(myself, RelationRelationId, RelationGetRelid(rel));
3796 :
3797 : /* Operator class and collation per key column */
3798 9730 : for (i = 0; i < partnatts; i++)
3799 : {
3800 5078 : ObjectAddressSet(referenced, OperatorClassRelationId, partopclass[i]);
3801 5078 : add_exact_object_address(&referenced, addrs);
3802 :
3803 : /* The default collation is pinned, so don't bother recording it */
3804 5078 : if (OidIsValid(partcollation[i]) &&
3805 596 : partcollation[i] != DEFAULT_COLLATION_OID)
3806 : {
3807 120 : ObjectAddressSet(referenced, CollationRelationId, partcollation[i]);
3808 120 : add_exact_object_address(&referenced, addrs);
3809 : }
3810 : }
3811 :
3812 4652 : record_object_address_dependencies(&myself, addrs, DEPENDENCY_NORMAL);
3813 4652 : free_object_addresses(addrs);
3814 :
3815 : /*
3816 : * The partitioning columns are made internally dependent on the table,
3817 : * because we cannot drop any of them without dropping the whole table.
3818 : * (ATExecDropColumn independently enforces that, but it's not bulletproof
3819 : * so we need the dependencies too.)
3820 : */
3821 9730 : for (i = 0; i < partnatts; i++)
3822 : {
3823 5078 : if (partattrs[i] == 0)
3824 232 : continue; /* ignore expressions here */
3825 :
3826 4846 : ObjectAddressSubSet(referenced, RelationRelationId,
3827 : RelationGetRelid(rel), partattrs[i]);
3828 4846 : recordDependencyOn(&referenced, &myself, DEPENDENCY_INTERNAL);
3829 : }
3830 :
3831 : /*
3832 : * Also consider anything mentioned in partition expressions. External
3833 : * references (e.g. functions) get NORMAL dependencies. Table columns
3834 : * mentioned in the expressions are handled the same as plain partitioning
3835 : * columns, i.e. they become internally dependent on the whole table.
3836 : */
3837 4652 : if (partexprs)
3838 214 : recordDependencyOnSingleRelExpr(&myself,
3839 : (Node *) partexprs,
3840 : RelationGetRelid(rel),
3841 : DEPENDENCY_NORMAL,
3842 : DEPENDENCY_INTERNAL,
3843 : true /* reverse the self-deps */ );
3844 :
3845 : /*
3846 : * We must invalidate the relcache so that the next
3847 : * CommandCounterIncrement() will cause the same to be rebuilt using the
3848 : * information in just created catalog entry.
3849 : */
3850 4652 : CacheInvalidateRelcache(rel);
3851 4652 : }
3852 :
3853 : /*
3854 : * RemovePartitionKeyByRelId
3855 : * Remove pg_partitioned_table entry for a relation
3856 : */
3857 : void
3858 3730 : RemovePartitionKeyByRelId(Oid relid)
3859 : {
3860 : Relation rel;
3861 : HeapTuple tuple;
3862 :
3863 3730 : rel = table_open(PartitionedRelationId, RowExclusiveLock);
3864 :
3865 3730 : tuple = SearchSysCache1(PARTRELID, ObjectIdGetDatum(relid));
3866 3730 : if (!HeapTupleIsValid(tuple))
3867 0 : elog(ERROR, "cache lookup failed for partition key of relation %u",
3868 : relid);
3869 :
3870 3730 : CatalogTupleDelete(rel, &tuple->t_self);
3871 :
3872 3730 : ReleaseSysCache(tuple);
3873 3730 : table_close(rel, RowExclusiveLock);
3874 3730 : }
3875 :
3876 : /*
3877 : * StorePartitionBound
3878 : * Update pg_class tuple of rel to store the partition bound and set
3879 : * relispartition to true
3880 : *
3881 : * If this is the default partition, also update the default partition OID in
3882 : * pg_partitioned_table.
3883 : *
3884 : * Also, invalidate the parent's relcache, so that the next rebuild will load
3885 : * the new partition's info into its partition descriptor. If there is a
3886 : * default partition, we must invalidate its relcache entry as well.
3887 : */
3888 : void
3889 9346 : StorePartitionBound(Relation rel, Relation parent, PartitionBoundSpec *bound)
3890 : {
3891 : Relation classRel;
3892 : HeapTuple tuple,
3893 : newtuple;
3894 : Datum new_val[Natts_pg_class];
3895 : bool new_null[Natts_pg_class],
3896 : new_repl[Natts_pg_class];
3897 : Oid defaultPartOid;
3898 :
3899 : /* Update pg_class tuple */
3900 9346 : classRel = table_open(RelationRelationId, RowExclusiveLock);
3901 9346 : tuple = SearchSysCacheCopy1(RELOID,
3902 : ObjectIdGetDatum(RelationGetRelid(rel)));
3903 9346 : if (!HeapTupleIsValid(tuple))
3904 0 : elog(ERROR, "cache lookup failed for relation %u",
3905 : RelationGetRelid(rel));
3906 :
3907 : #ifdef USE_ASSERT_CHECKING
3908 : {
3909 : Form_pg_class classForm;
3910 : bool isnull;
3911 :
3912 : classForm = (Form_pg_class) GETSTRUCT(tuple);
3913 : Assert(!classForm->relispartition);
3914 : (void) SysCacheGetAttr(RELOID, tuple, Anum_pg_class_relpartbound,
3915 : &isnull);
3916 : Assert(isnull);
3917 : }
3918 : #endif
3919 :
3920 : /* Fill in relpartbound value */
3921 9346 : memset(new_val, 0, sizeof(new_val));
3922 9346 : memset(new_null, false, sizeof(new_null));
3923 9346 : memset(new_repl, false, sizeof(new_repl));
3924 9346 : new_val[Anum_pg_class_relpartbound - 1] = CStringGetTextDatum(nodeToString(bound));
3925 9346 : new_null[Anum_pg_class_relpartbound - 1] = false;
3926 9346 : new_repl[Anum_pg_class_relpartbound - 1] = true;
3927 9346 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(classRel),
3928 : new_val, new_null, new_repl);
3929 : /* Also set the flag */
3930 9346 : ((Form_pg_class) GETSTRUCT(newtuple))->relispartition = true;
3931 :
3932 : /*
3933 : * We already checked for no inheritance children, but reset
3934 : * relhassubclass in case it was left over.
3935 : */
3936 9346 : if (rel->rd_rel->relkind == RELKIND_RELATION && rel->rd_rel->relhassubclass)
3937 6 : ((Form_pg_class) GETSTRUCT(newtuple))->relhassubclass = false;
3938 :
3939 9346 : CatalogTupleUpdate(classRel, &newtuple->t_self, newtuple);
3940 9346 : heap_freetuple(newtuple);
3941 9346 : table_close(classRel, RowExclusiveLock);
3942 :
3943 : /*
3944 : * If we're storing bounds for the default partition, update
3945 : * pg_partitioned_table too.
3946 : */
3947 9346 : if (bound->is_default)
3948 518 : update_default_partition_oid(RelationGetRelid(parent),
3949 : RelationGetRelid(rel));
3950 :
3951 : /* Make these updates visible */
3952 9346 : CommandCounterIncrement();
3953 :
3954 : /*
3955 : * The partition constraint for the default partition depends on the
3956 : * partition bounds of every other partition, so we must invalidate the
3957 : * relcache entry for that partition every time a partition is added or
3958 : * removed.
3959 : */
3960 : defaultPartOid =
3961 9346 : get_default_oid_from_partdesc(RelationGetPartitionDesc(parent, true));
3962 9346 : if (OidIsValid(defaultPartOid))
3963 644 : CacheInvalidateRelcacheByRelid(defaultPartOid);
3964 :
3965 9346 : CacheInvalidateRelcache(parent);
3966 9346 : }
|