PostgreSQL Source Code  git master
tablecmds.c File Reference
#include "postgres.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/heapam_xlog.h"
#include "access/multixact.h"
#include "access/reloptions.h"
#include "access/relscan.h"
#include "access/tableam.h"
#include "access/sysattr.h"
#include "access/tupconvert.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/objectaccess.h"
#include "catalog/partition.h"
#include "catalog/pg_am.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_depend.h"
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_tablespace.h"
#include "catalog/pg_trigger.h"
#include "catalog/pg_type.h"
#include "catalog/storage.h"
#include "catalog/storage_xlog.h"
#include "catalog/toasting.h"
#include "commands/cluster.h"
#include "commands/comment.h"
#include "commands/defrem.h"
#include "commands/event_trigger.h"
#include "commands/policy.h"
#include "commands/sequence.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "commands/trigger.h"
#include "commands/typecmds.h"
#include "commands/user.h"
#include "executor/executor.h"
#include "foreign/foreign.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/parsenodes.h"
#include "optimizer/optimizer.h"
#include "parser/parse_clause.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_expr.h"
#include "parser/parse_oper.h"
#include "parser/parse_relation.h"
#include "parser/parse_type.h"
#include "parser/parse_utilcmd.h"
#include "parser/parser.h"
#include "partitioning/partbounds.h"
#include "partitioning/partdesc.h"
#include "pgstat.h"
#include "rewrite/rewriteDefine.h"
#include "rewrite/rewriteHandler.h"
#include "rewrite/rewriteManip.h"
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "storage/lock.h"
#include "storage/predicate.h"
#include "storage/smgr.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/partcache.h"
#include "utils/relcache.h"
#include "utils/ruleutils.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/timestamp.h"
#include "utils/typcache.h"
Include dependency graph for tablecmds.c:

Go to the source code of this file.

Data Structures

struct  OnCommitItem
 
struct  AlteredTableInfo
 
struct  NewConstraint
 
struct  NewColumnValue
 
struct  dropmsgstrings
 
struct  DropRelationCallbackState
 
struct  AttachIndexCallbackState
 

Macros

#define AT_PASS_UNSET   -1 /* UNSET will cause ERROR */
 
#define AT_PASS_DROP   0 /* DROP (all flavors) */
 
#define AT_PASS_ALTER_TYPE   1 /* ALTER COLUMN TYPE */
 
#define AT_PASS_OLD_INDEX   2 /* re-add existing indexes */
 
#define AT_PASS_OLD_CONSTR   3 /* re-add existing constraints */
 
#define AT_PASS_ADD_COL   4 /* ADD COLUMN */
 
#define AT_PASS_COL_ATTRS   5 /* set other column attributes */
 
#define AT_PASS_ADD_INDEX   6 /* ADD indexes */
 
#define AT_PASS_ADD_CONSTR   7 /* ADD constraints, defaults */
 
#define AT_PASS_MISC   8 /* other stuff */
 
#define AT_NUM_PASSES   9
 
#define ATT_TABLE   0x0001
 
#define ATT_VIEW   0x0002
 
#define ATT_MATVIEW   0x0004
 
#define ATT_INDEX   0x0008
 
#define ATT_COMPOSITE_TYPE   0x0010
 
#define ATT_FOREIGN_TABLE   0x0020
 
#define ATT_PARTITIONED_INDEX   0x0040
 
#define child_dependency_type(child_is_partition)   ((child_is_partition) ? DEPENDENCY_AUTO : DEPENDENCY_NORMAL)
 

Typedefs

typedef struct OnCommitItem OnCommitItem
 
typedef struct AlteredTableInfo AlteredTableInfo
 
typedef struct NewConstraint NewConstraint
 
typedef struct NewColumnValue NewColumnValue
 

Functions

static void truncate_check_rel (Oid relid, Form_pg_class reltuple)
 
static void truncate_check_activity (Relation rel)
 
static void RangeVarCallbackForTruncate (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
static ListMergeAttributes (List *schema, List *supers, char relpersistence, bool is_partition, List **supconstr)
 
static bool MergeCheckConstraint (List *constraints, char *name, Node *expr)
 
static void MergeAttributesIntoExisting (Relation child_rel, Relation parent_rel)
 
static void MergeConstraintsIntoExisting (Relation child_rel, Relation parent_rel)
 
static void StoreCatalogInheritance (Oid relationId, List *supers, bool child_is_partition)
 
static void StoreCatalogInheritance1 (Oid relationId, Oid parentOid, int32 seqNumber, Relation inhRelation, bool child_is_partition)
 
static int findAttrByName (const char *attributeName, List *schema)
 
static void AlterIndexNamespaces (Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
 
static void AlterSeqNamespaces (Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved, LOCKMODE lockmode)
 
static ObjectAddress ATExecAlterConstraint (Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
 
static ObjectAddress ATExecValidateConstraint (Relation rel, char *constrName, bool recurse, bool recursing, LOCKMODE lockmode)
 
static int transformColumnNameList (Oid relId, List *colList, int16 *attnums, Oid *atttypids)
 
static int transformFkeyGetPrimaryKey (Relation pkrel, Oid *indexOid, List **attnamelist, int16 *attnums, Oid *atttypids, Oid *opclasses)
 
static Oid transformFkeyCheckAttrs (Relation pkrel, int numattrs, int16 *attnums, Oid *opclasses)
 
static void checkFkeyPermissions (Relation rel, int16 *attnums, int natts)
 
static CoercionPathType findFkeyCast (Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
 
static void validateCheckConstraint (Relation rel, HeapTuple constrtup)
 
static void validateForeignKeyConstraint (char *conname, Relation rel, Relation pkrel, Oid pkindOid, Oid constraintOid)
 
static void ATController (AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
 
static void ATPrepCmd (List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
 
static void ATRewriteCatalogs (List **wqueue, LOCKMODE lockmode)
 
static void ATExecCmd (List **wqueue, AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static void ATRewriteTables (AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode)
 
static void ATRewriteTable (AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode)
 
static AlteredTableInfoATGetQueueEntry (List **wqueue, Relation rel)
 
static void ATSimplePermissions (Relation rel, int allowed_targets)
 
static void ATWrongRelkindError (Relation rel, int allowed_targets)
 
static void ATSimpleRecursion (List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode)
 
static void ATCheckPartitionsNotInUse (Relation rel, LOCKMODE lockmode)
 
static void ATTypedTableRecursion (List **wqueue, Relation rel, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static Listfind_typed_table_dependencies (Oid typeOid, const char *typeName, DropBehavior behavior)
 
static void ATPrepAddColumn (List **wqueue, Relation rel, bool recurse, bool recursing, bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static ObjectAddress ATExecAddColumn (List **wqueue, AlteredTableInfo *tab, Relation rel, ColumnDef *colDef, bool recurse, bool recursing, bool if_not_exists, LOCKMODE lockmode)
 
static bool check_for_column_name_collision (Relation rel, const char *colname, bool if_not_exists)
 
static void add_column_datatype_dependency (Oid relid, int32 attnum, Oid typid)
 
static void add_column_collation_dependency (Oid relid, int32 attnum, Oid collid)
 
static void ATPrepDropNotNull (Relation rel, bool recurse, bool recursing)
 
static ObjectAddress ATExecDropNotNull (Relation rel, const char *colName, LOCKMODE lockmode)
 
static void ATPrepSetNotNull (List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
 
static ObjectAddress ATExecSetNotNull (AlteredTableInfo *tab, Relation rel, const char *colName, LOCKMODE lockmode)
 
static void ATExecCheckNotNull (AlteredTableInfo *tab, Relation rel, const char *colName, LOCKMODE lockmode)
 
static bool NotNullImpliedByRelConstraints (Relation rel, Form_pg_attribute attr)
 
static bool ConstraintImpliedByRelConstraint (Relation scanrel, List *testConstraint, List *provenConstraint)
 
static ObjectAddress ATExecColumnDefault (Relation rel, const char *colName, Node *newDefault, LOCKMODE lockmode)
 
static ObjectAddress ATExecAddIdentity (Relation rel, const char *colName, Node *def, LOCKMODE lockmode)
 
static ObjectAddress ATExecSetIdentity (Relation rel, const char *colName, Node *def, LOCKMODE lockmode)
 
static ObjectAddress ATExecDropIdentity (Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode)
 
static void ATPrepSetStatistics (Relation rel, const char *colName, int16 colNum, Node *newValue, LOCKMODE lockmode)
 
static ObjectAddress ATExecSetStatistics (Relation rel, const char *colName, int16 colNum, Node *newValue, LOCKMODE lockmode)
 
static ObjectAddress ATExecSetOptions (Relation rel, const char *colName, Node *options, bool isReset, LOCKMODE lockmode)
 
static ObjectAddress ATExecSetStorage (Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
 
static void ATPrepDropColumn (List **wqueue, Relation rel, bool recurse, bool recursing, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static ObjectAddress ATExecDropColumn (List **wqueue, Relation rel, const char *colName, DropBehavior behavior, bool recurse, bool recursing, bool missing_ok, LOCKMODE lockmode)
 
static ObjectAddress ATExecAddIndex (AlteredTableInfo *tab, Relation rel, IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
 
static ObjectAddress ATExecAddConstraint (List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *newConstraint, bool recurse, bool is_readd, LOCKMODE lockmode)
 
static char * ChooseForeignKeyConstraintNameAddition (List *colnames)
 
static ObjectAddress ATExecAddIndexConstraint (AlteredTableInfo *tab, Relation rel, IndexStmt *stmt, LOCKMODE lockmode)
 
static ObjectAddress ATAddCheckConstraint (List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *constr, bool recurse, bool recursing, bool is_readd, LOCKMODE lockmode)
 
static ObjectAddress ATAddForeignKeyConstraint (List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *fkconstraint, Oid parentConstr, bool recurse, bool recursing, LOCKMODE lockmode)
 
static ObjectAddress addFkRecurseReferenced (List **wqueue, Constraint *fkconstraint, Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr, int numfks, int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators, bool old_check_ok)
 
static void addFkRecurseReferencing (List **wqueue, Constraint *fkconstraint, Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr, int numfks, int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators, bool old_check_ok, LOCKMODE lockmode)
 
static void CloneForeignKeyConstraints (List **wqueue, Relation parentRel, Relation partitionRel)
 
static void CloneFkReferenced (Relation parentRel, Relation partitionRel)
 
static void CloneFkReferencing (List **wqueue, Relation parentRel, Relation partRel)
 
static void createForeignKeyCheckTriggers (Oid myRelOid, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid)
 
static void createForeignKeyActionTriggers (Relation rel, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid)
 
static bool tryAttachPartitionForeignKey (ForeignKeyCacheInfo *fk, Oid partRelid, Oid parentConstrOid, int numfks, AttrNumber *mapped_conkey, AttrNumber *confkey, Oid *conpfeqop)
 
static void ATExecDropConstraint (Relation rel, const char *constrName, DropBehavior behavior, bool recurse, bool recursing, bool missing_ok, LOCKMODE lockmode)
 
static void ATPrepAlterColumnType (List **wqueue, AlteredTableInfo *tab, Relation rel, bool recurse, bool recursing, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static bool ATColumnChangeRequiresRewrite (Node *expr, AttrNumber varattno)
 
static ObjectAddress ATExecAlterColumnType (AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static void RememberConstraintForRebuilding (Oid conoid, AlteredTableInfo *tab)
 
static void RememberIndexForRebuilding (Oid indoid, AlteredTableInfo *tab)
 
static void ATPostAlterTypeCleanup (List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
 
static void ATPostAlterTypeParse (Oid oldId, Oid oldRelId, Oid refRelId, char *cmd, List **wqueue, LOCKMODE lockmode, bool rewrite)
 
static void RebuildConstraintComment (AlteredTableInfo *tab, int pass, Oid objid, Relation rel, List *domname, const char *conname)
 
static void TryReuseIndex (Oid oldId, IndexStmt *stmt)
 
static void TryReuseForeignKey (Oid oldId, Constraint *con)
 
static ObjectAddress ATExecAlterColumnGenericOptions (Relation rel, const char *colName, List *options, LOCKMODE lockmode)
 
static void change_owner_fix_column_acls (Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
 
static void change_owner_recurse_to_sequences (Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
 
static ObjectAddress ATExecClusterOn (Relation rel, const char *indexName, LOCKMODE lockmode)
 
static void ATExecDropCluster (Relation rel, LOCKMODE lockmode)
 
static bool ATPrepChangePersistence (Relation rel, bool toLogged)
 
static void ATPrepSetTableSpace (AlteredTableInfo *tab, Relation rel, const char *tablespacename, LOCKMODE lockmode)
 
static void ATExecSetTableSpace (Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
 
static void ATExecSetTableSpaceNoStorage (Relation rel, Oid newTableSpace)
 
static void ATExecSetRelOptions (Relation rel, List *defList, AlterTableType operation, LOCKMODE lockmode)
 
static void ATExecEnableDisableTrigger (Relation rel, const char *trigname, char fires_when, bool skip_system, LOCKMODE lockmode)
 
static void ATExecEnableDisableRule (Relation rel, const char *rulename, char fires_when, LOCKMODE lockmode)
 
static void ATPrepAddInherit (Relation child_rel)
 
static ObjectAddress ATExecAddInherit (Relation child_rel, RangeVar *parent, LOCKMODE lockmode)
 
static ObjectAddress ATExecDropInherit (Relation rel, RangeVar *parent, LOCKMODE lockmode)
 
static void drop_parent_dependency (Oid relid, Oid refclassid, Oid refobjid, DependencyType deptype)
 
static ObjectAddress ATExecAddOf (Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
 
static void ATExecDropOf (Relation rel, LOCKMODE lockmode)
 
static void ATExecReplicaIdentity (Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode)
 
static void ATExecGenericOptions (Relation rel, List *options)
 
static void ATExecEnableRowSecurity (Relation rel)
 
static void ATExecDisableRowSecurity (Relation rel)
 
static void ATExecForceNoForceRowSecurity (Relation rel, bool force_rls)
 
static void index_copy_data (Relation rel, RelFileNode newrnode)
 
static const char * storage_name (char c)
 
static void RangeVarCallbackForDropRelation (const RangeVar *rel, Oid relOid, Oid oldRelOid, void *arg)
 
static void RangeVarCallbackForAlterRelation (const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
 
static PartitionSpectransformPartitionSpec (Relation rel, PartitionSpec *partspec, char *strategy)
 
static void ComputePartitionAttrs (ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs, List **partexprs, Oid *partopclass, Oid *partcollation, char strategy)
 
static void CreateInheritance (Relation child_rel, Relation parent_rel)
 
static void RemoveInheritance (Relation child_rel, Relation parent_rel)
 
static ObjectAddress ATExecAttachPartition (List **wqueue, Relation rel, PartitionCmd *cmd)
 
static void AttachPartitionEnsureIndexes (Relation rel, Relation attachrel)
 
static void QueuePartitionConstraintValidation (List **wqueue, Relation scanrel, List *partConstraint, bool validate_default)
 
static void CloneRowTriggersToPartition (Relation parent, Relation partition)
 
static ObjectAddress ATExecDetachPartition (Relation rel, RangeVar *name)
 
static ObjectAddress ATExecAttachPartitionIdx (List **wqueue, Relation rel, RangeVar *name)
 
static void validatePartitionedIndex (Relation partedIdx, Relation partedTbl)
 
static void refuseDupeIndexAttach (Relation parentIdx, Relation partIdx, Relation partitionTbl)
 
static ListGetParentedForeignKeyRefs (Relation partition)
 
static void ATDetachCheckNoForeignKeyRefs (Relation partition)
 
ObjectAddress DefineRelation (CreateStmt *stmt, char relkind, Oid ownerId, ObjectAddress *typaddress, const char *queryString)
 
static void DropErrorMsgNonExistent (RangeVar *rel, char rightkind, bool missing_ok)
 
static void DropErrorMsgWrongType (const char *relname, char wrongkind, char rightkind)
 
void RemoveRelations (DropStmt *drop)
 
void ExecuteTruncate (TruncateStmt *stmt)
 
void ExecuteTruncateGuts (List *explicit_rels, List *relids, List *relids_logged, DropBehavior behavior, bool restart_seqs)
 
void SetRelationHasSubclass (Oid relationId, bool relhassubclass)
 
static void renameatt_check (Oid myrelid, Form_pg_class classform, bool recursing)
 
static AttrNumber renameatt_internal (Oid myrelid, const char *oldattname, const char *newattname, bool recurse, bool recursing, int expected_parents, DropBehavior behavior)
 
static void RangeVarCallbackForRenameAttribute (const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
 
ObjectAddress renameatt (RenameStmt *stmt)
 
static ObjectAddress rename_constraint_internal (Oid myrelid, Oid mytypid, const char *oldconname, const char *newconname, bool recurse, bool recursing, int expected_parents)
 
ObjectAddress RenameConstraint (RenameStmt *stmt)
 
ObjectAddress RenameRelation (RenameStmt *stmt)
 
void RenameRelationInternal (Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
 
void CheckTableNotInUse (Relation rel, const char *stmt)
 
Oid AlterTableLookupRelation (AlterTableStmt *stmt, LOCKMODE lockmode)
 
void AlterTable (Oid relid, LOCKMODE lockmode, AlterTableStmt *stmt)
 
void AlterTableInternal (Oid relid, List *cmds, bool recurse)
 
LOCKMODE AlterTableGetLockLevel (List *cmds)
 
void find_composite_type_dependencies (Oid typeOid, Relation origRelation, const char *origTypeName)
 
void check_of_type (HeapTuple typetuple)
 
static void CreateFKCheckTrigger (Oid myRelOid, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid, bool on_insert)
 
void ATExecChangeOwner (Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
 
Oid AlterTableMoveAll (AlterTableMoveAllStmt *stmt)
 
static char * decompile_conbin (HeapTuple contup, TupleDesc tupdesc)
 
static bool constraints_equivalent (HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
 
static void relation_mark_replica_identity (Relation rel, char ri_type, Oid indexOid, bool is_internal)
 
ObjectAddress AlterTableNamespace (AlterObjectSchemaStmt *stmt, Oid *oldschema)
 
void AlterTableNamespaceInternal (Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
 
void AlterRelationNamespaceInternal (Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
 
void register_on_commit_action (Oid relid, OnCommitAction action)
 
void remove_on_commit_action (Oid relid)
 
void PreCommit_on_commit_actions (void)
 
void AtEOXact_on_commit_actions (bool isCommit)
 
void AtEOSubXact_on_commit_actions (bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
 
void RangeVarCallbackOwnsTable (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
void RangeVarCallbackOwnsRelation (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
bool PartConstraintImpliedByRelConstraint (Relation scanrel, List *partConstraint)
 
static void RangeVarCallbackForAttachIndex (const RangeVar *rv, Oid relOid, Oid oldRelOid, void *arg)
 

Variables

static Liston_commits = NIL
 
static const struct dropmsgstrings dropmsgstringarray []
 

Macro Definition Documentation

◆ AT_NUM_PASSES

#define AT_NUM_PASSES   9

Definition at line 151 of file tablecmds.c.

Referenced by ATRewriteCatalogs().

◆ AT_PASS_ADD_COL

#define AT_PASS_ADD_COL   4 /* ADD COLUMN */

Definition at line 146 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ AT_PASS_ADD_CONSTR

#define AT_PASS_ADD_CONSTR   7 /* ADD constraints, defaults */

Definition at line 149 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ AT_PASS_ADD_INDEX

#define AT_PASS_ADD_INDEX   6 /* ADD indexes */

Definition at line 148 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ AT_PASS_ALTER_TYPE

#define AT_PASS_ALTER_TYPE   1 /* ALTER COLUMN TYPE */

Definition at line 142 of file tablecmds.c.

Referenced by ATPrepCmd(), and ATRewriteCatalogs().

◆ AT_PASS_COL_ATTRS

#define AT_PASS_COL_ATTRS   5 /* set other column attributes */

Definition at line 147 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ AT_PASS_DROP

#define AT_PASS_DROP   0 /* DROP (all flavors) */

Definition at line 141 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ AT_PASS_MISC

#define AT_PASS_MISC   8 /* other stuff */

Definition at line 150 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ AT_PASS_OLD_CONSTR

#define AT_PASS_OLD_CONSTR   3 /* re-add existing constraints */

Definition at line 144 of file tablecmds.c.

Referenced by ATPostAlterTypeParse().

◆ AT_PASS_OLD_INDEX

#define AT_PASS_OLD_INDEX   2 /* re-add existing indexes */

Definition at line 143 of file tablecmds.c.

Referenced by ATPostAlterTypeParse().

◆ AT_PASS_UNSET

#define AT_PASS_UNSET   -1 /* UNSET will cause ERROR */

Definition at line 140 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ ATT_COMPOSITE_TYPE

#define ATT_COMPOSITE_TYPE   0x0010

Definition at line 290 of file tablecmds.c.

Referenced by ATPrepCmd(), ATSimplePermissions(), and ATWrongRelkindError().

◆ ATT_FOREIGN_TABLE

◆ ATT_INDEX

#define ATT_INDEX   0x0008

Definition at line 289 of file tablecmds.c.

Referenced by ATPrepCmd(), ATSimplePermissions(), and ATWrongRelkindError().

◆ ATT_MATVIEW

#define ATT_MATVIEW   0x0004

Definition at line 288 of file tablecmds.c.

Referenced by ATPrepCmd(), ATSimplePermissions(), and ATWrongRelkindError().

◆ ATT_PARTITIONED_INDEX

#define ATT_PARTITIONED_INDEX   0x0040

Definition at line 292 of file tablecmds.c.

Referenced by ATPrepCmd(), and ATSimplePermissions().

◆ ATT_TABLE

◆ ATT_VIEW

#define ATT_VIEW   0x0002

Definition at line 287 of file tablecmds.c.

Referenced by ATPrepCmd(), ATSimplePermissions(), and ATWrongRelkindError().

◆ child_dependency_type

#define child_dependency_type (   child_is_partition)    ((child_is_partition) ? DEPENDENCY_AUTO : DEPENDENCY_NORMAL)

Definition at line 299 of file tablecmds.c.

Referenced by RemoveInheritance(), and StoreCatalogInheritance1().

Typedef Documentation

◆ AlteredTableInfo

◆ NewColumnValue

◆ NewConstraint

◆ OnCommitItem

Function Documentation

◆ add_column_collation_dependency()

static void add_column_collation_dependency ( Oid  relid,
int32  attnum,
Oid  collid 
)
static

Definition at line 6027 of file tablecmds.c.

References attnum, ObjectAddress::classId, DEPENDENCY_NORMAL, ObjectAddress::objectId, ObjectAddress::objectSubId, OidIsValid, recordDependencyOn(), and OnCommitItem::relid.

Referenced by ATExecAddColumn(), and ATExecAlterColumnType().

6028 {
6029  ObjectAddress myself,
6030  referenced;
6031 
6032  /* We know the default collation is pinned, so don't bother recording it */
6033  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
6034  {
6035  myself.classId = RelationRelationId;
6036  myself.objectId = relid;
6037  myself.objectSubId = attnum;
6038  referenced.classId = CollationRelationId;
6039  referenced.objectId = collid;
6040  referenced.objectSubId = 0;
6041  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
6042  }
6043 }
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
#define OidIsValid(objectId)
Definition: c.h:638
int16 attnum
Definition: pg_attribute.h:79

◆ add_column_datatype_dependency()

static void add_column_datatype_dependency ( Oid  relid,
int32  attnum,
Oid  typid 
)
static

Definition at line 6009 of file tablecmds.c.

References attnum, ObjectAddress::classId, DEPENDENCY_NORMAL, ObjectAddress::objectId, ObjectAddress::objectSubId, recordDependencyOn(), and OnCommitItem::relid.

Referenced by ATExecAddColumn(), and ATExecAlterColumnType().

6010 {
6011  ObjectAddress myself,
6012  referenced;
6013 
6014  myself.classId = RelationRelationId;
6015  myself.objectId = relid;
6016  myself.objectSubId = attnum;
6017  referenced.classId = TypeRelationId;
6018  referenced.objectId = typid;
6019  referenced.objectSubId = 0;
6020  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
6021 }
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
int16 attnum
Definition: pg_attribute.h:79

◆ addFkRecurseReferenced()

static ObjectAddress addFkRecurseReferenced ( List **  wqueue,
Constraint fkconstraint,
Relation  rel,
Relation  pkrel,
Oid  indexOid,
Oid  parentConstr,
int  numfks,
int16 pkattnum,
int16 fkattnum,
Oid pfeqoperators,
Oid ppeqoperators,
Oid ffeqoperators,
bool  old_check_ok 
)
static

Definition at line 8033 of file tablecmds.c.

References ChooseConstraintName(), ChooseForeignKeyConstraintNameAddition(), CommandCounterIncrement(), Constraint::conname, CONSTRAINT_RELATION, ConstraintNameIsUsed(), convert_tuples_by_name_map_if_req(), CreateConstraintEntry(), createForeignKeyActionTriggers(), Constraint::deferrable, DEPENDENCY_INTERNAL, elog, ereport, errcode(), errmsg(), ERROR, Constraint::fk_attrs, Constraint::fk_del_action, Constraint::fk_matchtype, Constraint::fk_upd_action, gettext_noop, i, index_get_partition(), Constraint::initdeferred, Constraint::initially_valid, InvalidOid, NIL, NoLock, PartitionDescData::nparts, ObjectAddressSet, OidIsValid, PartitionDescData::oids, palloc(), pfree(), RelationData::rd_rel, recordDependencyOn(), RelationGetDescr, RelationGetNamespace, RelationGetPartitionDesc, RelationGetRelationName, RelationGetRelid, ShareRowExclusiveLock, table_close(), and table_open().

Referenced by ATAddForeignKeyConstraint(), and CloneFkReferenced().

8038 {
8039  ObjectAddress address;
8040  Oid constrOid;
8041  char *conname;
8042  bool conislocal;
8043  int coninhcount;
8044  bool connoinherit;
8045 
8046  /*
8047  * Verify relkind for each referenced partition. At the top level, this
8048  * is redundant with a previous check, but we need it when recursing.
8049  */
8050  if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
8051  pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
8052  ereport(ERROR,
8053  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8054  errmsg("referenced relation \"%s\" is not a table",
8055  RelationGetRelationName(pkrel))));
8056 
8057  /*
8058  * Caller supplies us with a constraint name; however, it may be used in
8059  * this partition, so come up with a different one in that case.
8060  */
8062  RelationGetRelid(rel),
8063  fkconstraint->conname))
8066  "fkey",
8067  RelationGetNamespace(rel), NIL);
8068  else
8069  conname = fkconstraint->conname;
8070 
8071  if (OidIsValid(parentConstr))
8072  {
8073  conislocal = false;
8074  coninhcount = 1;
8075  connoinherit = false;
8076  }
8077  else
8078  {
8079  conislocal = true;
8080  coninhcount = 0;
8081 
8082  /*
8083  * always inherit for partitioned tables, never for legacy inheritance
8084  */
8085  connoinherit = rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE;
8086  }
8087 
8088  /*
8089  * Record the FK constraint in pg_constraint.
8090  */
8091  constrOid = CreateConstraintEntry(conname,
8092  RelationGetNamespace(rel),
8093  CONSTRAINT_FOREIGN,
8094  fkconstraint->deferrable,
8095  fkconstraint->initdeferred,
8096  fkconstraint->initially_valid,
8097  parentConstr,
8098  RelationGetRelid(rel),
8099  fkattnum,
8100  numfks,
8101  numfks,
8102  InvalidOid, /* not a domain constraint */
8103  indexOid,
8104  RelationGetRelid(pkrel),
8105  pkattnum,
8106  pfeqoperators,
8107  ppeqoperators,
8108  ffeqoperators,
8109  numfks,
8110  fkconstraint->fk_upd_action,
8111  fkconstraint->fk_del_action,
8112  fkconstraint->fk_matchtype,
8113  NULL, /* no exclusion constraint */
8114  NULL, /* no check constraint */
8115  NULL,
8116  conislocal, /* islocal */
8117  coninhcount, /* inhcount */
8118  connoinherit, /* conNoInherit */
8119  false); /* is_internal */
8120 
8121  ObjectAddressSet(address, ConstraintRelationId, constrOid);
8122 
8123  /*
8124  * Mark the child constraint as part of the parent constraint; it must not
8125  * be dropped on its own. (This constraint is deleted when the partition
8126  * is detached, but a special check needs to occur that the partition
8127  * contains no referenced values.)
8128  */
8129  if (OidIsValid(parentConstr))
8130  {
8131  ObjectAddress referenced;
8132 
8133  ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
8134  recordDependencyOn(&address, &referenced, DEPENDENCY_INTERNAL);
8135  }
8136 
8137  /* make new constraint visible, in case we add more */
8139 
8140  /*
8141  * If the referenced table is a plain relation, create the action triggers
8142  * that enforce the constraint.
8143  */
8144  if (pkrel->rd_rel->relkind == RELKIND_RELATION)
8145  {
8147  fkconstraint,
8148  constrOid, indexOid);
8149  }
8150 
8151  /*
8152  * If the referenced table is partitioned, recurse on ourselves to handle
8153  * each partition. We need one pg_constraint row created for each
8154  * partition in addition to the pg_constraint row for the parent table.
8155  */
8156  if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
8157  {
8159 
8160  for (int i = 0; i < pd->nparts; i++)
8161  {
8162  Relation partRel;
8163  AttrNumber *map;
8164  AttrNumber *mapped_pkattnum;
8165  Oid partIndexId;
8166 
8167  partRel = table_open(pd->oids[i], ShareRowExclusiveLock);
8168 
8169  /*
8170  * Map the attribute numbers in the referenced side of the FK
8171  * definition to match the partition's column layout.
8172  */
8174  RelationGetDescr(pkrel),
8175  gettext_noop("could not convert row type"));
8176  if (map)
8177  {
8178  mapped_pkattnum = palloc(sizeof(AttrNumber) * numfks);
8179  for (int j = 0; j < numfks; j++)
8180  mapped_pkattnum[j] = map[pkattnum[j] - 1];
8181  }
8182  else
8183  mapped_pkattnum = pkattnum;
8184 
8185  /* do the deed */
8186  partIndexId = index_get_partition(partRel, indexOid);
8187  if (!OidIsValid(partIndexId))
8188  elog(ERROR, "index for %u not found in partition %s",
8189  indexOid, RelationGetRelationName(partRel));
8190  addFkRecurseReferenced(wqueue, fkconstraint, rel, partRel,
8191  partIndexId, constrOid, numfks,
8192  mapped_pkattnum, fkattnum,
8193  pfeqoperators, ppeqoperators, ffeqoperators,
8194  old_check_ok);
8195 
8196  /* Done -- clean up (but keep the lock) */
8197  table_close(partRel, NoLock);
8198  if (map)
8199  {
8200  pfree(mapped_pkattnum);
8201  pfree(map);
8202  }
8203  }
8204  }
8205 
8206  return address;
8207 }
#define NIL
Definition: pg_list.h:65
Oid index_get_partition(Relation partition, Oid indexId)
Definition: partition.c:154
char * ChooseConstraintName(const char *name1, const char *name2, const char *label, Oid namespaceid, List *others)
bool ConstraintNameIsUsed(ConstraintCategory conCat, Oid objId, const char *conname)
static char * ChooseForeignKeyConstraintNameAddition(List *colnames)
Definition: tablecmds.c:7416
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define RelationGetDescr(relation)
Definition: rel.h:442
char fk_matchtype
Definition: parsenodes.h:2166
Oid CreateConstraintEntry(const char *constraintName, Oid constraintNamespace, char constraintType, bool isDeferrable, bool isDeferred, bool isValidated, Oid parentConstrId, Oid relId, const int16 *constraintKey, int constraintNKeys, int constraintNTotalKeys, Oid domainId, Oid indexRelId, Oid foreignRelId, const int16 *foreignKey, const Oid *pfEqOp, const Oid *ppEqOp, const Oid *ffEqOp, int foreignNKeys, char foreignUpdateType, char foreignDeleteType, char foreignMatchType, const Oid *exclOp, Node *conExpr, const char *conBin, bool conIsLocal, int conInhCount, bool conNoInherit, bool is_internal)
Definition: pg_constraint.c:51
#define gettext_noop(x)
Definition: c.h:1117
int errcode(int sqlerrcode)
Definition: elog.c:570
bool initdeferred
Definition: parsenodes.h:2134
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
char * conname
Definition: parsenodes.h:2132
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
AttrNumber * convert_tuples_by_name_map_if_req(TupleDesc indesc, TupleDesc outdesc, const char *msg)
Definition: tupconvert.c:329
void pfree(void *pointer)
Definition: mcxt.c:1031
static ObjectAddress addFkRecurseReferenced(List **wqueue, Constraint *fkconstraint, Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr, int numfks, int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators, bool old_check_ok)
Definition: tablecmds.c:8033
#define ERROR
Definition: elog.h:43
bool deferrable
Definition: parsenodes.h:2133
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:450
#define ereport(elevel, rest)
Definition: elog.h:141
static void createForeignKeyActionTriggers(Relation rel, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid)
Definition: tablecmds.c:9864
void CommandCounterIncrement(void)
Definition: xact.c:1003
#define InvalidOid
Definition: postgres_ext.h:36
bool initially_valid
Definition: parsenodes.h:2175
char fk_del_action
Definition: parsenodes.h:2168
#define ShareRowExclusiveLock
Definition: lockdefs.h:42
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
int i
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:416
List * fk_attrs
Definition: parsenodes.h:2164
char fk_upd_action
Definition: parsenodes.h:2167
#define RelationGetPartitionDesc(relation)
Definition: rel.h:603
#define RelationGetNamespace(relation)
Definition: rel.h:457

◆ addFkRecurseReferencing()

static void addFkRecurseReferencing ( List **  wqueue,
Constraint fkconstraint,
Relation  rel,
Relation  pkrel,
Oid  indexOid,
Oid  parentConstr,
int  numfks,
int16 pkattnum,
int16 fkattnum,
Oid pfeqoperators,
Oid ppeqoperators,
Oid ffeqoperators,
bool  old_check_ok,
LOCKMODE  lockmode 
)
static

Definition at line 8239 of file tablecmds.c.

References AssertArg, ATGetQueueEntry(), CheckTableNotInUse(), ChooseConstraintName(), ChooseForeignKeyConstraintNameAddition(), CommandCounterIncrement(), NewConstraint::conid, Constraint::conname, CONSTR_FOREIGN, CONSTRAINT_RELATION, ConstraintNameIsUsed(), AlteredTableInfo::constraints, NewConstraint::contype, convert_tuples_by_name_map(), copyObject, CreateConstraintEntry(), createForeignKeyCheckTriggers(), Constraint::deferrable, DEPENDENCY_PARTITION_PRI, DEPENDENCY_PARTITION_SEC, ereport, errcode(), errmsg(), ERROR, Constraint::fk_attrs, Constraint::fk_del_action, Constraint::fk_matchtype, Constraint::fk_upd_action, get_constraint_name(), gettext_noop, i, INDEX_MAX_KEYS, Constraint::initdeferred, Constraint::initially_valid, InvalidOid, lappend(), lfirst_node, NewConstraint::name, NIL, NoLock, PartitionDescData::nparts, ObjectAddressSet, OidIsValid, PartitionDescData::oids, palloc0(), NewConstraint::qual, RelationData::rd_rel, recordDependencyOn(), NewConstraint::refindid, NewConstraint::refrelid, RelationGetDescr, RelationGetFKeyList(), RelationGetNamespace, RelationGetPartitionDesc, RelationGetRelationName, RelationGetRelid, Constraint::skip_validation, table_close(), table_open(), and tryAttachPartitionForeignKey().

Referenced by ATAddForeignKeyConstraint(), and CloneFkReferencing().

8244 {
8245  AssertArg(OidIsValid(parentConstr));
8246 
8247  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
8248  ereport(ERROR,
8249  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8250  errmsg("foreign key constraints are not supported on foreign tables")));
8251 
8252  /*
8253  * If the referencing relation is a plain table, add the check triggers to
8254  * it and, if necessary, schedule it to be checked in Phase 3.
8255  *
8256  * If the relation is partitioned, drill down to do it to its partitions.
8257  */
8258  if (rel->rd_rel->relkind == RELKIND_RELATION)
8259  {
8261  RelationGetRelid(pkrel),
8262  fkconstraint,
8263  parentConstr,
8264  indexOid);
8265 
8266  /*
8267  * Tell Phase 3 to check that the constraint is satisfied by existing
8268  * rows. We can skip this during table creation, when requested
8269  * explicitly by specifying NOT VALID in an ADD FOREIGN KEY command,
8270  * and when we're recreating a constraint following a SET DATA TYPE
8271  * operation that did not impugn its validity.
8272  */
8273  if (wqueue && !old_check_ok && !fkconstraint->skip_validation)
8274  {
8275  NewConstraint *newcon;
8276  AlteredTableInfo *tab;
8277 
8278  tab = ATGetQueueEntry(wqueue, rel);
8279 
8280  newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
8281  newcon->name = get_constraint_name(parentConstr);
8282  newcon->contype = CONSTR_FOREIGN;
8283  newcon->refrelid = RelationGetRelid(pkrel);
8284  newcon->refindid = indexOid;
8285  newcon->conid = parentConstr;
8286  newcon->qual = (Node *) fkconstraint;
8287 
8288  tab->constraints = lappend(tab->constraints, newcon);
8289  }
8290  }
8291  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
8292  {
8294 
8295  /*
8296  * Recurse to take appropriate action on each partition; either we
8297  * find an existing constraint to reparent to ours, or we create a new
8298  * one.
8299  */
8300  for (int i = 0; i < pd->nparts; i++)
8301  {
8302  Oid partitionId = pd->oids[i];
8303  Relation partition = table_open(partitionId, lockmode);
8304  List *partFKs;
8305  AttrNumber *attmap;
8306  AttrNumber mapped_fkattnum[INDEX_MAX_KEYS];
8307  bool attached;
8308  char *conname;
8309  Oid constrOid;
8310  ObjectAddress address,
8311  referenced;
8312  ListCell *cell;
8313 
8314  CheckTableNotInUse(partition, "ALTER TABLE");
8315 
8316  attmap = convert_tuples_by_name_map(RelationGetDescr(partition),
8317  RelationGetDescr(rel),
8318  gettext_noop("could not convert row type"));
8319  for (int j = 0; j < numfks; j++)
8320  mapped_fkattnum[j] = attmap[fkattnum[j] - 1];
8321 
8322  /* Check whether an existing constraint can be repurposed */
8323  partFKs = copyObject(RelationGetFKeyList(partition));
8324  attached = false;
8325  foreach(cell, partFKs)
8326  {
8327  ForeignKeyCacheInfo *fk;
8328 
8329  fk = lfirst_node(ForeignKeyCacheInfo, cell);
8331  partitionId,
8332  parentConstr,
8333  numfks,
8334  mapped_fkattnum,
8335  pkattnum,
8336  pfeqoperators))
8337  {
8338  attached = true;
8339  break;
8340  }
8341  }
8342  if (attached)
8343  {
8344  table_close(partition, NoLock);
8345  continue;
8346  }
8347 
8348  /*
8349  * No luck finding a good constraint to reuse; create our own.
8350  */
8352  RelationGetRelid(partition),
8353  fkconstraint->conname))
8354  conname = ChooseConstraintName(RelationGetRelationName(partition),
8356  "fkey",
8357  RelationGetNamespace(partition), NIL);
8358  else
8359  conname = fkconstraint->conname;
8360  constrOid =
8361  CreateConstraintEntry(conname,
8362  RelationGetNamespace(partition),
8363  CONSTRAINT_FOREIGN,
8364  fkconstraint->deferrable,
8365  fkconstraint->initdeferred,
8366  fkconstraint->initially_valid,
8367  parentConstr,
8368  partitionId,
8369  mapped_fkattnum,
8370  numfks,
8371  numfks,
8372  InvalidOid,
8373  indexOid,
8374  RelationGetRelid(pkrel),
8375  pkattnum,
8376  pfeqoperators,
8377  ppeqoperators,
8378  ffeqoperators,
8379  numfks,
8380  fkconstraint->fk_upd_action,
8381  fkconstraint->fk_del_action,
8382  fkconstraint->fk_matchtype,
8383  NULL,
8384  NULL,
8385  NULL,
8386  false,
8387  1,
8388  false,
8389  false);
8390 
8391  /*
8392  * Give this constraint partition-type dependencies on the parent
8393  * constraint as well as the table.
8394  */
8395  ObjectAddressSet(address, ConstraintRelationId, constrOid);
8396  ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
8397  recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_PRI);
8398  ObjectAddressSet(referenced, RelationRelationId, partitionId);
8399  recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_SEC);
8400 
8401  /* Make all this visible before recursing */
8403 
8404  /* call ourselves to finalize the creation and we're done */
8405  addFkRecurseReferencing(wqueue, fkconstraint, partition, pkrel,
8406  indexOid,
8407  constrOid,
8408  numfks,
8409  pkattnum,
8410  mapped_fkattnum,
8411  pfeqoperators,
8412  ppeqoperators,
8413  ffeqoperators,
8414  old_check_ok,
8415  lockmode);
8416 
8417  table_close(partition, NoLock);
8418  }
8419  }
8420 }
#define NIL
Definition: pg_list.h:65
char * ChooseConstraintName(const char *name1, const char *name2, const char *label, Oid namespaceid, List *others)
static void createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid)
Definition: tablecmds.c:9985
bool ConstraintNameIsUsed(ConstraintCategory conCat, Oid objId, const char *conname)
char * name
Definition: tablecmds.c:183
static char * ChooseForeignKeyConstraintNameAddition(List *colnames)
Definition: tablecmds.c:7416
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define RelationGetDescr(relation)
Definition: rel.h:442
char * get_constraint_name(Oid conoid)
Definition: lsyscache.c:969
static void addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint, Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr, int numfks, int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators, bool old_check_ok, LOCKMODE lockmode)
Definition: tablecmds.c:8239
char fk_matchtype
Definition: parsenodes.h:2166
Oid CreateConstraintEntry(const char *constraintName, Oid constraintNamespace, char constraintType, bool isDeferrable, bool isDeferred, bool isValidated, Oid parentConstrId, Oid relId, const int16 *constraintKey, int constraintNKeys, int constraintNTotalKeys, Oid domainId, Oid indexRelId, Oid foreignRelId, const int16 *foreignKey, const Oid *pfEqOp, const Oid *ppEqOp, const Oid *ffEqOp, int foreignNKeys, char foreignUpdateType, char foreignDeleteType, char foreignMatchType, const Oid *exclOp, Node *conExpr, const char *conBin, bool conIsLocal, int conInhCount, bool conNoInherit, bool is_internal)
Definition: pg_constraint.c:51
Node * qual
Definition: tablecmds.c:188
#define gettext_noop(x)
Definition: c.h:1117
Definition: nodes.h:524
int errcode(int sqlerrcode)
Definition: elog.c:570
bool initdeferred
Definition: parsenodes.h:2134
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
char * conname
Definition: parsenodes.h:2132
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
List * constraints
Definition: tablecmds.c:162
static bool tryAttachPartitionForeignKey(ForeignKeyCacheInfo *fk, Oid partRelid, Oid parentConstrOid, int numfks, AttrNumber *mapped_conkey, AttrNumber *confkey, Oid *conpfeqop)
Definition: tablecmds.c:8832
#define ERROR
Definition: elog.h:43
bool deferrable
Definition: parsenodes.h:2133
#define lfirst_node(type, lc)
Definition: pg_list.h:193
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:450
static AlteredTableInfo * ATGetQueueEntry(List **wqueue, Relation rel)
Definition: tablecmds.c:5071
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3416
#define ereport(elevel, rest)
Definition: elog.h:141
#define AssertArg(condition)
Definition: c.h:734
List * lappend(List *list, void *datum)
Definition: list.c:321
ConstrType contype
Definition: tablecmds.c:184
AttrNumber * convert_tuples_by_name_map(TupleDesc indesc, TupleDesc outdesc, const char *msg)
Definition: tupconvert.c:246
void * palloc0(Size size)
Definition: mcxt.c:955
void CommandCounterIncrement(void)
Definition: xact.c:1003
#define InvalidOid
Definition: postgres_ext.h:36
bool initially_valid
Definition: parsenodes.h:2175
char fk_del_action
Definition: parsenodes.h:2168
#define INDEX_MAX_KEYS
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
List * RelationGetFKeyList(Relation relation)
Definition: relcache.c:4239
int errmsg(const char *fmt,...)
Definition: elog.c:784
int i
#define copyObject(obj)
Definition: nodes.h:640
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
bool skip_validation
Definition: parsenodes.h:2174
#define RelationGetRelid(relation)
Definition: rel.h:416
List * fk_attrs
Definition: parsenodes.h:2164
char fk_upd_action
Definition: parsenodes.h:2167
#define RelationGetPartitionDesc(relation)
Definition: rel.h:603
#define RelationGetNamespace(relation)
Definition: rel.h:457

◆ AlterIndexNamespaces()

static void AlterIndexNamespaces ( Relation  classRel,
Relation  rel,
Oid  oldNspOid,
Oid  newNspOid,
ObjectAddresses objsMoved 
)
static

Definition at line 14362 of file tablecmds.c.

References add_exact_object_address(), AlterRelationNamespaceInternal(), ObjectAddress::classId, lfirst_oid, list_free(), object_address_present(), ObjectAddress::objectId, ObjectAddress::objectSubId, and RelationGetIndexList().

Referenced by AlterTableNamespaceInternal().

14364 {
14365  List *indexList;
14366  ListCell *l;
14367 
14368  indexList = RelationGetIndexList(rel);
14369 
14370  foreach(l, indexList)
14371  {
14372  Oid indexOid = lfirst_oid(l);
14373  ObjectAddress thisobj;
14374 
14375  thisobj.classId = RelationRelationId;
14376  thisobj.objectId = indexOid;
14377  thisobj.objectSubId = 0;
14378 
14379  /*
14380  * Note: currently, the index will not have its own dependency on the
14381  * namespace, so we don't need to do changeDependencyFor(). There's no
14382  * row type in pg_type, either.
14383  *
14384  * XXX this objsMoved test may be pointless -- surely we have a single
14385  * dependency link from a relation to each index?
14386  */
14387  if (!object_address_present(&thisobj, objsMoved))
14388  {
14389  AlterRelationNamespaceInternal(classRel, indexOid,
14390  oldNspOid, newNspOid,
14391  false, objsMoved);
14392  add_exact_object_address(&thisobj, objsMoved);
14393  }
14394  }
14395 
14396  list_free(indexList);
14397 }
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2500
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2440
unsigned int Oid
Definition: postgres_ext.h:31
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:14292
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4348
void list_free(List *list)
Definition: list.c:1373
Definition: pg_list.h:50
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ AlterRelationNamespaceInternal()

void AlterRelationNamespaceInternal ( Relation  classRel,
Oid  relOid,
Oid  oldNspOid,
Oid  newNspOid,
bool  hasDependEntry,
ObjectAddresses objsMoved 
)

Definition at line 14292 of file tablecmds.c.

References add_exact_object_address(), Assert, CatalogTupleUpdate(), changeDependencyFor(), ObjectAddress::classId, elog, ereport, errcode(), errmsg(), ERROR, get_namespace_name(), get_relname_relid(), GETSTRUCT, heap_freetuple(), HeapTupleIsValid, InvalidOid, InvokeObjectPostAlterHook, NameStr, object_address_present(), ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, RELOID, SearchSysCacheCopy1, and HeapTupleData::t_self.

Referenced by AlterIndexNamespaces(), AlterSeqNamespaces(), AlterTableNamespaceInternal(), and AlterTypeNamespaceInternal().

14296 {
14297  HeapTuple classTup;
14298  Form_pg_class classForm;
14299  ObjectAddress thisobj;
14300  bool already_done = false;
14301 
14302  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
14303  if (!HeapTupleIsValid(classTup))
14304  elog(ERROR, "cache lookup failed for relation %u", relOid);
14305  classForm = (Form_pg_class) GETSTRUCT(classTup);
14306 
14307  Assert(classForm->relnamespace == oldNspOid);
14308 
14309  thisobj.classId = RelationRelationId;
14310  thisobj.objectId = relOid;
14311  thisobj.objectSubId = 0;
14312 
14313  /*
14314  * If the object has already been moved, don't move it again. If it's
14315  * already in the right place, don't move it, but still fire the object
14316  * access hook.
14317  */
14318  already_done = object_address_present(&thisobj, objsMoved);
14319  if (!already_done && oldNspOid != newNspOid)
14320  {
14321  /* check for duplicate name (more friendly than unique-index failure) */
14322  if (get_relname_relid(NameStr(classForm->relname),
14323  newNspOid) != InvalidOid)
14324  ereport(ERROR,
14325  (errcode(ERRCODE_DUPLICATE_TABLE),
14326  errmsg("relation \"%s\" already exists in schema \"%s\"",
14327  NameStr(classForm->relname),
14328  get_namespace_name(newNspOid))));
14329 
14330  /* classTup is a copy, so OK to scribble on */
14331  classForm->relnamespace = newNspOid;
14332 
14333  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
14334 
14335  /* Update dependency on schema if caller said so */
14336  if (hasDependEntry &&
14337  changeDependencyFor(RelationRelationId,
14338  relOid,
14339  NamespaceRelationId,
14340  oldNspOid,
14341  newNspOid) != 1)
14342  elog(ERROR, "failed to change schema dependency for relation \"%s\"",
14343  NameStr(classForm->relname));
14344  }
14345  if (!already_done)
14346  {
14347  add_exact_object_address(&thisobj, objsMoved);
14348 
14349  InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
14350  }
14351 
14352  heap_freetuple(classTup);
14353 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2500
int errcode(int sqlerrcode)
Definition: elog.c:570
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2440
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1687
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:732
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
int errmsg(const char *fmt,...)
Definition: elog.c:784
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:297
#define elog(elevel,...)
Definition: elog.h:226
#define NameStr(name)
Definition: c.h:609

◆ AlterSeqNamespaces()

static void AlterSeqNamespaces ( Relation  classRel,
Relation  rel,
Oid  oldNspOid,
Oid  newNspOid,
ObjectAddresses objsMoved,
LOCKMODE  lockmode 
)
static

Definition at line 14407 of file tablecmds.c.

References AccessShareLock, AlterRelationNamespaceInternal(), AlterTypeNamespaceInternal(), BTEqualStrategyNumber, DEPENDENCY_AUTO, DEPENDENCY_INTERNAL, DependReferenceIndexId, GETSTRUCT, HeapTupleIsValid, sort-test::key, NoLock, ObjectIdGetDatum, relation_close(), relation_open(), RelationGetForm, RelationGetRelid, relkind, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), and table_open().

Referenced by AlterTableNamespaceInternal().

14410 {
14411  Relation depRel;
14412  SysScanDesc scan;
14413  ScanKeyData key[2];
14414  HeapTuple tup;
14415 
14416  /*
14417  * SERIAL sequences are those having an auto dependency on one of the
14418  * table's columns (we don't care *which* column, exactly).
14419  */
14420  depRel = table_open(DependRelationId, AccessShareLock);
14421 
14422  ScanKeyInit(&key[0],
14423  Anum_pg_depend_refclassid,
14424  BTEqualStrategyNumber, F_OIDEQ,
14425  ObjectIdGetDatum(RelationRelationId));
14426  ScanKeyInit(&key[1],
14427  Anum_pg_depend_refobjid,
14428  BTEqualStrategyNumber, F_OIDEQ,
14430  /* we leave refobjsubid unspecified */
14431 
14432  scan = systable_beginscan(depRel, DependReferenceIndexId, true,
14433  NULL, 2, key);
14434 
14435  while (HeapTupleIsValid(tup = systable_getnext(scan)))
14436  {
14437  Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
14438  Relation seqRel;
14439 
14440  /* skip dependencies other than auto dependencies on columns */
14441  if (depForm->refobjsubid == 0 ||
14442  depForm->classid != RelationRelationId ||
14443  depForm->objsubid != 0 ||
14444  !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
14445  continue;
14446 
14447  /* Use relation_open just in case it's an index */
14448  seqRel = relation_open(depForm->objid, lockmode);
14449 
14450  /* skip non-sequence relations */
14451  if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
14452  {
14453  /* No need to keep the lock */
14454  relation_close(seqRel, lockmode);
14455  continue;
14456  }
14457 
14458  /* Fix the pg_class and pg_depend entries */
14459  AlterRelationNamespaceInternal(classRel, depForm->objid,
14460  oldNspOid, newNspOid,
14461  true, objsMoved);
14462 
14463  /*
14464  * Sequences have entries in pg_type. We need to be careful to move
14465  * them to the new namespace, too.
14466  */
14468  newNspOid, false, false, objsMoved);
14469 
14470  /* Now we can close it. Keep the lock till end of transaction. */
14471  relation_close(seqRel, NoLock);
14472  }
14473 
14474  systable_endscan(scan);
14475 
14477 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:525
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define RelationGetForm(relation)
Definition: rel.h:410
#define DependReferenceIndexId
Definition: indexing.h:151
#define AccessShareLock
Definition: lockdefs.h:36
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:3579
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:352
char relkind
Definition: pg_class.h:81
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:444
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:71
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:14292
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:416
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ AlterTable()

void AlterTable ( Oid  relid,
LOCKMODE  lockmode,
AlterTableStmt stmt 
)

Definition at line 3495 of file tablecmds.c.

References ATController(), CheckTableNotInUse(), AlterTableStmt::cmds, RangeVar::inh, NoLock, AlterTableStmt::relation, and relation_open().

Referenced by ProcessUtilitySlow().

3496 {
3497  Relation rel;
3498 
3499  /* Caller is required to provide an adequate lock. */
3500  rel = relation_open(relid, NoLock);
3501 
3502  CheckTableNotInUse(rel, "ALTER TABLE");
3503 
3504  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode);
3505 }
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
Definition: tablecmds.c:3825
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3416
bool inh
Definition: primnodes.h:69
RangeVar * relation
Definition: parsenodes.h:1753

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)

Definition at line 3564 of file tablecmds.c.

References AccessExclusiveLock, AccessShareLock, AlterTableGetRelOptionsLockLevel(), AT_AddColumn, AT_AddColumnToView, AT_AddConstraint, AT_AddConstraintRecurse, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AddInherit, AT_AddOf, AT_AlterColumnGenericOptions, AT_AlterColumnType, AT_AlterConstraint, AT_AttachPartition, AT_ChangeOwner, AT_CheckNotNull, AT_ClusterOn, AT_ColumnDefault, AT_DetachPartition, AT_DisableRowSecurity, AT_DisableRule, AT_DisableTrig, AT_DisableTrigAll, AT_DisableTrigUser, AT_DropCluster, AT_DropColumn, AT_DropConstraint, AT_DropIdentity, AT_DropInherit, AT_DropNotNull, AT_DropOf, AT_DropOids, AT_EnableAlwaysRule, AT_EnableAlwaysTrig, AT_EnableReplicaRule, AT_EnableReplicaTrig, AT_EnableRowSecurity, AT_EnableRule, AT_EnableTrig, AT_EnableTrigAll, AT_EnableTrigUser, AT_ForceRowSecurity, AT_GenericOptions, AT_NoForceRowSecurity, AT_ProcessedConstraint, AT_ReAddConstraint, AT_ReAddDomainConstraint, AT_ReplaceRelOptions, AT_ReplicaIdentity, AT_ResetOptions, AT_ResetRelOptions, AT_SetIdentity, AT_SetLogged, AT_SetNotNull, AT_SetOptions, AT_SetRelOptions, AT_SetStatistics, AT_SetStorage, AT_SetTableSpace, AT_SetUnLogged, AT_ValidateConstraint, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, AlterTableCmd::def, elog, ERROR, IsA, lfirst, ShareRowExclusiveLock, ShareUpdateExclusiveLock, and AlterTableCmd::subtype.

Referenced by AlterTableInternal(), and ProcessUtilitySlow().

3565 {
3566  /*
3567  * This only works if we read catalog tables using MVCC snapshots.
3568  */
3569  ListCell *lcmd;
3571 
3572  foreach(lcmd, cmds)
3573  {
3574  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3575  LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
3576 
3577  switch (cmd->subtype)
3578  {
3579  /*
3580  * These subcommands rewrite the heap, so require full locks.
3581  */
3582  case AT_AddColumn: /* may rewrite heap, in some cases and visible
3583  * to SELECT */
3584  case AT_SetTableSpace: /* must rewrite heap */
3585  case AT_AlterColumnType: /* must rewrite heap */
3586  cmd_lockmode = AccessExclusiveLock;
3587  break;
3588 
3589  /*
3590  * These subcommands may require addition of toast tables. If
3591  * we add a toast table to a table currently being scanned, we
3592  * might miss data added to the new toast table by concurrent
3593  * insert transactions.
3594  */
3595  case AT_SetStorage: /* may add toast tables, see
3596  * ATRewriteCatalogs() */
3597  cmd_lockmode = AccessExclusiveLock;
3598  break;
3599 
3600  /*
3601  * Removing constraints can affect SELECTs that have been
3602  * optimized assuming the constraint holds true. See also
3603  * CloneFkReferenced.
3604  */
3605  case AT_DropConstraint: /* as DROP INDEX */
3606  case AT_DropNotNull: /* may change some SQL plans */
3607  cmd_lockmode = AccessExclusiveLock;
3608  break;
3609 
3610  /*
3611  * Subcommands that may be visible to concurrent SELECTs
3612  */
3613  case AT_DropColumn: /* change visible to SELECT */
3614  case AT_AddColumnToView: /* CREATE VIEW */
3615  case AT_DropOids: /* used to equiv to DropColumn */
3616  case AT_EnableAlwaysRule: /* may change SELECT rules */
3617  case AT_EnableReplicaRule: /* may change SELECT rules */
3618  case AT_EnableRule: /* may change SELECT rules */
3619  case AT_DisableRule: /* may change SELECT rules */
3620  cmd_lockmode = AccessExclusiveLock;
3621  break;
3622 
3623  /*
3624  * Changing owner may remove implicit SELECT privileges
3625  */
3626  case AT_ChangeOwner: /* change visible to SELECT */
3627  cmd_lockmode = AccessExclusiveLock;
3628  break;
3629 
3630  /*
3631  * Changing foreign table options may affect optimization.
3632  */
3633  case AT_GenericOptions:
3635  cmd_lockmode = AccessExclusiveLock;
3636  break;
3637 
3638  /*
3639  * These subcommands affect write operations only.
3640  */
3641  case AT_EnableTrig:
3642  case AT_EnableAlwaysTrig:
3643  case AT_EnableReplicaTrig:
3644  case AT_EnableTrigAll:
3645  case AT_EnableTrigUser:
3646  case AT_DisableTrig:
3647  case AT_DisableTrigAll:
3648  case AT_DisableTrigUser:
3649  cmd_lockmode = ShareRowExclusiveLock;
3650  break;
3651 
3652  /*
3653  * These subcommands affect write operations only. XXX
3654  * Theoretically, these could be ShareRowExclusiveLock.
3655  */
3656  case AT_ColumnDefault:
3657  case AT_AlterConstraint:
3658  case AT_AddIndex: /* from ADD CONSTRAINT */
3659  case AT_AddIndexConstraint:
3660  case AT_ReplicaIdentity:
3661  case AT_SetNotNull:
3662  case AT_EnableRowSecurity:
3663  case AT_DisableRowSecurity:
3664  case AT_ForceRowSecurity:
3665  case AT_NoForceRowSecurity:
3666  case AT_AddIdentity:
3667  case AT_DropIdentity:
3668  case AT_SetIdentity:
3669  cmd_lockmode = AccessExclusiveLock;
3670  break;
3671 
3672  case AT_AddConstraint:
3673  case AT_ProcessedConstraint: /* becomes AT_AddConstraint */
3674  case AT_AddConstraintRecurse: /* becomes AT_AddConstraint */
3675  case AT_ReAddConstraint: /* becomes AT_AddConstraint */
3676  case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
3677  if (IsA(cmd->def, Constraint))
3678  {
3679  Constraint *con = (Constraint *) cmd->def;
3680 
3681  switch (con->contype)
3682  {
3683  case CONSTR_EXCLUSION:
3684  case CONSTR_PRIMARY:
3685  case CONSTR_UNIQUE:
3686 
3687  /*
3688  * Cases essentially the same as CREATE INDEX. We
3689  * could reduce the lock strength to ShareLock if
3690  * we can work out how to allow concurrent catalog
3691  * updates. XXX Might be set down to
3692  * ShareRowExclusiveLock but requires further
3693  * analysis.
3694  */
3695  cmd_lockmode = AccessExclusiveLock;
3696  break;
3697  case CONSTR_FOREIGN:
3698 
3699  /*
3700  * We add triggers to both tables when we add a
3701  * Foreign Key, so the lock level must be at least
3702  * as strong as CREATE TRIGGER.
3703  */
3704  cmd_lockmode = ShareRowExclusiveLock;
3705  break;
3706 
3707  default:
3708  cmd_lockmode = AccessExclusiveLock;
3709  }
3710  }
3711  break;
3712 
3713  /*
3714  * These subcommands affect inheritance behaviour. Queries
3715  * started before us will continue to see the old inheritance
3716  * behaviour, while queries started after we commit will see
3717  * new behaviour. No need to prevent reads or writes to the
3718  * subtable while we hook it up though. Changing the TupDesc
3719  * may be a problem, so keep highest lock.
3720  */
3721  case AT_AddInherit:
3722  case AT_DropInherit:
3723  cmd_lockmode = AccessExclusiveLock;
3724  break;
3725 
3726  /*
3727  * These subcommands affect implicit row type conversion. They
3728  * have affects similar to CREATE/DROP CAST on queries. don't
3729  * provide for invalidating parse trees as a result of such
3730  * changes, so we keep these at AccessExclusiveLock.
3731  */
3732  case AT_AddOf:
3733  case AT_DropOf:
3734  cmd_lockmode = AccessExclusiveLock;
3735  break;
3736 
3737  /*
3738  * Only used by CREATE OR REPLACE VIEW which must conflict
3739  * with an SELECTs currently using the view.
3740  */
3741  case AT_ReplaceRelOptions:
3742  cmd_lockmode = AccessExclusiveLock;
3743  break;
3744 
3745  /*
3746  * These subcommands affect general strategies for performance
3747  * and maintenance, though don't change the semantic results
3748  * from normal data reads and writes. Delaying an ALTER TABLE
3749  * behind currently active writes only delays the point where
3750  * the new strategy begins to take effect, so there is no
3751  * benefit in waiting. In this case the minimum restriction
3752  * applies: we don't currently allow concurrent catalog
3753  * updates.
3754  */
3755  case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
3756  case AT_ClusterOn: /* Uses MVCC in getIndexes() */
3757  case AT_DropCluster: /* Uses MVCC in getIndexes() */
3758  case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
3759  case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
3760  cmd_lockmode = ShareUpdateExclusiveLock;
3761  break;
3762 
3763  case AT_SetLogged:
3764  case AT_SetUnLogged:
3765  cmd_lockmode = AccessExclusiveLock;
3766  break;
3767 
3768  case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
3769  cmd_lockmode = ShareUpdateExclusiveLock;
3770  break;
3771 
3772  /*
3773  * Rel options are more complex than first appears. Options
3774  * are set here for tables, views and indexes; for historical
3775  * reasons these can all be used with ALTER TABLE, so we can't
3776  * decide between them using the basic grammar.
3777  */
3778  case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
3779  * getTables() */
3780  case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
3781  * getTables() */
3782  cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
3783  break;
3784 
3785  case AT_AttachPartition:
3786  cmd_lockmode = ShareUpdateExclusiveLock;
3787  break;
3788 
3789  case AT_DetachPartition:
3790  cmd_lockmode = AccessExclusiveLock;
3791  break;
3792 
3793  case AT_CheckNotNull:
3794 
3795  /*
3796  * This only examines the table's schema; but lock must be
3797  * strong enough to prevent concurrent DROP NOT NULL.
3798  */
3799  cmd_lockmode = AccessShareLock;
3800  break;
3801 
3802  default: /* oops */
3803  elog(ERROR, "unrecognized alter table type: %d",
3804  (int) cmd->subtype);
3805  break;
3806  }
3807 
3808  /*
3809  * Take the greatest lockmode from any subcommand
3810  */
3811  if (cmd_lockmode > lockmode)
3812  lockmode = cmd_lockmode;
3813  }
3814 
3815  return lockmode;
3816 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:575
int LOCKMODE
Definition: lockdefs.h:26
#define AccessShareLock
Definition: lockdefs.h:36
AlterTableType subtype
Definition: parsenodes.h:1840
#define ERROR
Definition: elog.h:43
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define lfirst(lc)
Definition: pg_list.h:190
#define ShareRowExclusiveLock
Definition: lockdefs.h:42
LOCKMODE AlterTableGetRelOptionsLockLevel(List *defList)
Definition: reloptions.c:1589
#define AccessExclusiveLock
Definition: lockdefs.h:45
#define elog(elevel,...)
Definition: elog.h:226
ConstrType contype
Definition: parsenodes.h:2129
Definition: pg_list.h:50

◆ AlterTableInternal()

void AlterTableInternal ( Oid  relid,
List cmds,
bool  recurse 
)

Definition at line 3519 of file tablecmds.c.

References AlterTableGetLockLevel(), ATController(), EventTriggerAlterTableRelid(), and relation_open().

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

3520 {
3521  Relation rel;
3522  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
3523 
3524  rel = relation_open(relid, lockmode);
3525 
3527 
3528  ATController(NULL, rel, cmds, recurse, lockmode);
3529 }
int LOCKMODE
Definition: lockdefs.h:26
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
Definition: tablecmds.c:3825
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:3564
void EventTriggerAlterTableRelid(Oid objectId)

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 3444 of file tablecmds.c.

References AlterTableStmt::missing_ok, RangeVarCallbackForAlterRelation(), RangeVarGetRelidExtended(), AlterTableStmt::relation, and RVR_MISSING_OK.

Referenced by ProcessUtilitySlow().

3445 {
3446  return RangeVarGetRelidExtended(stmt->relation, lockmode,
3447  stmt->missing_ok ? RVR_MISSING_OK : 0,
3449  (void *) stmt);
3450 }
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:14805
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:228
RangeVar * relation
Definition: parsenodes.h:1753

◆ AlterTableMoveAll()

Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

Definition at line 12487 of file tablecmds.c.

References AccessExclusiveLock, AccessShareLock, ACL_CREATE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, AlterTableInternal(), AT_SetTableSpace, BTEqualStrategyNumber, ConditionalLockRelationOid(), ereport, errcode(), errmsg(), ERROR, EventTriggerAlterTableEnd(), EventTriggerAlterTableStart(), ForwardScanDirection, get_namespace_name(), get_rel_relkind(), get_relkind_objtype(), get_tablespace_name(), get_tablespace_oid(), GETSTRUCT, GetUserId(), heap_getnext(), InvalidOid, isAnyTempNamespace(), IsCatalogNamespace(), IsToastNamespace(), sort-test::key, lappend(), lappend_oid(), lfirst_oid, list_member_oid(), LockRelationOid(), makeNode, MyDatabaseTableSpace, AlterTableCmd::name, NameStr, AlterTableMoveAllStmt::new_tablespacename, NIL, NOTICE, AlterTableMoveAllStmt::nowait, OBJECT_INDEX, OBJECT_MATVIEW, OBJECT_TABLE, OBJECT_TABLESPACE, ObjectIdGetDatum, AlterTableMoveAllStmt::objtype, OidIsValid, AlterTableMoveAllStmt::orig_tablespacename, pg_class_ownercheck(), pg_tablespace_aclcheck(), AlterTableMoveAllStmt::roles, roleSpecsToIds(), ScanKeyInit(), AlterTableCmd::subtype, table_beginscan_catalog(), table_close(), table_endscan(), and table_open().

Referenced by ProcessUtilitySlow().

12488 {
12489  List *relations = NIL;
12490  ListCell *l;
12491  ScanKeyData key[1];
12492  Relation rel;
12493  TableScanDesc scan;
12494  HeapTuple tuple;
12495  Oid orig_tablespaceoid;
12496  Oid new_tablespaceoid;
12497  List *role_oids = roleSpecsToIds(stmt->roles);
12498 
12499  /* Ensure we were not asked to move something we can't */
12500  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
12501  stmt->objtype != OBJECT_MATVIEW)
12502  ereport(ERROR,
12503  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
12504  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
12505 
12506  /* Get the orig and new tablespace OIDs */
12507  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
12508  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
12509 
12510  /* Can't move shared relations in to or out of pg_global */
12511  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
12512  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
12513  new_tablespaceoid == GLOBALTABLESPACE_OID)
12514  ereport(ERROR,
12515  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
12516  errmsg("cannot move relations in to or out of pg_global tablespace")));
12517 
12518  /*
12519  * Must have CREATE rights on the new tablespace, unless it is the
12520  * database default tablespace (which all users implicitly have CREATE
12521  * rights on).
12522  */
12523  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
12524  {
12525  AclResult aclresult;
12526 
12527  aclresult = pg_tablespace_aclcheck(new_tablespaceoid, GetUserId(),
12528  ACL_CREATE);
12529  if (aclresult != ACLCHECK_OK)
12530  aclcheck_error(aclresult, OBJECT_TABLESPACE,
12531  get_tablespace_name(new_tablespaceoid));
12532  }
12533 
12534  /*
12535  * Now that the checks are done, check if we should set either to
12536  * InvalidOid because it is our database's default tablespace.
12537  */
12538  if (orig_tablespaceoid == MyDatabaseTableSpace)
12539  orig_tablespaceoid = InvalidOid;
12540 
12541  if (new_tablespaceoid == MyDatabaseTableSpace)
12542  new_tablespaceoid = InvalidOid;
12543 
12544  /* no-op */
12545  if (orig_tablespaceoid == new_tablespaceoid)
12546  return new_tablespaceoid;
12547 
12548  /*
12549  * Walk the list of objects in the tablespace and move them. This will
12550  * only find objects in our database, of course.
12551  */
12552  ScanKeyInit(&key[0],
12553  Anum_pg_class_reltablespace,
12554  BTEqualStrategyNumber, F_OIDEQ,
12555  ObjectIdGetDatum(orig_tablespaceoid));
12556 
12557  rel = table_open(RelationRelationId, AccessShareLock);
12558  scan = table_beginscan_catalog(rel, 1, key);
12559  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
12560  {
12561  Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
12562  Oid relOid = relForm->oid;
12563 
12564  /*
12565  * Do not move objects in pg_catalog as part of this, if an admin
12566  * really wishes to do so, they can issue the individual ALTER
12567  * commands directly.
12568  *
12569  * Also, explicitly avoid any shared tables, temp tables, or TOAST
12570  * (TOAST will be moved with the main table).
12571  */
12572  if (IsCatalogNamespace(relForm->relnamespace) ||
12573  relForm->relisshared ||
12574  isAnyTempNamespace(relForm->relnamespace) ||
12575  IsToastNamespace(relForm->relnamespace))
12576  continue;
12577 
12578  /* Only move the object type requested */
12579  if ((stmt->objtype == OBJECT_TABLE &&
12580  relForm->relkind != RELKIND_RELATION &&
12581  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
12582  (stmt->objtype == OBJECT_INDEX &&
12583  relForm->relkind != RELKIND_INDEX &&
12584  relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
12585  (stmt->objtype == OBJECT_MATVIEW &&
12586  relForm->relkind != RELKIND_MATVIEW))
12587  continue;
12588 
12589  /* Check if we are only moving objects owned by certain roles */
12590  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
12591  continue;
12592 
12593  /*
12594  * Handle permissions-checking here since we are locking the tables
12595  * and also to avoid doing a bunch of work only to fail part-way. Note
12596  * that permissions will also be checked by AlterTableInternal().
12597  *
12598  * Caller must be considered an owner on the table to move it.
12599  */
12600  if (!pg_class_ownercheck(relOid, GetUserId()))
12602  NameStr(relForm->relname));
12603 
12604  if (stmt->nowait &&
12606  ereport(ERROR,
12607  (errcode(ERRCODE_OBJECT_IN_USE),
12608  errmsg("aborting because lock on relation \"%s.%s\" is not available",
12609  get_namespace_name(relForm->relnamespace),
12610  NameStr(relForm->relname))));
12611  else
12613 
12614  /* Add to our list of objects to move */
12615  relations = lappend_oid(relations, relOid);
12616  }
12617 
12618  table_endscan(scan);
12620 
12621  if (relations == NIL)
12622  ereport(NOTICE,
12623  (errcode(ERRCODE_NO_DATA_FOUND),
12624  errmsg("no matching relations in tablespace \"%s\" found",
12625  orig_tablespaceoid == InvalidOid ? "(database default)" :
12626  get_tablespace_name(orig_tablespaceoid))));
12627 
12628  /* Everything is locked, loop through and move all of the relations. */
12629  foreach(l, relations)
12630  {
12631  List *cmds = NIL;
12633 
12634  cmd->subtype = AT_SetTableSpace;
12635  cmd->name = stmt->new_tablespacename;
12636 
12637  cmds = lappend(cmds, cmd);
12638 
12640  /* OID is set by AlterTableInternal */
12641  AlterTableInternal(lfirst_oid(l), cmds, false);
12643  }
12644 
12645  return new_tablespaceoid;
12646 }
#define NIL
Definition: pg_list.h:65
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:151
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1417
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4705
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:98
Oid GetUserId(void)
Definition: miscinit.c:380
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1805
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:524
int errcode(int sqlerrcode)
Definition: elog.c:570
AlterTableType subtype
Definition: parsenodes.h:1840
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:197
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
#define OidIsValid(objectId)
Definition: c.h:638
Oid MyDatabaseTableSpace
Definition: globals.c:87
void EventTriggerAlterTableStart(Node *parsetree)
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:84
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1290
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:321
AclResult
Definition: acl.h:177
#define InvalidOid
Definition: postgres_ext.h:36
#define NOTICE
Definition: elog.h:37
#define makeNode(_type_)
Definition: nodes.h:572
List * roleSpecsToIds(List *memberNames)
Definition: user.c:1423
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:674
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4755
bool IsCatalogNamespace(Oid namespaceId)
Definition: catalog.c:179
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:831
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:3519
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:784
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1463
ObjectType get_relkind_objtype(char relkind)
#define NameStr(name)
Definition: c.h:609
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
bool isAnyTempNamespace(Oid namespaceId)
Definition: namespace.c:3187
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:108
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define lfirst_oid(lc)
Definition: pg_list.h:192
void EventTriggerAlterTableEnd(void)

◆ AlterTableNamespace()

ObjectAddress AlterTableNamespace ( AlterObjectSchemaStmt stmt,
Oid oldschema 
)

Definition at line 14183 of file tablecmds.c.

References AccessExclusiveLock, AlterTableNamespaceInternal(), CheckSetNamespace(), DEPENDENCY_AUTO, DEPENDENCY_INTERNAL, ereport, errcode(), errdetail(), errmsg(), ERROR, free_object_addresses(), get_rel_name(), InvalidObjectAddress, makeRangeVar(), AlterObjectSchemaStmt::missing_ok, new_object_addresses(), NoLock, NOTICE, ObjectAddressSet, OidIsValid, RangeVarCallbackForAlterRelation(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetRelidExtended(), RelationData::rd_rel, AlterObjectSchemaStmt::relation, relation_close(), relation_open(), RelationGetNamespace, RelationGetRelationName, OnCommitItem::relid, RVR_MISSING_OK, and sequenceIsOwned().

Referenced by ExecAlterObjectSchemaStmt().

14184 {
14185  Relation rel;
14186  Oid relid;
14187  Oid oldNspOid;
14188  Oid nspOid;
14189  RangeVar *newrv;
14190  ObjectAddresses *objsMoved;
14191  ObjectAddress myself;
14192 
14194  stmt->missing_ok ? RVR_MISSING_OK : 0,
14196  (void *) stmt);
14197 
14198  if (!OidIsValid(relid))
14199  {
14200  ereport(NOTICE,
14201  (errmsg("relation \"%s\" does not exist, skipping",
14202  stmt->relation->relname)));
14203  return InvalidObjectAddress;
14204  }
14205 
14206  rel = relation_open(relid, NoLock);
14207 
14208  oldNspOid = RelationGetNamespace(rel);
14209 
14210  /* If it's an owned sequence, disallow moving it by itself. */
14211  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
14212  {
14213  Oid tableId;
14214  int32 colId;
14215 
14216  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
14217  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
14218  ereport(ERROR,
14219  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14220  errmsg("cannot move an owned sequence into another schema"),
14221  errdetail("Sequence \"%s\" is linked to table \"%s\".",
14223  get_rel_name(tableId))));
14224  }
14225 
14226  /* Get and lock schema OID and check its permissions. */
14227  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
14228  nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
14229 
14230  /* common checks on switching namespaces */
14231  CheckSetNamespace(oldNspOid, nspOid);
14232 
14233  objsMoved = new_object_addresses();
14234  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
14235  free_object_addresses(objsMoved);
14236 
14237  ObjectAddressSet(myself, RelationRelationId, relid);
14238 
14239  if (oldschema)
14240  *oldschema = oldNspOid;
14241 
14242  /* close rel, but keep lock until commit */
14243  relation_close(rel, NoLock);
14244 
14245  return myself;
14246 }
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition: pg_depend.c:663
int errcode(int sqlerrcode)
Definition: elog.c:570
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2385
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2680
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
signed int int32
Definition: c.h:346
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
void AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:14254
#define NoLock
Definition: lockdefs.h:34
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:14805
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define RelationGetRelationName(relation)
Definition: rel.h:450
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:228
#define ereport(elevel, rest)
Definition: elog.h:141
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition: namespace.c:2959
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:526
#define NOTICE
Definition: elog.h:37
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define AccessExclusiveLock
Definition: lockdefs.h:45
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:784
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1730
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:420
#define RelationGetNamespace(relation)
Definition: rel.h:457

◆ AlterTableNamespaceInternal()

void AlterTableNamespaceInternal ( Relation  rel,
Oid  oldNspOid,
Oid  nspOid,
ObjectAddresses objsMoved 
)

Definition at line 14254 of file tablecmds.c.

References AccessExclusiveLock, AlterConstraintNamespaces(), AlterIndexNamespaces(), AlterRelationNamespaceInternal(), AlterSeqNamespaces(), AlterTypeNamespaceInternal(), Assert, RelationData::rd_rel, RelationGetRelid, RowExclusiveLock, table_close(), and table_open().

Referenced by AlterObjectNamespace_oid(), and AlterTableNamespace().

14256 {
14257  Relation classRel;
14258 
14259  Assert(objsMoved != NULL);
14260 
14261  /* OK, modify the pg_class row and pg_depend entry */
14262  classRel = table_open(RelationRelationId, RowExclusiveLock);
14263 
14264  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
14265  nspOid, true, objsMoved);
14266 
14267  /* Fix the table's row type too */
14268  AlterTypeNamespaceInternal(rel->rd_rel->reltype,
14269  nspOid, false, false, objsMoved);
14270 
14271  /* Fix other dependent stuff */
14272  if (rel->rd_rel->relkind == RELKIND_RELATION ||
14273  rel->rd_rel->relkind == RELKIND_MATVIEW ||
14274  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
14275  {
14276  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
14277  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
14278  objsMoved, AccessExclusiveLock);
14279  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
14280  false, objsMoved);
14281  }
14282 
14283  table_close(classRel, RowExclusiveLock);
14284 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:3579
Form_pg_class rd_rel
Definition: rel.h:83
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:14362
void AlterConstraintNamespaces(Oid ownerId, Oid oldNspId, Oid newNspId, bool isType, ObjectAddresses *objsMoved)
static void AlterSeqNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved, LOCKMODE lockmode)
Definition: tablecmds.c:14407
#define RowExclusiveLock
Definition: lockdefs.h:38
#define Assert(condition)
Definition: c.h:732
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:14292
#define AccessExclusiveLock
Definition: lockdefs.h:45
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:416

◆ ATAddCheckConstraint()

static ObjectAddress ATAddCheckConstraint ( List **  wqueue,
AlteredTableInfo tab,
Relation  rel,
Constraint constr,
bool  recurse,
bool  recursing,
bool  is_readd,
LOCKMODE  lockmode 
)
static

Definition at line 7458 of file tablecmds.c.

References AddRelationNewConstraints(), Assert, ATGetQueueEntry(), ATSimplePermissions(), ATT_FOREIGN_TABLE, ATT_TABLE, CheckTableNotInUse(), CommandCounterIncrement(), Constraint::conname, CookedConstraint::conoid, AlteredTableInfo::constraints, CookedConstraint::contype, NewConstraint::contype, copyObject, ereport, errcode(), errmsg(), ERROR, CookedConstraint::expr, find_inheritance_children(), InvalidObjectAddress, Constraint::is_no_inherit, lappend(), lfirst, lfirst_oid, list_length(), list_make1, CookedConstraint::name, NewConstraint::name, NIL, NoLock, ObjectAddressSet, palloc0(), NewConstraint::qual, RelationGetRelid, CookedConstraint::skip_validation, table_close(), and table_open().

Referenced by ATExecAddConstraint().

7461 {
7462  List *newcons;
7463  ListCell *lcon;
7464  List *children;
7465  ListCell *child;
7467 
7468  /* At top level, permission check was done in ATPrepCmd, else do it */
7469  if (recursing)
7471 
7472  /*
7473  * Call AddRelationNewConstraints to do the work, making sure it works on
7474  * a copy of the Constraint so transformExpr can't modify the original. It
7475  * returns a list of cooked constraints.
7476  *
7477  * If the constraint ends up getting merged with a pre-existing one, it's
7478  * omitted from the returned list, which is what we want: we do not need
7479  * to do any validation work. That can only happen at child tables,
7480  * though, since we disallow merging at the top level.
7481  */
7482  newcons = AddRelationNewConstraints(rel, NIL,
7483  list_make1(copyObject(constr)),
7484  recursing | is_readd, /* allow_merge */
7485  !recursing, /* is_local */
7486  is_readd, /* is_internal */
7487  NULL); /* queryString not available
7488  * here */
7489 
7490  /* we don't expect more than one constraint here */
7491  Assert(list_length(newcons) <= 1);
7492 
7493  /* Add each to-be-validated constraint to Phase 3's queue */
7494  foreach(lcon, newcons)
7495  {
7496  CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
7497 
7498  if (!ccon->skip_validation)
7499  {
7500  NewConstraint *newcon;
7501 
7502  newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
7503  newcon->name = ccon->name;
7504  newcon->contype = ccon->contype;
7505  newcon->qual = ccon->expr;
7506 
7507  tab->constraints = lappend(tab->constraints, newcon);
7508  }
7509 
7510  /* Save the actually assigned name if it was defaulted */
7511  if (constr->conname == NULL)
7512  constr->conname = ccon->name;
7513 
7514  ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
7515  }
7516 
7517  /* At this point we must have a locked-down name to use */
7518  Assert(constr->conname != NULL);
7519 
7520  /* Advance command counter in case same table is visited multiple times */
7522 
7523  /*
7524  * If the constraint got merged with an existing constraint, we're done.
7525  * We mustn't recurse to child tables in this case, because they've
7526  * already got the constraint, and visiting them again would lead to an
7527  * incorrect value for coninhcount.
7528  */
7529  if (newcons == NIL)
7530  return address;
7531 
7532  /*
7533  * If adding a NO INHERIT constraint, no need to find our children.
7534  */
7535  if (constr->is_no_inherit)
7536  return address;
7537 
7538  /*
7539  * Propagate to children as appropriate. Unlike most other ALTER
7540  * routines, we have to do this one level of recursion at a time; we can't
7541  * use find_all_inheritors to do it in one pass.
7542  */
7543  children = find_inheritance_children(RelationGetRelid(rel), lockmode);
7544 
7545  /*
7546  * Check if ONLY was specified with ALTER TABLE. If so, allow the
7547  * constraint creation only if there are no children currently. Error out
7548  * otherwise.
7549  */
7550  if (!recurse && children != NIL)
7551  ereport(ERROR,
7552  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7553  errmsg("constraint must be added to child tables too")));
7554 
7555  foreach(child, children)
7556  {
7557  Oid childrelid = lfirst_oid(child);
7558  Relation childrel;
7559  AlteredTableInfo *childtab;
7560 
7561  /* find_inheritance_children already got lock */
7562  childrel = table_open(childrelid, NoLock);
7563  CheckTableNotInUse(childrel, "ALTER TABLE");
7564 
7565  /* Find or create work queue entry for this table */
7566  childtab = ATGetQueueEntry(wqueue, childrel);
7567 
7568  /* Recurse to child */
7569  ATAddCheckConstraint(wqueue, childtab, childrel,
7570  constr, recurse, true, is_readd, lockmode);
7571 
7572  table_close(childrel, NoLock);
7573  }
7574 
7575  return address;
7576 }
#define NIL
Definition: pg_list.h:65
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal, const char *queryString)
Definition: heap.c:2490
char * name
Definition: tablecmds.c:183
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Node * qual
Definition: tablecmds.c:188
int errcode(int sqlerrcode)
Definition: elog.c:570
static ObjectAddress ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *constr, bool recurse, bool recursing, bool is_readd, LOCKMODE lockmode)
Definition: tablecmds.c:7458
char * conname
Definition: parsenodes.h:2132
unsigned int Oid
Definition: postgres_ext.h:31
#define ATT_TABLE
Definition: tablecmds.c:286
List * constraints
Definition: tablecmds.c:162
#define list_make1(x1)
Definition: pg_list.h:227
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
static AlteredTableInfo * ATGetQueueEntry(List **wqueue, Relation rel)
Definition: tablecmds.c:5071
bool skip_validation
Definition: heap.h:41
ConstrType contype
Definition: heap.h:36
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3416
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:321
ConstrType contype
Definition: tablecmds.c:184
void * palloc0(Size size)
Definition: mcxt.c:955
void CommandCounterIncrement(void)
Definition: xact.c:1003
bool is_no_inherit
Definition: parsenodes.h:2138
List * find_inheritance_children(Oid parentrelId, LOCKMODE lockmode)
Definition: pg_inherits.c:55
#define Assert(condition)
Definition: c.h:732
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:784
Oid conoid
Definition: heap.h:37
Node * expr
Definition: heap.h:40
static void ATSimplePermissions(Relation rel, int allowed_targets)
Definition: tablecmds.c:5108
#define copyObject(obj)
Definition: nodes.h:640
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define ATT_FOREIGN_TABLE
Definition: tablecmds.c:291
char * name
Definition: heap.h:38
#define RelationGetRelid(relation)
Definition: rel.h:416
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ ATAddForeignKeyConstraint()

static ObjectAddress ATAddForeignKeyConstraint ( List **  wqueue,
AlteredTableInfo tab,
Relation  rel,
Constraint fkconstraint,
Oid  parentConstr,
bool  recurse,
bool  recursing,
LOCKMODE  lockmode 
)
static

Definition at line 7594 of file tablecmds.c.

References addFkRecurseReferenced(), addFkRecurseReferencing(), allowSystemTableMods, Assert, BTEqualStrategyNumber, can_coerce_type(), checkFkeyPermissions(), CLAOID, COERCION_IMPLICIT, Constraint::conname, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, findFkeyCast(), Constraint::fk_attrs, Constraint::fk_del_action, Constraint::fk_upd_action, FKCONSTR_ACTION_CASCADE, FKCONSTR_ACTION_SETDEFAULT, FKCONSTR_ACTION_SETNULL, format_type_be(), get_opfamily_member(), getBaseType(), GETSTRUCT, HeapTupleIsValid, i, INDEX_MAX_KEYS, Constraint::initially_valid, InvalidOid, IsSystemRelation(), lfirst_oid, list_head(), list_length(), list_nth(), lnext(), MemSet, NIL, NoLock, ObjectAddress::objectId, ObjectIdGetDatum, OidIsValid, Constraint::old_conpfeqop, Constraint::old_pktable_oid, AlteredTableInfo::oldDesc, Constraint::pk_attrs, Constraint::pktable, RelationData::rd_islocaltemp, RelationData::rd_rel, RelationGetDescr, RelationGetRelationName, RelationGetRelid, ReleaseSysCache(), SearchSysCache1(), ShareRowExclusiveLock, Constraint::skip_validation, strVal, table_close(), table_open(), table_openrv(), transformColumnNameList(), transformFkeyCheckAttrs(), transformFkeyGetPrimaryKey(), and TupleDescAttr.

Referenced by ATExecAddConstraint().

7597 {
7598  Relation pkrel;
7599  int16 pkattnum[INDEX_MAX_KEYS];
7600  int16 fkattnum[INDEX_MAX_KEYS];
7601  Oid pktypoid[INDEX_MAX_KEYS];
7602  Oid fktypoid[INDEX_MAX_KEYS];
7603  Oid opclasses[INDEX_MAX_KEYS];
7604  Oid pfeqoperators[INDEX_MAX_KEYS];
7605  Oid ppeqoperators[INDEX_MAX_KEYS];
7606  Oid ffeqoperators[INDEX_MAX_KEYS];
7607  int i;
7608  int numfks,
7609  numpks;
7610  Oid indexOid;
7611  bool old_check_ok;
7612  ObjectAddress address;
7613  ListCell *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
7614 
7615  /*
7616  * Grab ShareRowExclusiveLock on the pk table, so that someone doesn't
7617  * delete rows out from under us.
7618  */
7619  if (OidIsValid(fkconstraint->old_pktable_oid))
7620  pkrel = table_open(fkconstraint->old_pktable_oid, ShareRowExclusiveLock);
7621  else
7622  pkrel = table_openrv(fkconstraint->pktable, ShareRowExclusiveLock);
7623 
7624  /*
7625  * Validity checks (permission checks wait till we have the column
7626  * numbers)
7627  */
7628  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
7629  {
7630  if (!recurse)
7631  ereport(ERROR,
7632  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7633  errmsg("cannot use ONLY for foreign key on partitioned table \"%s\" referencing relation \"%s\"",
7635  RelationGetRelationName(pkrel))));
7636  if (fkconstraint->skip_validation && !fkconstraint->initially_valid)
7637  ereport(ERROR,
7638  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7639  errmsg("cannot add NOT VALID foreign key on partitioned table \"%s\" referencing relation \"%s\"",
7641  RelationGetRelationName(pkrel)),
7642  errdetail("This feature is not yet supported on partitioned tables.")));
7643  }
7644 
7645  if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
7646  pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
7647  ereport(ERROR,
7648  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7649  errmsg("referenced relation \"%s\" is not a table",
7650  RelationGetRelationName(pkrel))));
7651 
7652  if (!allowSystemTableMods && IsSystemRelation(pkrel))
7653  ereport(ERROR,
7654  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
7655  errmsg("permission denied: \"%s\" is a system catalog",
7656  RelationGetRelationName(pkrel))));
7657 
7658  /*
7659  * References from permanent or unlogged tables to temp tables, and from
7660  * permanent tables to unlogged tables, are disallowed because the
7661  * referenced data can vanish out from under us. References from temp
7662  * tables to any other table type are also disallowed, because other
7663  * backends might need to run the RI triggers on the perm table, but they
7664  * can't reliably see tuples in the local buffers of other backends.
7665  */
7666  switch (rel->rd_rel->relpersistence)
7667  {
7668  case RELPERSISTENCE_PERMANENT:
7669  if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT)
7670  ereport(ERROR,
7671  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7672  errmsg("constraints on permanent tables may reference only permanent tables")));
7673  break;
7674  case RELPERSISTENCE_UNLOGGED:
7675  if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT
7676  && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
7677  ereport(ERROR,
7678  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7679  errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
7680  break;
7681  case RELPERSISTENCE_TEMP:
7682  if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
7683  ereport(ERROR,
7684  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7685  errmsg("constraints on temporary tables may reference only temporary tables")));
7686  if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
7687  ereport(ERROR,
7688  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7689  errmsg("constraints on temporary tables must involve temporary tables of this session")));
7690  break;
7691  }
7692 
7693  /*
7694  * Look up the referencing attributes to make sure they exist, and record
7695  * their attnums and type OIDs.
7696  */
7697  MemSet(pkattnum, 0, sizeof(pkattnum));
7698  MemSet(fkattnum, 0, sizeof(fkattnum));
7699  MemSet(pktypoid, 0, sizeof(pktypoid));
7700  MemSet(fktypoid, 0, sizeof(fktypoid));
7701  MemSet(opclasses, 0, sizeof(opclasses));
7702  MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
7703  MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
7704  MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
7705 
7707  fkconstraint->fk_attrs,
7708  fkattnum, fktypoid);
7709 
7710  /*
7711  * If the attribute list for the referenced table was omitted, lookup the
7712  * definition of the primary key and use it. Otherwise, validate the
7713  * supplied attribute list. In either case, discover the index OID and
7714  * index opclasses, and the attnums and type OIDs of the attributes.
7715  */
7716  if (fkconstraint->pk_attrs == NIL)
7717  {
7718  numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
7719  &fkconstraint->pk_attrs,
7720  pkattnum, pktypoid,
7721  opclasses);
7722  }
7723  else
7724  {
7725  numpks = transformColumnNameList(RelationGetRelid(pkrel),
7726  fkconstraint->pk_attrs,
7727  pkattnum, pktypoid);
7728  /* Look for an index matching the column list */
7729  indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
7730  opclasses);
7731  }
7732 
7733  /*
7734  * Now we can check permissions.
7735  */
7736  checkFkeyPermissions(pkrel, pkattnum, numpks);
7737 
7738  /*
7739  * Check some things for generated columns.
7740  */
7741  for (i = 0; i < numfks; i++)
7742  {
7743  char attgenerated = TupleDescAttr(RelationGetDescr(rel), fkattnum[i] - 1)->attgenerated;
7744 
7745  if (attgenerated)
7746  {
7747  /*
7748  * Check restrictions on UPDATE/DELETE actions, per SQL standard
7749  */
7750  if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
7751  fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT ||
7752  fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE)
7753  ereport(ERROR,
7754  (errcode(ERRCODE_SYNTAX_ERROR),
7755  errmsg("invalid %s action for foreign key constraint containing generated column",
7756  "ON UPDATE")));
7757  if (fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
7758  fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
7759  ereport(ERROR,
7760  (errcode(ERRCODE_SYNTAX_ERROR),
7761  errmsg("invalid %s action for foreign key constraint containing generated column",
7762  "ON DELETE")));
7763  }
7764  }
7765 
7766  /*
7767  * Look up the equality operators to use in the constraint.
7768  *
7769  * Note that we have to be careful about the difference between the actual
7770  * PK column type and the opclass' declared input type, which might be
7771  * only binary-compatible with it. The declared opcintype is the right
7772  * thing to probe pg_amop with.
7773  */
7774  if (numfks != numpks)
7775  ereport(ERROR,
7776  (errcode(ERRCODE_INVALID_FOREIGN_KEY),
7777  errmsg("number of referencing and referenced columns for foreign key disagree")));
7778 
7779  /*
7780  * On the strength of a previous constraint, we might avoid scanning
7781  * tables to validate this one. See below.
7782  */
7783  old_check_ok = (fkconstraint->old_conpfeqop != NIL);
7784  Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
7785 
7786  for (i = 0; i < numpks; i++)
7787  {
7788  Oid pktype = pktypoid[i];
7789  Oid fktype = fktypoid[i];
7790  Oid fktyped;
7791  HeapTuple cla_ht;
7792  Form_pg_opclass cla_tup;
7793  Oid amid;
7794  Oid opfamily;
7795  Oid opcintype;
7796  Oid pfeqop;
7797  Oid ppeqop;
7798  Oid ffeqop;
7799  int16 eqstrategy;
7800  Oid pfeqop_right;
7801 
7802  /* We need several fields out of the pg_opclass entry */
7803  cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
7804  if (!HeapTupleIsValid(cla_ht))
7805  elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
7806  cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
7807  amid = cla_tup->opcmethod;
7808  opfamily = cla_tup->opcfamily;
7809  opcintype = cla_tup->opcintype;
7810  ReleaseSysCache(cla_ht);
7811 
7812  /*
7813  * Check it's a btree; currently this can never fail since no other
7814  * index AMs support unique indexes. If we ever did have other types
7815  * of unique indexes, we'd need a way to determine which operator
7816  * strategy number is equality. (Is it reasonable to insist that
7817  * every such index AM use btree's number for equality?)
7818  */
7819  if (amid != BTREE_AM_OID)
7820  elog(ERROR, "only b-tree indexes are supported for foreign keys");
7821  eqstrategy = BTEqualStrategyNumber;
7822 
7823  /*
7824  * There had better be a primary equality operator for the index.
7825  * We'll use it for PK = PK comparisons.
7826  */
7827  ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
7828  eqstrategy);
7829 
7830  if (!OidIsValid(ppeqop))
7831  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
7832  eqstrategy, opcintype, opcintype, opfamily);
7833 
7834  /*
7835  * Are there equality operators that take exactly the FK type? Assume
7836  * we should look through any domain here.
7837  */
7838  fktyped = getBaseType(fktype);
7839 
7840  pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
7841  eqstrategy);
7842  if (OidIsValid(pfeqop))
7843  {
7844  pfeqop_right = fktyped;
7845  ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
7846  eqstrategy);
7847  }
7848  else
7849  {
7850  /* keep compiler quiet */
7851  pfeqop_right = InvalidOid;
7852  ffeqop = InvalidOid;
7853  }
7854 
7855  if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
7856  {
7857  /*
7858  * Otherwise, look for an implicit cast from the FK type to the
7859  * opcintype, and if found, use the primary equality operator.
7860  * This is a bit tricky because opcintype might be a polymorphic
7861  * type such as ANYARRAY or ANYENUM; so what we have to test is
7862  * whether the two actual column types can be concurrently cast to
7863  * that type. (Otherwise, we'd fail to reject combinations such
7864  * as int[] and point[].)
7865  */
7866  Oid input_typeids[2];
7867  Oid target_typeids[2];
7868 
7869  input_typeids[0] = pktype;
7870  input_typeids[1] = fktype;
7871  target_typeids[0] = opcintype;
7872  target_typeids[1] = opcintype;
7873  if (can_coerce_type(2, input_typeids, target_typeids,
7875  {
7876  pfeqop = ffeqop = ppeqop;
7877  pfeqop_right = opcintype;
7878  }
7879  }
7880 
7881  if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
7882  ereport(ERROR,
7883  (errcode(ERRCODE_DATATYPE_MISMATCH),
7884  errmsg("foreign key constraint \"%s\" cannot be implemented",
7885  fkconstraint->conname),
7886  errdetail("Key columns \"%s\" and \"%s\" "
7887  "are of incompatible types: %s and %s.",
7888  strVal(list_nth(fkconstraint->fk_attrs, i)),
7889  strVal(list_nth(fkconstraint->pk_attrs, i)),
7890  format_type_be(fktype),
7891  format_type_be(pktype))));
7892 
7893  if (old_check_ok)
7894  {
7895  /*
7896  * When a pfeqop changes, revalidate the constraint. We could
7897  * permit intra-opfamily changes, but that adds subtle complexity
7898  * without any concrete benefit for core types. We need not
7899  * assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
7900  */
7901  old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
7902  old_pfeqop_item = lnext(fkconstraint->old_conpfeqop,
7903  old_pfeqop_item);
7904  }
7905  if (old_check_ok)
7906  {
7907  Oid old_fktype;
7908  Oid new_fktype;
7909  CoercionPathType old_pathtype;
7910  CoercionPathType new_pathtype;
7911  Oid old_castfunc;
7912  Oid new_castfunc;
7914  fkattnum[i] - 1);
7915 
7916  /*
7917  * Identify coercion pathways from each of the old and new FK-side
7918  * column types to the right (foreign) operand type of the pfeqop.
7919  * We may assume that pg_constraint.conkey is not changing.
7920  */
7921  old_fktype = attr->atttypid;
7922  new_fktype = fktype;
7923  old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
7924  &old_castfunc);
7925  new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
7926  &new_castfunc);
7927 
7928  /*
7929  * Upon a change to the cast from the FK column to its pfeqop
7930  * operand, revalidate the constraint. For this evaluation, a
7931  * binary coercion cast is equivalent to no cast at all. While
7932  * type implementors should design implicit casts with an eye
7933  * toward consistency of operations like equality, we cannot
7934  * assume here that they have done so.
7935  *
7936  * A function with a polymorphic argument could change behavior
7937  * arbitrarily in response to get_fn_expr_argtype(). Therefore,
7938  * when the cast destination is polymorphic, we only avoid
7939  * revalidation if the input type has not changed at all. Given
7940  * just the core data types and operator classes, this requirement
7941  * prevents no would-be optimizations.
7942  *
7943  * If the cast converts from a base type to a domain thereon, then
7944  * that domain type must be the opcintype of the unique index.
7945  * Necessarily, the primary key column must then be of the domain
7946  * type. Since the constraint was previously valid, all values on
7947  * the foreign side necessarily exist on the primary side and in
7948  * turn conform to the domain. Consequently, we need not treat
7949  * domains specially here.
7950  *
7951  * Since we require that all collations share the same notion of
7952  * equality (which they do, because texteq reduces to bitwise
7953  * equality), we don't compare collation here.
7954  *
7955  * We need not directly consider the PK type. It's necessarily
7956  * binary coercible to the opcintype of the unique index column,
7957  * and ri_triggers.c will only deal with PK datums in terms of
7958  * that opcintype. Changing the opcintype also changes pfeqop.
7959  */
7960  old_check_ok = (new_pathtype == old_pathtype &&
7961  new_castfunc == old_castfunc &&
7962  (!IsPolymorphicType(pfeqop_right) ||
7963  new_fktype == old_fktype));
7964  }
7965 
7966  pfeqoperators[i] = pfeqop;
7967  ppeqoperators[i] = ppeqop;
7968  ffeqoperators[i] = ffeqop;
7969  }
7970 
7971  /*
7972  * Create all the constraint and trigger objects, recursing to partitions
7973  * as necessary. First handle the referenced side.
7974  */
7975  address = addFkRecurseReferenced(wqueue, fkconstraint, rel, pkrel,
7976  indexOid,
7977  InvalidOid, /* no parent constraint */
7978  numfks,
7979  pkattnum,
7980  fkattnum,
7981  pfeqoperators,
7982  ppeqoperators,
7983  ffeqoperators,
7984  old_check_ok);
7985 
7986  /* Now handle the referencing side. */
7987  addFkRecurseReferencing(wqueue, fkconstraint, rel, pkrel,
7988  indexOid,
7989  address.objectId,
7990  numfks,
7991  pkattnum,
7992  fkattnum,
7993  pfeqoperators,
7994  ppeqoperators,
7995  ffeqoperators,
7996  old_check_ok,
7997  lockmode);
7998 
7999  /*
8000  * Done. Close pk table, but keep lock until we've committed.
8001  */
8002  table_close(pkrel, NoLock);
8003 
8004  return address;
8005 }
signed short int16
Definition: c.h:345
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
List * old_conpfeqop
Definition: parsenodes.h:2169
bool IsSystemRelation(Relation relation)
Definition: catalog.c:70
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
#define RelationGetDescr(relation)
Definition: rel.h:442
static void addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint, Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr, int numfks, int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators, bool old_check_ok, LOCKMODE lockmode)
Definition: tablecmds.c:8239
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:543
#define FKCONSTR_ACTION_SETDEFAULT
Definition: parsenodes.h:2119
static int transformColumnNameList(Oid relId, List *colList, int16 *attnums, Oid *atttypids)
Definition: tablecmds.c:9296
bool rd_islocaltemp
Definition: rel.h:59
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:570
#define MemSet(start, val, len)
Definition: c.h:955
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
List * pk_attrs
Definition: parsenodes.h:2165
char * conname
Definition: parsenodes.h:2132
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
Definition: tablecmds.c:9608
#define OidIsValid(objectId)
Definition: c.h:638
CoercionPathType
Definition: parse_coerce.h:24
static ObjectAddress addFkRecurseReferenced(List **wqueue, Constraint *fkconstraint, Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr, int numfks, int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators, bool old_check_ok)
Definition: tablecmds.c:8033
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
static void * list_nth(const List *list, int n)
Definition: pg_list.h:277
TupleDesc oldDesc
Definition: tablecmds.c:158
#define NoLock
Definition: lockdefs.h:34
int errdetail(const char *fmt,...)
Definition: elog.c:860
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:163
#define RelationGetRelationName(relation)
Definition: rel.h:450
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
#define ereport(elevel, rest)
Definition: elog.h:141
Oid old_pktable_oid
Definition: parsenodes.h:2170
#define FKCONSTR_ACTION_CASCADE
Definition: parsenodes.h:2117
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1124
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:68
bool allowSystemTableMods
Definition: globals.c:120
#define InvalidOid
Definition: postgres_ext.h:36
bool initially_valid
Definition: parsenodes.h:2175
static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid, List **attnamelist, int16 *attnums, Oid *atttypids, Oid *opclasses)
Definition: tablecmds.c:9341
char fk_del_action
Definition: parsenodes.h:2168
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:732
#define ShareRowExclusiveLock
Definition: lockdefs.h:42
static CoercionPathType findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
Definition: tablecmds.c:9579
#define INDEX_MAX_KEYS
static int list_length(const List *l)
Definition: pg_list.h:169
static Oid transformFkeyCheckAttrs(Relation pkrel, int numattrs, int16 *attnums, Oid *opclasses)
Definition: tablecmds.c:9438
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
int i
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
RangeVar * pktable
Definition: parsenodes.h:2163
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2299
#define FKCONSTR_ACTION_SETNULL
Definition: parsenodes.h:2118
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
bool skip_validation
Definition: parsenodes.h:2174
#define RelationGetRelid(relation)
Definition: rel.h:416
List * fk_attrs
Definition: parsenodes.h:2164
#define BTEqualStrategyNumber
Definition: stratnum.h:31
char fk_upd_action
Definition: parsenodes.h:2167
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ ATCheckPartitionsNotInUse()

static void ATCheckPartitionsNotInUse ( Relation  rel,
LOCKMODE  lockmode 
)
static

Definition at line 5274 of file tablecmds.c.

References CheckTableNotInUse(), find_all_inheritors(), for_each_cell, lfirst_oid, list_free(), list_second_cell(), NoLock, RelationData::rd_rel, RelationGetRelid, table_close(), and table_open().

Referenced by ATPrepCmd().

5275 {
5276  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
5277  {
5278  List *inh;
5279  ListCell *cell;
5280 
5281  inh = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
5282  /* first element is the parent rel; must ignore it */
5283  for_each_cell(cell, inh, list_second_cell(inh))
5284  {
5285  Relation childrel;
5286 
5287  /* find_all_inheritors already got lock */
5288  childrel = table_open(lfirst_oid(cell), NoLock);
5289  CheckTableNotInUse(childrel, "ALTER TABLE");
5290  table_close(childrel, NoLock);
5291  }
5292  list_free(inh);
5293  }
5294 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:390
Form_pg_class rd_rel
Definition: rel.h:83
#define NoLock
Definition: lockdefs.h:34
static ListCell * list_second_cell(const List *l)
Definition: pg_list.h:139
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3416
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:165
void list_free(List *list)
Definition: list.c:1373
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:416
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ ATColumnChangeRequiresRewrite()

static bool ATColumnChangeRequiresRewrite ( Node expr,
AttrNumber  varattno 
)
static

Definition at line 10487 of file tablecmds.c.

References arg, CoerceToDomain::arg, FuncExpr::args, Assert, DomainHasConstraints(), FuncExpr::funcid, IsA, linitial, CoerceToDomain::resulttype, and TimestampTimestampTzRequiresRewrite().

Referenced by ATPrepAlterColumnType().

10488 {
10489  Assert(expr != NULL);
10490 
10491  for (;;)
10492  {
10493  /* only one varno, so no need to check that */
10494  if (IsA(expr, Var) &&((Var *) expr)->varattno == varattno)
10495  return false;
10496  else if (IsA(expr, RelabelType))
10497  expr = (Node *) ((RelabelType *) expr)->arg;
10498  else if (IsA(expr, CoerceToDomain))
10499  {
10500  CoerceToDomain *d = (CoerceToDomain *) expr;
10501 
10503  return true;
10504  expr = (Node *) d->arg;
10505  }
10506  else if (IsA(expr, FuncExpr))
10507  {
10508  FuncExpr *f = (FuncExpr *) expr;
10509 
10510  switch (f->funcid)
10511  {
10512  case F_TIMESTAMPTZ_TIMESTAMP:
10513  case F_TIMESTAMP_TIMESTAMPTZ:
10515  return true;
10516  else
10517  expr = linitial(f->args);
10518  break;
10519  default:
10520  return true;
10521  }
10522  }
10523  else
10524  return true;
10525  }
10526 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:575
List * args
Definition: primnodes.h:463
Definition: nodes.h:524
Definition: primnodes.h:167
bool DomainHasConstraints(Oid type_id)
Definition: typcache.c:1289
#define linitial(l)
Definition: pg_list.h:195
Oid funcid
Definition: primnodes.h:455
#define Assert(condition)
Definition: c.h:732
void * arg
bool TimestampTimestampTzRequiresRewrite(void)
Definition: timestamp.c:5156

◆ ATController()

static void ATController ( AlterTableStmt parsetree,
Relation  rel,
List cmds,
bool  recurse,
LOCKMODE  lockmode 
)
static

Definition at line 3825 of file tablecmds.c.

References ATPrepCmd(), ATRewriteCatalogs(), ATRewriteTables(), lfirst, NIL, NoLock, and relation_close().

Referenced by AlterTable(), and AlterTableInternal().

3827 {
3828  List *wqueue = NIL;
3829  ListCell *lcmd;
3830 
3831  /* Phase 1: preliminary examination of commands, create work queue */
3832  foreach(lcmd, cmds)
3833  {
3834  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3835 
3836  ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode);
3837  }
3838 
3839  /* Close the relation, but keep lock until commit */
3840  relation_close(rel, NoLock);
3841 
3842  /* Phase 2: update system catalogs */
3843  ATRewriteCatalogs(&wqueue, lockmode);
3844 
3845  /* Phase 3: scan/rewrite tables as needed */
3846  ATRewriteTables(parsetree, &wqueue, lockmode);
3847 }
#define NIL
Definition: pg_list.h:65
#define NoLock
Definition: lockdefs.h:34
static void ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode)
Definition: tablecmds.c:4499
static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
Definition: tablecmds.c:3859
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define lfirst(lc)
Definition: pg_list.h:190
static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode)
Definition: tablecmds.c:4154
Definition: pg_list.h:50

◆ ATDetachCheckNoForeignKeyRefs()

static void ATDetachCheckNoForeignKeyRefs ( Relation  partition)
static

Definition at line 16625 of file tablecmds.c.

References Assert, CONSTROID, elog, ERROR, GetParentedForeignKeyRefs(), GETSTRUCT, HeapTupleIsValid, InvalidOid, lfirst_oid, MemSet, NameStr, NoLock, ObjectIdGetDatum, OidIsValid, RelationGetRelid, ReleaseSysCache(), RI_PartitionRemove_Check(), SearchSysCache1(), ShareLock, table_close(), table_open(), Trigger::tgconstraint, Trigger::tgconstrindid, Trigger::tgconstrrelid, Trigger::tgdeferrable, Trigger::tgenabled, Trigger::tginitdeferred, Trigger::tgisinternal, Trigger::tgname, Trigger::tgoid, and TRIGGER_FIRES_ON_ORIGIN.

Referenced by ATExecDetachPartition().

16626 {
16627  List *constraints;
16628  ListCell *cell;
16629 
16630  constraints = GetParentedForeignKeyRefs(partition);
16631 
16632  foreach(cell, constraints)
16633  {
16634  Oid constrOid = lfirst_oid(cell);
16635  HeapTuple tuple;
16636  Form_pg_constraint constrForm;
16637  Relation rel;
16638  Trigger trig;
16639 
16640  tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
16641  if (!HeapTupleIsValid(tuple))
16642  elog(ERROR, "cache lookup failed for constraint %u", constrOid);
16643  constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
16644 
16645  Assert(OidIsValid(constrForm->conparentid));
16646  Assert(constrForm->confrelid == RelationGetRelid(partition));
16647 
16648  /* prevent data changes into the referencing table until commit */
16649  rel = table_open(constrForm->conrelid, ShareLock);
16650 
16651  MemSet(&trig, 0, sizeof(trig));
16652  trig.tgoid = InvalidOid;
16653  trig.tgname = NameStr(constrForm->conname);
16655  trig.tgisinternal = true;
16656  trig.tgconstrrelid = RelationGetRelid(partition);
16657  trig.tgconstrindid = constrForm->conindid;
16658  trig.tgconstraint = constrForm->oid;
16659  trig.tgdeferrable = false;
16660  trig.tginitdeferred = false;
16661  /* we needn't fill in remaining fields */
16662 
16663  RI_PartitionRemove_Check(&trig, rel, partition);
16664 
16665  ReleaseSysCache(tuple);
16666 
16667  table_close(rel, NoLock);
16668  }
16669 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
static List * GetParentedForeignKeyRefs(Relation partition)
Definition: tablecmds.c:16572
Oid tgoid
Definition: reltrigger.h:25
bool tgisinternal
Definition: reltrigger.h:31
#define MemSet(start, val, len)
Definition: c.h:955
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
#define TRIGGER_FIRES_ON_ORIGIN
Definition: trigger.h:155
char tgenabled
Definition: reltrigger.h:30
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Oid tgconstraint
Definition: reltrigger.h:34
char * tgname
Definition: reltrigger.h:27
void RI_PartitionRemove_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
Definition: ri_triggers.c:1572
bool tgdeferrable
Definition: reltrigger.h:35
bool tginitdeferred
Definition: reltrigger.h:36
#define NoLock
Definition: lockdefs.h:34
Oid tgconstrrelid
Definition: reltrigger.h:32
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1124
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
#define InvalidOid
Definition: postgres_ext.h:36
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:732
Oid tgconstrindid
Definition: reltrigger.h:33
#define elog(elevel,...)
Definition: elog.h:226
#define ShareLock
Definition: lockdefs.h:41
#define NameStr(name)
Definition: c.h:609
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:416
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ AtEOSubXact_on_commit_actions()

void AtEOSubXact_on_commit_actions ( bool  isCommit,
SubTransactionId  mySubid,
SubTransactionId  parentSubid 
)

Definition at line 14683 of file tablecmds.c.

References OnCommitItem::creating_subid, OnCommitItem::deleting_subid, foreach_delete_current, InvalidSubTransactionId, lfirst, and pfree().

Referenced by AbortSubTransaction(), and CommitSubTransaction().

14685 {
14686  ListCell *cur_item;
14687 
14688  foreach(cur_item, on_commits)
14689  {
14690  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
14691 
14692  if (!isCommit && oc->creating_subid == mySubid)
14693  {
14694  /* cur_item must be removed */
14696  pfree(oc);
14697  }
14698  else
14699  {
14700  /* cur_item must be preserved */
14701  if (oc->creating_subid == mySubid)
14702  oc->creating_subid = parentSubid;
14703  if (oc->deleting_subid == mySubid)
14704  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
14705  }
14706  }
14707 }
SubTransactionId creating_subid
Definition: tablecmds.c:119
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:368
void pfree(void *pointer)
Definition: mcxt.c:1031
static List * on_commits
Definition: tablecmds.c:123
SubTransactionId deleting_subid
Definition: tablecmds.c:120
#define lfirst(lc)
Definition: pg_list.h:190
#define InvalidSubTransactionId
Definition: c.h:513

◆ AtEOXact_on_commit_actions()

void AtEOXact_on_commit_actions ( bool  isCommit)

Definition at line 14651 of file tablecmds.c.

References OnCommitItem::creating_subid, OnCommitItem::deleting_subid, foreach_delete_current, InvalidSubTransactionId, lfirst, and pfree().

Referenced by AbortTransaction(), CommitTransaction(), and PrepareTransaction().

14652 {
14653  ListCell *cur_item;
14654 
14655  foreach(cur_item, on_commits)
14656  {
14657  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
14658 
14659  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
14661  {
14662  /* cur_item must be removed */
14664  pfree(oc);
14665  }
14666  else
14667  {
14668  /* cur_item must be preserved */
14671  }
14672  }
14673 }
SubTransactionId creating_subid
Definition: tablecmds.c:119
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:368
void pfree(void *pointer)
Definition: mcxt.c:1031
static List * on_commits
Definition: tablecmds.c:123
SubTransactionId deleting_subid
Definition: tablecmds.c:120
#define lfirst(lc)
Definition: pg_list.h:190
#define InvalidSubTransactionId
Definition: c.h:513

◆ ATExecAddColumn()

static ObjectAddress ATExecAddColumn ( List **  wqueue,
AlteredTableInfo tab,
Relation  rel,
ColumnDef colDef,
bool  recurse,
bool  recursing,
bool  if_not_exists,
LOCKMODE  lockmode 
)
static

Definition at line 5579 of file tablecmds.c.

References ACL_USAGE, aclcheck_error_type(), ACLCHECK_OK, add_column_collation_dependency(), add_column_datatype_dependency(), AddRelationNewConstraints(), TypeName::arrayBounds, AT_REWRITE_DEFAULT_VAL, ATGetQueueEntry(), ATSimplePermissions(), ATT_FOREIGN_TABLE, ATT_TABLE, RawColumnDefault::attnum, NewColumnValue::attnum, build_column_default(), CatalogTupleUpdate(), check_for_column_name_collision(), CheckAttributeType(), CheckTableNotInUse(), COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, ColumnDef::colname, CommandCounterIncrement(), copyObject, DomainHasConstraints(), elog, ereport, errcode(), errdetail(), errmsg(), ERROR, NewColumnValue::expr, expression_planner(), find_inheritance_children(), FormData_pg_attribute, RawColumnDefault::generated, ColumnDef::generated, get_collation_name(), get_typcollation(), getBaseTypeAndTypmod(), GetColumnDefCollation(), GETSTRUCT, GetUserId(), heap_freetuple(), HeapTupleIsValid, ColumnDef::identity, ColumnDef::identitySequence, ColumnDef::inhcount, InsertPgAttributeTuple(), InvalidObjectAddress, InvokeObjectPostCreateHook, ColumnDef::is_local, ColumnDef::is_not_null, lappend(), lfirst_oid, list_length(), list_make1, list_make1_oid, makeNode, makeNullConst(), MaxHeapAttributeNumber, RawColumnDefault::missingMode, namestrcpy(), newval, AlteredTableInfo::newvals, NIL, NoLock, NOTICE, ObjectAddressSubSet, ObjectIdGetDatum, palloc(), palloc0(), pg_type_aclcheck(), RangeVarGetRelid, RawColumnDefault::raw_default, ColumnDef::raw_default, RelationData::rd_att, RelationData::rd_rel, RelationGetRelationName, RelationGetRelid, ReleaseSysCache(), relkind, relnatts, RELOID, AlteredTableInfo::rewrite, RowExclusiveLock, SearchSysCacheCopy1, SearchSysCacheCopyAttName(), NextValueExpr::seqid, HeapTupleData::t_self, table_close(), table_open(), TupleDescAttr, NextValueExpr::typeId, ColumnDef::typeName, typenameType(), typenameTypeIdAndMod(), and AlteredTableInfo::verify_new_notnull.

Referenced by ATExecCmd().

5583 {
5584  Oid myrelid = RelationGetRelid(rel);
5585  Relation pgclass,
5586  attrdesc;
5587  HeapTuple reltup;
5588  FormData_pg_attribute attribute;
5589  int newattnum;
5590  char relkind;
5591  HeapTuple typeTuple;
5592  Oid typeOid;
5593  int32 typmod;
5594  Oid collOid;
5595  Form_pg_type tform;
5596  Expr *defval;
5597  List *children;
5598  ListCell *child;
5599  AclResult aclresult;
5600  ObjectAddress address;
5601 
5602  /* At top level, permission check was done in ATPrepCmd, else do it */
5603  if (recursing)
5605 
5606  if (rel->rd_rel->relispartition && !recursing)
5607  ereport(ERROR,
5608  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5609  errmsg("cannot add column to a partition")));
5610 
5611  attrdesc = table_open(AttributeRelationId, RowExclusiveLock);
5612 
5613  /*
5614  * Are we adding the column to a recursion child? If so, check whether to
5615  * merge with an existing definition for the column. If we do merge, we
5616  * must not recurse. Children will already have the column, and recursing
5617  * into them would mess up attinhcount.
5618  */
5619  if (colDef->inhcount > 0)
5620  {
5621  HeapTuple tuple;
5622 
5623  /* Does child already have a column by this name? */
5624  tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
5625  if (HeapTupleIsValid(tuple))
5626  {
5627  Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
5628  Oid ctypeId;
5629  int32 ctypmod;
5630  Oid ccollid;
5631 
5632  /* Child column must match on type, typmod, and collation */
5633  typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
5634  if (ctypeId != childatt->atttypid ||
5635  ctypmod != childatt->atttypmod)
5636  ereport(ERROR,
5637  (errcode(ERRCODE_DATATYPE_MISMATCH),
5638  errmsg("child table \"%s\" has different type for column \"%s\"",
5639  RelationGetRelationName(rel), colDef->colname)));
5640  ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
5641  if (ccollid != childatt->attcollation)
5642  ereport(ERROR,
5643  (errcode(ERRCODE_COLLATION_MISMATCH),
5644  errmsg("child table \"%s\" has different collation for column \"%s\"",
5645  RelationGetRelationName(rel), colDef->colname),
5646  errdetail("\"%s\" versus \"%s\"",
5647  get_collation_name(ccollid),
5648  get_collation_name(childatt->attcollation))));
5649 
5650  /* Bump the existing child att's inhcount */
5651  childatt->attinhcount++;
5652  CatalogTupleUpdate(attrdesc, &tuple->t_self, tuple);
5653 
5654  heap_freetuple(tuple);
5655 
5656  /* Inform the user about the merge */
5657  ereport(NOTICE,
5658  (errmsg("merging definition of column \"%s\" for child \"%s\"",
5659  colDef->colname, RelationGetRelationName(rel))));
5660 
5661  table_close(attrdesc, RowExclusiveLock);
5662  return InvalidObjectAddress;
5663  }
5664  }
5665 
5666  pgclass = table_open(RelationRelationId, RowExclusiveLock);
5667 
5668  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
5669  if (!HeapTupleIsValid(reltup))
5670  elog(ERROR, "cache lookup failed for relation %u", myrelid);
5671  relkind = ((Form_pg_class) GETSTRUCT(reltup))->relkind;
5672 
5673  /*
5674  * Cannot add identity column if table has children, because identity does
5675  * not inherit. (Adding column and identity separately will work.)
5676  */
5677  if (colDef->identity &&
5678  recurse &&
5679  find_inheritance_children(myrelid, NoLock) != NIL)
5680  ereport(ERROR,
5681  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5682  errmsg("cannot recursively add identity column to table that has child tables")));
5683 
5684  /* skip if the name already exists and if_not_exists is true */
5685  if (!check_for_column_name_collision(rel, colDef->colname, if_not_exists))
5686  {
5687  table_close(attrdesc, RowExclusiveLock);
5688  heap_freetuple(reltup);
5689  table_close(pgclass, RowExclusiveLock);
5690  return InvalidObjectAddress;
5691  }
5692 
5693  /* Determine the new attribute's number */
5694  newattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts + 1;
5695  if (newattnum > MaxHeapAttributeNumber)
5696  ereport(ERROR,
5697  (errcode(ERRCODE_TOO_MANY_COLUMNS),
5698  errmsg("tables can have at most %d columns",
5700 
5701  typeTuple = typenameType(NULL, colDef->typeName, &typmod);
5702  tform = (Form_pg_type) GETSTRUCT(typeTuple);
5703  typeOid = tform->oid;
5704 
5705  aclresult = pg_type_aclcheck(typeOid, GetUserId(), ACL_USAGE);
5706  if (aclresult != ACLCHECK_OK)
5707  aclcheck_error_type(aclresult, typeOid);
5708 
5709  collOid = GetColumnDefCollation(NULL, colDef, typeOid);
5710 
5711  /* make sure datatype is legal for a column */
5712  CheckAttributeType(colDef->colname, typeOid, collOid,
5713  list_make1_oid(rel->rd_rel->reltype),
5714  0);
5715 
5716  /* construct new attribute's pg_attribute entry */
5717  attribute.attrelid = myrelid;
5718  namestrcpy(&(attribute.attname), colDef->colname);
5719  attribute.atttypid = typeOid;
5720  attribute.attstattarget = (newattnum > 0) ? -1 : 0;
5721  attribute.attlen = tform->typlen;
5722  attribute.atttypmod = typmod;
5723  attribute.attnum = newattnum;
5724  attribute.attbyval = tform->typbyval;
5725  attribute.attndims = list_length(colDef->typeName->arrayBounds);
5726  attribute.attstorage = tform->typstorage;
5727  attribute.attalign = tform->typalign;
5728  attribute.attnotnull = colDef->is_not_null;
5729  attribute.atthasdef = false;
5730  attribute.atthasmissing = false;
5731  attribute.attidentity = colDef->identity;
5732  attribute.attgenerated = colDef->generated;
5733  attribute.attisdropped = false;
5734  attribute.attislocal = colDef->is_local;
5735  attribute.attinhcount = colDef->inhcount;
5736  attribute.attcollation = collOid;
5737  /* attribute.attacl is handled by InsertPgAttributeTuple */
5738 
5739  ReleaseSysCache(typeTuple);
5740 
5741  InsertPgAttributeTuple(attrdesc, &attribute, NULL);
5742 
5743  table_close(attrdesc, RowExclusiveLock);
5744 
5745  /*
5746  * Update pg_class tuple as appropriate
5747  */
5748  ((Form_pg_class) GETSTRUCT(reltup))->relnatts = newattnum;
5749 
5750  CatalogTupleUpdate(pgclass, &reltup->t_self, reltup);
5751 
5752  heap_freetuple(reltup);
5753 
5754  /* Post creation hook for new attribute */
5755  InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
5756 
5757  table_close(pgclass, RowExclusiveLock);
5758 
5759  /* Make the attribute's catalog entry visible */
5761 
5762  /*
5763  * Store the DEFAULT, if any, in the catalogs
5764  */
5765  if (colDef->raw_default)
5766  {
5767  RawColumnDefault *rawEnt;
5768 
5769  rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
5770  rawEnt->attnum = attribute.attnum;
5771  rawEnt->raw_default = copyObject(colDef->raw_default);
5772 
5773  /*
5774  * Attempt to skip a complete table rewrite by storing the specified
5775  * DEFAULT value outside of the heap. This may be disabled inside
5776  * AddRelationNewConstraints if the optimization cannot be applied.
5777  */
5778  rawEnt->missingMode = (!colDef->generated);
5779 
5780  rawEnt->generated = colDef->generated;
5781 
5782  /*
5783  * This function is intended for CREATE TABLE, so it processes a
5784  * _list_ of defaults, but we just do one.
5785  */
5787  false, true, false, NULL);
5788 
5789  /* Make the additional catalog changes visible */
5791 
5792  /*
5793  * Did the request for a missing value work? If not we'll have to do a
5794  * rewrite
5795  */
5796  if (!rawEnt->missingMode)
5798  }
5799 
5800  /*
5801  * Tell Phase 3 to fill in the default expression, if there is one.
5802  *
5803  * If there is no default, Phase 3 doesn't have to do anything, because
5804  * that effectively means that the default is NULL. The heap tuple access
5805  * routines always check for attnum > # of attributes in tuple, and return
5806  * NULL if so, so without any modification of the tuple data we will get
5807  * the effect of NULL values in the new column.
5808  *
5809  * An exception occurs when the new column is of a domain type: the domain
5810  * might have a NOT NULL constraint, or a check constraint that indirectly
5811  * rejects nulls. If there are any domain constraints then we construct
5812  * an explicit NULL default value that will be passed through
5813  * CoerceToDomain processing. (This is a tad inefficient, since it causes
5814  * rewriting the table which we really don't have to do, but the present
5815  * design of domain processing doesn't offer any simple way of checking
5816  * the constraints more directly.)
5817  *
5818  * Note: we use build_column_default, and not just the cooked default
5819  * returned by AddRelationNewConstraints, so that the right thing happens
5820  * when a datatype's default applies.
5821  *
5822  * We skip this step completely for views and foreign tables. For a view,
5823  * we can only get here from CREATE OR REPLACE VIEW, which historically
5824  * doesn't set up defaults, not even for domain-typed columns. And in any
5825  * case we mustn't invoke Phase 3 on a view or foreign table, since they
5826  * have no storage.
5827  */
5828  if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE
5829  && relkind != RELKIND_FOREIGN_TABLE && attribute.attnum > 0)
5830  {
5831  /*
5832  * For an identity column, we can't use build_column_default(),
5833  * because the sequence ownership isn't set yet. So do it manually.
5834  */
5835  if (colDef->identity)
5836  {
5838 
5839  nve->seqid = RangeVarGetRelid(colDef->identitySequence, NoLock, false);
5840  nve->typeId = typeOid;
5841 
5842  defval = (Expr *) nve;
5843 
5844  /* must do a rewrite for identity columns */
5846  }
5847  else
5848  defval = (Expr *) build_column_default(rel, attribute.attnum);
5849 
5850  if (!defval && DomainHasConstraints(typeOid))
5851  {
5852  Oid baseTypeId;
5853  int32 baseTypeMod;
5854  Oid baseTypeColl;
5855 
5856  baseTypeMod = typmod;
5857  baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
5858  baseTypeColl = get_typcollation(baseTypeId);
5859  defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
5860  defval = (Expr *) coerce_to_target_type(NULL,
5861  (Node *) defval,
5862  baseTypeId,
5863  typeOid,
5864  typmod,
5867  -1);
5868  if (defval == NULL) /* should not happen */
5869  elog(ERROR, "failed to coerce base type to domain");
5870  }
5871 
5872  if (defval)
5873  {
5875 
5876  newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
5877  newval->attnum = attribute.attnum;
5878  newval->expr = expression_planner(defval);
5879 
5880  tab->newvals = lappend(tab->newvals, newval);
5881  }
5882 
5883  if (DomainHasConstraints(typeOid))
5885 
5886  if (!TupleDescAttr(rel->rd_att, attribute.attnum - 1)->atthasmissing)
5887  {
5888  /*
5889  * If the new column is NOT NULL, and there is no missing value,
5890  * tell Phase 3 it needs to check for NULLs.
5891  */
5892  tab->verify_new_notnull |= colDef->is_not_null;
5893  }
5894  }
5895 
5896  /*
5897  * Add needed dependency entries for the new column.
5898  */
5899  add_column_datatype_dependency(myrelid, newattnum, attribute.atttypid);
5900  add_column_collation_dependency(myrelid, newattnum, attribute.attcollation);
5901 
5902  /*
5903  * Propagate to children as appropriate. Unlike most other ALTER
5904  * routines, we have to do this one level of recursion at a time; we can't
5905  * use find_all_inheritors to do it in one pass.
5906  */
5907  children = find_inheritance_children(RelationGetRelid(rel), lockmode);
5908 
5909  /*
5910  * If we are told not to recurse, there had better not be any child
5911  * tables; else the addition would put them out of step.
5912  */
5913  if (children && !recurse)
5914  ereport(ERROR,
5915  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5916  errmsg("column must be added to child tables too")));
5917 
5918  /* Children should see column as singly inherited */
5919  if (!recursing)
5920  {
5921  colDef = copyObject(colDef);
5922  colDef->inhcount = 1;
5923  colDef->is_local = false;
5924  }
5925 
5926  foreach(child, children)
5927  {
5928  Oid childrelid = lfirst_oid(child);
5929  Relation childrel;
5930  AlteredTableInfo *childtab;
5931 
5932  /* find_inheritance_children already got lock */
5933  childrel = table_open(childrelid, NoLock);
5934  CheckTableNotInUse(childrel, "ALTER TABLE");
5935 
5936  /* Find or create work queue entry for this table */
5937  childtab = ATGetQueueEntry(wqueue, childrel);
5938 
5939  /* Recurse to child; return value is ignored */
5940  ATExecAddColumn(wqueue, childtab, childrel,
5941  colDef, recurse, true,
5942  if_not_exists, lockmode);
5943 
5944  table_close(childrel, NoLock);
5945  }
5946 
5947  ObjectAddressSubSet(address, RelationRelationId, myrelid, newattnum);
5948  return address;
5949 }
#define NIL
Definition: pg_list.h:65
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal, const char *queryString)
Definition: heap.c:2490
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2316
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:265
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
AttrNumber attnum
Definition: heap.h:28
bool is_local
Definition: parsenodes.h:649
Oid GetUserId(void)
Definition: miscinit.c:380
char identity
Definition: parsenodes.h:655
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:63
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
char * get_collation_name(Oid colloid)
Definition: lsyscache.c:923
Expr * expression_planner(Expr *expr)
Definition: planner.c:6046
Definition: nodes.h:524
int errcode(int sqlerrcode)
Definition: elog.c:570
char generated
Definition: parsenodes.h:658
bool is_not_null
Definition: parsenodes.h:650
Form_pg_class rd_rel
Definition: rel.h:83
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define ATT_TABLE
Definition: tablecmds.c:286
int namestrcpy(Name name, const char *str)
Definition: name.c:250
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3666
char relkind
Definition: pg_class.h:81
signed int int32
Definition: c.h:346
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:335
bool DomainHasConstraints(Oid type_id)
Definition: typcache.c:1289
#define list_make1(x1)
Definition: pg_list.h:227
RangeVar * identitySequence
Definition: parsenodes.h:656
#define AT_REWRITE_DEFAULT_VAL
Definition: event_trigger.h:32
static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
Definition: tablecmds.c:6009
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
HeapTuple SearchSysCacheCopyAttName(Oid relid, const char *attname)
Definition: syscache.c:1288
ItemPointerData t_self
Definition: htup.h:65
static void add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
Definition: tablecmds.c:6027
bool missingMode
Definition: heap.h:30
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:860
char generated
Definition: heap.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:450
static AlteredTableInfo * ATGetQueueEntry(List **wqueue, Relation rel)
Definition: tablecmds.c:5071
Node * raw_default
Definition: heap.h:29
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
#define ACL_USAGE
Definition: parsenodes.h:82
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3416
#define ereport(elevel, rest)
Definition: elog.h:141
bool verify_new_notnull
Definition: tablecmds.c:164
Node * raw_default
Definition: parsenodes.h:653
List * lappend(List *list, void *datum)
Definition: list.c:321
int16 relnatts
Definition: pg_class.h:84
Oid GetColumnDefCollation(ParseState *pstate, ColumnDef *coldef, Oid typeOid)
Definition: parse_type.c:539
Node * build_column_default(Relation rel, int attrno)
void * palloc0(Size size)
Definition: mcxt.c:955
AclResult
Definition: acl.h:177
void CommandCounterIncrement(void)
Definition: xact.c:1003
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
#define list_make1_oid(x1)
Definition: pg_list.h:249
TupleDesc rd_att
Definition: rel.h:84
void typenameTypeIdAndMod(ParseState *pstate, const TypeName *typeName, Oid *typeid_p, int32 *typmod_p)
Definition: parse_type.c:311
FormData_pg_attribute
Definition: pg_attribute.h:184
List * find_inheritance_children(Oid parentrelId, LOCKMODE lockmode)
Definition: pg_inherits.c:55
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2823
#define NOTICE
Definition: elog.h:37
#define MaxHeapAttributeNumber
Definition: htup_details.h:47
#define makeNode(_type_)
Definition: nodes.h:572
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
FormData_pg_type * Form_pg_type
Definition: pg_type.h:251
static int list_length(const List *l)
Definition: pg_list.h:169
#define newval
TypeName * typeName
Definition: parsenodes.h:647
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
List * arrayBounds
Definition: parsenodes.h:215
void InsertPgAttributeTuple(Relation pg_attribute_rel, Form_pg_attribute new_attribute, CatalogIndexState indstate)
Definition: heap.c:694
const ObjectAddress InvalidObjectAddress
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:784
static bool check_for_column_name_collision(Relation rel, const char *colname, bool if_not_exists)
Definition: tablecmds.c:5956
#define elog(elevel,...)
Definition: elog.h:226
int inhcount
Definition: parsenodes.h:648
static void ATSimplePermissions(Relation rel, int allowed_targets)
Definition: tablecmds.c:5108
char * colname
Definition: parsenodes.h:646
#define copyObject(obj)
Definition: nodes.h:640
void CheckAttributeType(const char *attname, Oid atttypid, Oid attcollation, List *containing_rowtypes, int flags)
Definition: heap.c:578
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4743
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define ATT_FOREIGN_TABLE
Definition: tablecmds.c:291
#define RelationGetRelid(relation)
Definition: rel.h:416
#define lfirst_oid(lc)
Definition: pg_list.h:192
static ObjectAddress ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel, ColumnDef *colDef, bool recurse, bool recursing, bool if_not_exists, LOCKMODE lockmode)
Definition: tablecmds.c:5579
AttrNumber attnum
Definition: tablecmds.c:201

◆ ATExecAddConstraint()

static ObjectAddress ATExecAddConstraint ( List **  wqueue,
AlteredTableInfo tab,
Relation  rel,
Constraint newConstraint,
bool  recurse,
bool  is_readd,
LOCKMODE  lockmode 
)
static

Definition at line 7343 of file tablecmds.c.

References Assert, ATAddCheckConstraint(), ATAddForeignKeyConstraint(), ChooseConstraintName(), ChooseForeignKeyConstraintNameAddition(), Constraint::conname, CONSTR_CHECK, CONSTR_FOREIGN, CONSTRAINT_RELATION, ConstraintNameIsUsed(), Constraint::contype, elog, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, Constraint::fk_attrs, InvalidObjectAddress, InvalidOid, IsA, NIL, RelationGetNamespace, RelationGetRelationName, and RelationGetRelid.

Referenced by ATExecCmd().

7346 {
7348 
7349  Assert(IsA(newConstraint, Constraint));
7350 
7351  /*
7352  * Currently, we only expect to see CONSTR_CHECK and CONSTR_FOREIGN nodes
7353  * arriving here (see the preprocessing done in parse_utilcmd.c). Use a
7354  * switch anyway to make it easier to add more code later.
7355  */
7356  switch (newConstraint->contype)
7357  {
7358  case CONSTR_CHECK:
7359  address =
7360  ATAddCheckConstraint(wqueue, tab, rel,
7361  newConstraint, recurse, false, is_readd,
7362  lockmode);
7363  break;
7364 
7365  case CONSTR_FOREIGN:
7366 
7367  /*
7368  * Assign or validate constraint name
7369  */
7370  if (newConstraint->conname)
7371  {
7373  RelationGetRelid(rel),
7374  newConstraint->conname))
7375  ereport(ERROR,
7377  errmsg("constraint \"%s\" for relation \"%s\" already exists",
7378  newConstraint->conname,
7379  RelationGetRelationName(rel))));
7380  }
7381  else
7382  newConstraint->conname =
7385  "fkey",
7386  RelationGetNamespace(rel),
7387  NIL);
7388 
7389  address = ATAddForeignKeyConstraint(wqueue, tab, rel,
7390  newConstraint, InvalidOid,
7391  recurse, false,
7392  lockmode);
7393  break;
7394 
7395  default:
7396  elog(ERROR, "unrecognized constraint type: %d",
7397  (int) newConstraint->contype);
7398  }
7399 
7400  return address;
7401 }
#define NIL
Definition: pg_list.h:65
char * ChooseConstraintName(const char *name1, const char *name2, const char *label, Oid namespaceid, List *others)
#define IsA(nodeptr, _type_)
Definition: nodes.h:575
bool ConstraintNameIsUsed(ConstraintCategory conCat, Oid objId, const char *conname)
static char * ChooseForeignKeyConstraintNameAddition(List *colnames)
Definition: tablecmds.c:7416
int errcode(int sqlerrcode)
Definition: elog.c:570
static ObjectAddress ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *constr, bool recurse, bool recursing, bool is_readd, LOCKMODE lockmode)
Definition: tablecmds.c:7458
char * conname
Definition: parsenodes.h:2132
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:450
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:732
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
static ObjectAddress ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *fkconstraint, Oid parentConstr, bool recurse, bool recursing, LOCKMODE lockmode)
Definition: tablecmds.c:7594
ConstrType contype
Definition: parsenodes.h:2129
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:33
#define RelationGetRelid(relation)
Definition: rel.h:416
List * fk_attrs
Definition: parsenodes.h:2164
#define RelationGetNamespace(relation)
Definition: rel.h:457

◆ ATExecAddIdentity()

static ObjectAddress ATExecAddIdentity ( Relation  rel,
const char *  colName,
Node def,
LOCKMODE  lockmode 
)
static

Definition at line 6460 of file tablecmds.c.

References attnum, castNode, CatalogTupleUpdate(), ereport, errcode(), errmsg(), ERROR, GETSTRUCT, heap_freetuple(), HeapTupleIsValid, ColumnDef::identity, InvokeObjectPostAlterHook, ObjectAddressSubSet, RelationGetRelationName, RelationGetRelid, RowExclusiveLock, SearchSysCacheCopyAttName(), HeapTupleData::t_self, table_close(), and table_open().

Referenced by ATExecCmd().

6462 {
6463  Relation attrelation;
6464  HeapTuple tuple;
6465  Form_pg_attribute attTup;
6467  ObjectAddress address;
6468  ColumnDef *cdef = castNode(ColumnDef, def);
6469 
6470  attrelation = table_open(AttributeRelationId, RowExclusiveLock);
6471 
6472  tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
6473  if (!HeapTupleIsValid(tuple))
6474  ereport(ERROR,
6475  (errcode(ERRCODE_UNDEFINED_COLUMN),
6476  errmsg("column \"%s\" of relation \"%s\" does not exist",
6477  colName, RelationGetRelationName(rel))));
6478  attTup = (Form_pg_attribute) GETSTRUCT(tuple);
6479  attnum = attTup->attnum;
6480 
6481  /* Can't alter a system attribute */
6482  if (attnum <= 0)
6483  ereport(ERROR,
6484  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6485  errmsg("cannot alter system column \"%s\"",
6486  colName)));
6487 
6488  /*
6489  * Creating a column as identity implies NOT NULL, so adding the identity
6490  * to an existing column that is not NOT NULL would create a state that
6491  * cannot be reproduced without contortions.
6492  */
6493  if (!attTup->attnotnull)
6494  ereport(ERROR,
6495  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6496  errmsg("column \"%s\" of relation \"%s\" must be declared NOT NULL before identity can be added",
6497  colName, RelationGetRelationName(rel))));
6498 
6499  if (attTup->attidentity)
6500  ereport(ERROR,
6501  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6502  errmsg("column \"%s\" of relation \"%s\" is already an identity column",
6503  colName, RelationGetRelationName(rel))));
6504 
6505  if (attTup->atthasdef)
6506  ereport(ERROR,
6507  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6508  errmsg("column \"%s\" of relation \"%s\" already has a default value",
6509  colName, RelationGetRelationName(rel))));
6510 
6511  attTup->attidentity = cdef->identity;
6512  CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
6513 
6514  InvokeObjectPostAlterHook(RelationRelationId,
6515  RelationGetRelid(rel),
6516  attTup->attnum);
6517  ObjectAddressSubSet(address, RelationRelationId,
6518  RelationGetRelid(rel), attnum);
6519  heap_freetuple(tuple);
6520 
6521  table_close(attrelation, RowExclusiveLock);
6522 
6523  return address;
6524 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define castNode(_type_, nodeptr)
Definition: nodes.h:593
char identity
Definition: parsenodes.h:655
int errcode(int sqlerrcode)
Definition: elog.c:570
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCacheCopyAttName(Oid relid, const char *attname)
Definition: syscache.c:1288
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:450
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
int16 attnum
Definition: pg_attribute.h:79
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
int errmsg(const char *fmt,...)
Definition: elog.c:784
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:416

◆ ATExecAddIndex()

static ObjectAddress ATExecAddIndex ( AlteredTableInfo tab,
Relation  rel,
IndexStmt stmt,
bool  is_rebuild,
LOCKMODE  lockmode 
)
static

Definition at line 7196 of file tablecmds.c.

References Assert, IndexStmt::concurrent, DefineIndex(), index_close(), index_open(), InvalidOid, IsA, NoLock, ObjectAddress::objectId, OidIsValid, IndexStmt::oldNode, RelationData::rd_node, RelationGetRelid, RelationPreserveStorage(), AlteredTableInfo::rewrite, and IndexStmt::transformed.

Referenced by ATExecCmd().

7198 {
7199  bool check_rights;
7200  bool skip_build;
7201  bool quiet;
7202  ObjectAddress address;
7203 
7204  Assert(IsA(stmt, IndexStmt));
7205  Assert(!stmt->concurrent);
7206 
7207  /* The IndexStmt has already been through transformIndexStmt */
7208  Assert(stmt->transformed);
7209 
7210  /* suppress schema rights check when rebuilding existing index */
7211  check_rights = !is_rebuild;
7212  /* skip index build if phase 3 will do it or we're reusing an old one */
7213  skip_build = tab->rewrite > 0 || OidIsValid(stmt->oldNode);
7214  /* suppress notices when rebuilding existing index */
7215  quiet = is_rebuild;
7216 
7217  address = DefineIndex(RelationGetRelid(rel),
7218  stmt,
7219  InvalidOid, /* no predefined OID */
7220  InvalidOid, /* no parent index */
7221  InvalidOid, /* no parent constraint */
7222  true, /* is_alter_table */
7223  check_rights,
7224  false, /* check_not_in_use - we did it already */
7225  skip_build,
7226  quiet);
7227 
7228  /*
7229  * If TryReuseIndex() stashed a relfilenode for us, we used it for the new
7230  * index instead of building from scratch. The DROP of the old edition of
7231  * this index will have scheduled the storage for deletion at commit, so
7232  * cancel that pending deletion.
7233  */
7234  if (OidIsValid(stmt->oldNode))
7235  {
7236  Relation irel = index_open(address.objectId, NoLock);
7237 
7238  RelationPreserveStorage(irel->rd_node, true);
7239  index_close(irel, NoLock);
7240  }
7241 
7242  return address;
7243 }
void RelationPreserveStorage(RelFileNode rnode, bool atCommit)
Definition: storage.c:193
#define IsA(nodeptr, _type_)
Definition: nodes.h:575
ObjectAddress DefineIndex(Oid relationId, IndexStmt *stmt, Oid indexRelationId, Oid parentIndexId, Oid parentConstraintId, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
Definition: indexcmds.c:428
#define OidIsValid(objectId)
Definition: c.h:638
#define NoLock
Definition: lockdefs.h:34
bool transformed
Definition: parsenodes.h:2770
#define InvalidOid
Definition: postgres_ext.h:36
RelFileNode rd_node
Definition: rel.h:54
#define Assert(condition)
Definition: c.h:732
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:152
bool concurrent
Definition: parsenodes.h:2771
#define RelationGetRelid(relation)
Definition: rel.h:416
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:126

◆ ATExecAddIndexConstraint()

static ObjectAddress ATExecAddIndexConstraint ( AlteredTableInfo tab,
Relation  rel,
IndexStmt stmt,
LOCKMODE  lockmode 
)
static

Definition at line 7251 of file tablecmds.c.

References AccessShareLock, allowSystemTableMods, Assert, BuildIndexInfo(), IndexStmt::deferrable, elog, ereport, errcode(), errmsg(), ERROR, IndexStmt::idxname, IndexInfo::ii_Unique, index_check_primary_key(), index_close(), INDEX_CONSTR_CREATE_DEFERRABLE, INDEX_CONSTR_CREATE_INIT_DEFERRED, INDEX_CONSTR_CREATE_MARK_AS_PRIMARY, INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS, INDEX_CONSTR_CREATE_UPDATE_INDEX, index_constraint_create(), index_open(), IndexStmt::indexOid, IndexStmt::initdeferred, InvalidOid, IsA, IndexStmt::isconstraint, NoLock, NOTICE, OidIsValid, IndexStmt::primary, pstrdup(), RelationData::rd_rel, RelationGetRelationName, and RenameRelationInternal().

Referenced by ATExecCmd().

7253 {
7254  Oid index_oid = stmt->indexOid;
7255  Relation indexRel;
7256  char *indexName;
7257  IndexInfo *indexInfo;
7258  char *constraintName;
7259  char constraintType;
7260  ObjectAddress address;
7261  bits16 flags;
7262 
7263  Assert(IsA(stmt, IndexStmt));
7264  Assert(OidIsValid(index_oid));
7265  Assert(stmt->isconstraint);
7266 
7267  /*
7268  * Doing this on partitioned tables is not a simple feature to implement,
7269  * so let's punt for now.
7270  */
7271  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
7272  ereport(ERROR,
7273  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7274  errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX is not supported on partitioned tables")));
7275 
7276  indexRel = index_open(index_oid, AccessShareLock);
7277 
7278  indexName = pstrdup(RelationGetRelationName(indexRel));
7279 
7280  indexInfo = BuildIndexInfo(indexRel);
7281 
7282  /* this should have been checked at parse time */
7283  if (!indexInfo->ii_Unique)
7284  elog(ERROR, "index \"%s\" is not unique", indexName);
7285 
7286  /*
7287  * Determine name to assign to constraint. We require a constraint to
7288  * have the same name as the underlying index; therefore, use the index's
7289  * existing name as the default constraint name, and if the user
7290  * explicitly gives some other name for the constraint, rename the index
7291  * to match.
7292  */
7293  constraintName = stmt->idxname;
7294  if (constraintName == NULL)
7295  constraintName = indexName;
7296  else if (strcmp(constraintName, indexName) != 0)
7297  {
7298  ereport(NOTICE,
7299  (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
7300  indexName, constraintName)));
7301  RenameRelationInternal(index_oid, constraintName, false, true);
7302  }
7303 
7304  /* Extra checks needed if making primary key */
7305  if (stmt->primary)
7306  index_check_primary_key(rel, indexInfo, true, stmt);
7307 
7308  /* Note we currently don't support EXCLUSION constraints here */
7309  if (stmt->primary)
7310  constraintType = CONSTRAINT_PRIMARY;
7311  else
7312  constraintType = CONSTRAINT_UNIQUE;
7313 
7314  /* Create the catalog entries for the constraint */
7320 
7321  address = index_constraint_create(rel,
7322  index_oid,
7323  InvalidOid,
7324  indexInfo,
7325  constraintName,
7326  constraintType,
7327  flags,
7329  false); /* is_internal */
7330 
7331  index_close(indexRel, NoLock);
7332 
7333  return address;
7334 }
bool deferrable
Definition: parsenodes.h:2768
bool primary
Definition: parsenodes.h:2766
#define IsA(nodeptr, _type_)
Definition: nodes.h:575
uint16 bits16
Definition: c.h:366
char * pstrdup(const char *in)
Definition: mcxt.c:1161
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:570
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2230
#define INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS
Definition: index.h:79
void index_check_primary_key(Relation heapRel, IndexInfo *indexInfo, bool is_alter_table, IndexStmt *stmt)
Definition: index.c:201
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
#define INDEX_CONSTR_CREATE_INIT_DEFERRED
Definition: index.h:77
Oid indexOid
Definition: parsenodes.h:2763
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:450
#define ereport(elevel, rest)
Definition: elog.h:141
char * idxname
Definition: parsenodes.h:2752
bool allowSystemTableMods
Definition: globals.c:120
#define InvalidOid
Definition: postgres_ext.h:36
#define NOTICE
Definition: elog.h:37
bool ii_Unique
Definition: execnodes.h:170
#define Assert(condition)
Definition: c.h:732
bool initdeferred
Definition: parsenodes.h:2769
#define INDEX_CONSTR_CREATE_UPDATE_INDEX
Definition: index.h:78
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:152
bool isconstraint
Definition: parsenodes.h:2767
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
Definition: tablecmds.c:3314
#define INDEX_CONSTR_CREATE_DEFERRABLE
Definition: index.h:76
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:126
#define INDEX_CONSTR_CREATE_MARK_AS_PRIMARY
Definition: index.h:75
ObjectAddress index_constraint_create(Relation heapRelation, Oid indexRelationId, Oid parentConstraintId, IndexInfo *indexInfo, const char *constraintName, char constraintType, bits16 constr_flags, bool allow_system_table_mods, bool is_internal)
Definition: index.c:1737

◆ ATExecAddInherit()

static ObjectAddress ATExecAddInherit ( Relation  child_rel,
RangeVar parent,
LOCKMODE  lockmode 
)
static

Definition at line 12757 of file tablecmds.c.

References AccessShareLock, ATSimplePermissions(), ATT_FOREIGN_TABLE, ATT_TABLE, CreateInheritance(), ereport, errcode(), errdetail(), errmsg(), ERROR, find_all_inheritors(), FindTriggerIncompatibleWithInheritance(), list_member_oid(), NoLock, ObjectAddressSet, RelationData::rd_islocaltemp, RelationData::rd_rel, RelationGetRelationName, RelationGetRelid, RangeVar::relname, ShareUpdateExclusiveLock, table_close(), table_openrv(), and RelationData::trigdesc.

Referenced by ATExecCmd().

12758 {
12759  Relation parent_rel;
12760  List *children;
12761  ObjectAddress address;
12762  const char *trigger_name;
12763 
12764  /*
12765  * A self-exclusive lock is needed here. See the similar case in
12766  * MergeAttributes() for a full explanation.
12767  */
12768  parent_rel = table_openrv(parent, ShareUpdateExclusiveLock);
12769 
12770  /*
12771  * Must be owner of both parent and child -- child was checked by
12772  * ATSimplePermissions call in ATPrepCmd
12773  */
12775 
12776  /* Permanent rels cannot inherit from temporary ones */
12777  if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
12778  child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
12779  ereport(ERROR,
12780  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12781  errmsg("cannot inherit from temporary relation \"%s\"",
12782  RelationGetRelationName(parent_rel))));
12783 
12784  /* If parent rel is temp, it must belong to this session */
12785  if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
12786  !parent_rel->rd_islocaltemp)
12787  ereport(ERROR,
12788  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12789  errmsg("cannot inherit from temporary relation of another session")));
12790 
12791  /* Ditto for the child */
12792  if (child_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
12793  !child_rel->rd_islocaltemp)
12794  ereport(ERROR,
12795  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12796  errmsg("cannot inherit to temporary relation of another session")));
12797 
12798  /* Prevent partitioned tables from becoming inheritance parents */
12799  if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
12800  ereport(ERROR,
12801  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12802  errmsg("cannot inherit from partitioned table \"%s\"",
12803  parent->relname)));
12804 
12805  /* Likewise for partitions */
12806  if (parent_rel->rd_rel->relispartition)
12807  ereport(ERROR,
12808  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12809  errmsg("cannot inherit from a partition")));
12810 
12811  /*
12812  * Prevent circularity by seeing if proposed parent inherits from child.
12813  * (In particular, this disallows making a rel inherit from itself.)
12814  *
12815  * This is not completely bulletproof because of race conditions: in
12816  * multi-level inheritance trees, someone else could concurrently be
12817  * making another inheritance link that closes the loop but does not join
12818  * either of the rels we have locked. Preventing that seems to require
12819  * exclusive locks on the entire inheritance tree, which is a cure worse
12820  * than the disease. find_all_inheritors() will cope with circularity
12821  * anyway, so don't sweat it too much.
12822  *
12823  * We use weakest lock we can on child's children, namely AccessShareLock.
12824  */
12825  children = find_all_inheritors(RelationGetRelid(child_rel),
12826  AccessShareLock, NULL);
12827 
12828  if (list_member_oid(children, RelationGetRelid(parent_rel)))
12829  ereport(ERROR,
12830  (errcode(ERRCODE_DUPLICATE_TABLE),
12831  errmsg("circular inheritance not allowed"),
12832  errdetail("\"%s\" is already a child of \"%s\".",
12833  parent->relname,
12834  RelationGetRelationName(child_rel))));
12835 
12836  /*
12837  * If child_rel has row-level triggers with transition tables, we
12838  * currently don't allow it to become an inheritance child. See also
12839  * prohibitions in ATExecAttachPartition() and CreateTrigger().
12840  */
12841  trigger_name = FindTriggerIncompatibleWithInheritance(child_rel->trigdesc);
12842  if (trigger_name != NULL)
12843  ereport(ERROR,
12844  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
12845  errmsg("trigger \"%s\" prevents table \"%s\" from becoming an inheritance child",
12846  trigger_name, RelationGetRelationName(child_rel)),
12847  errdetail("ROW triggers with transition tables are not supported in inheritance hierarchies.")));
12848 
12849  /* OK to create inheritance */
12850  CreateInheritance(child_rel, parent_rel);
12851 
12852