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