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