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