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