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