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