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