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