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