Debian Codegraph @

src/backend/catalog/heap.c

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