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, ObjectAddresses *addrs)
 
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

typedef struct NewConstraint NewConstraint

◆ OnCommitItem

typedef struct OnCommitItem OnCommitItem

Function Documentation

◆ add_column_collation_dependency()

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

Definition at line 6039 of file tablecmds.c.

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

Referenced by ATExecAddColumn(), and ATExecAlterColumnType().

6040 {
6041  ObjectAddress myself,
6042  referenced;
6043 
6044  /* We know the default collation is pinned, so don't bother recording it */
6045  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
6046  {
6047  myself.classId = RelationRelationId;
6048  myself.objectId = relid;
6049  myself.objectSubId = attnum;
6050  referenced.classId = CollationRelationId;
6051  referenced.objectId = collid;
6052  referenced.objectSubId = 0;
6053  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
6054  }
6055 }
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 6021 of file tablecmds.c.

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

Referenced by ATExecAddColumn(), and ATExecAlterColumnType().

6022 {
6023  ObjectAddress myself,
6024  referenced;
6025 
6026  myself.classId = RelationRelationId;
6027  myself.objectId = relid;
6028  myself.objectSubId = attnum;
6029  referenced.classId = TypeRelationId;
6030  referenced.objectId = typid;
6031  referenced.objectSubId = 0;
6032  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
6033 }
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 8063 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, 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().

8068 {
8069  ObjectAddress address;
8070  Oid constrOid;
8071  char *conname;
8072  bool conislocal;
8073  int coninhcount;
8074  bool connoinherit;
8075 
8076  /*
8077  * Verify relkind for each referenced partition. At the top level, this
8078  * is redundant with a previous check, but we need it when recursing.
8079  */
8080  if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
8081  pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
8082  ereport(ERROR,
8083  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8084  errmsg("referenced relation \"%s\" is not a table",
8085  RelationGetRelationName(pkrel))));
8086 
8087  /*
8088  * Caller supplies us with a constraint name; however, it may be used in
8089  * this partition, so come up with a different one in that case.
8090  */
8092  RelationGetRelid(rel),
8093  fkconstraint->conname))
8096  "fkey",
8097  RelationGetNamespace(rel), NIL);
8098  else
8099  conname = fkconstraint->conname;
8100 
8101  if (OidIsValid(parentConstr))
8102  {
8103  conislocal = false;
8104  coninhcount = 1;
8105  connoinherit = false;
8106  }
8107  else
8108  {
8109  conislocal = true;
8110  coninhcount = 0;
8111 
8112  /*
8113  * always inherit for partitioned tables, never for legacy inheritance
8114  */
8115  connoinherit = rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE;
8116  }
8117 
8118  /*
8119  * Record the FK constraint in pg_constraint.
8120  */
8121  constrOid = CreateConstraintEntry(conname,
8122  RelationGetNamespace(rel),
8123  CONSTRAINT_FOREIGN,
8124  fkconstraint->deferrable,
8125  fkconstraint->initdeferred,
8126  fkconstraint->initially_valid,
8127  parentConstr,
8128  RelationGetRelid(rel),
8129  fkattnum,
8130  numfks,
8131  numfks,
8132  InvalidOid, /* not a domain constraint */
8133  indexOid,
8134  RelationGetRelid(pkrel),
8135  pkattnum,
8136  pfeqoperators,
8137  ppeqoperators,
8138  ffeqoperators,
8139  numfks,
8140  fkconstraint->fk_upd_action,
8141  fkconstraint->fk_del_action,
8142  fkconstraint->fk_matchtype,
8143  NULL, /* no exclusion constraint */
8144  NULL, /* no check constraint */
8145  NULL,
8146  conislocal, /* islocal */
8147  coninhcount, /* inhcount */
8148  connoinherit, /* conNoInherit */
8149  false); /* is_internal */
8150 
8151  ObjectAddressSet(address, ConstraintRelationId, constrOid);
8152 
8153  /*
8154  * Mark the child constraint as part of the parent constraint; it must not
8155  * be dropped on its own. (This constraint is deleted when the partition
8156  * is detached, but a special check needs to occur that the partition
8157  * contains no referenced values.)
8158  */
8159  if (OidIsValid(parentConstr))
8160  {
8161  ObjectAddress referenced;
8162 
8163  ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
8164  recordDependencyOn(&address, &referenced, DEPENDENCY_INTERNAL);
8165  }
8166 
8167  /* make new constraint visible, in case we add more */
8169 
8170  /*
8171  * If the referenced table is a plain relation, create the action triggers
8172  * that enforce the constraint.
8173  */
8174  if (pkrel->rd_rel->relkind == RELKIND_RELATION)
8175  {
8177  fkconstraint,
8178  constrOid, indexOid);
8179  }
8180 
8181  /*
8182  * If the referenced table is partitioned, recurse on ourselves to handle
8183  * each partition. We need one pg_constraint row created for each
8184  * partition in addition to the pg_constraint row for the parent table.
8185  */
8186  if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
8187  {
8189 
8190  for (int i = 0; i < pd->nparts; i++)
8191  {
8192  Relation partRel;
8193  AttrNumber *map;
8194  AttrNumber *mapped_pkattnum;
8195  Oid partIndexId;
8196 
8197  partRel = table_open(pd->oids[i], ShareRowExclusiveLock);
8198 
8199  /*
8200  * Map the attribute numbers in the referenced side of the FK
8201  * definition to match the partition's column layout.
8202  */
8204  RelationGetDescr(pkrel));
8205  if (map)
8206  {
8207  mapped_pkattnum = palloc(sizeof(AttrNumber) * numfks);
8208  for (int j = 0; j < numfks; j++)
8209  mapped_pkattnum[j] = map[pkattnum[j] - 1];
8210  }
8211  else
8212  mapped_pkattnum = pkattnum;
8213 
8214  /* do the deed */
8215  partIndexId = index_get_partition(partRel, indexOid);
8216  if (!OidIsValid(partIndexId))
8217  elog(ERROR, "index for %u not found in partition %s",
8218  indexOid, RelationGetRelationName(partRel));
8219  addFkRecurseReferenced(wqueue, fkconstraint, rel, partRel,
8220  partIndexId, constrOid, numfks,
8221  mapped_pkattnum, fkattnum,
8222  pfeqoperators, ppeqoperators, ffeqoperators,
8223  old_check_ok);
8224 
8225  /* Done -- clean up (but keep the lock) */
8226  table_close(partRel, NoLock);
8227  if (map)
8228  {
8229  pfree(mapped_pkattnum);
8230  pfree(map);
8231  }
8232  }
8233  }
8234 
8235  return address;
8236 }
#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:7446
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define RelationGetDescr(relation)
Definition: rel.h:445
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
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
void pfree(void *pointer)
Definition: mcxt.c:1056
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:8063
#define ERROR
Definition: elog.h:43
bool deferrable
Definition: parsenodes.h:2133
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:453
#define ereport(elevel, rest)
Definition: elog.h:141
static void createForeignKeyActionTriggers(Relation rel, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid)
Definition: tablecmds.c:9890
AttrNumber * convert_tuples_by_name_map_if_req(TupleDesc indesc, TupleDesc outdesc)
Definition: tupconvert.c:327
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:949
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:419
List * fk_attrs
Definition: parsenodes.h:2164
char fk_upd_action
Definition: parsenodes.h:2167
#define RelationGetPartitionDesc(relation)
Definition: rel.h:606
#define RelationGetNamespace(relation)
Definition: rel.h:460

◆ 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 8268 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(), 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().

8273 {
8274  AssertArg(OidIsValid(parentConstr));
8275 
8276  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
8277  ereport(ERROR,
8278  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8279  errmsg("foreign key constraints are not supported on foreign tables")));
8280 
8281  /*
8282  * If the referencing relation is a plain table, add the check triggers to
8283  * it and, if necessary, schedule it to be checked in Phase 3.
8284  *
8285  * If the relation is partitioned, drill down to do it to its partitions.
8286  */
8287  if (rel->rd_rel->relkind == RELKIND_RELATION)
8288  {
8290  RelationGetRelid(pkrel),
8291  fkconstraint,
8292  parentConstr,
8293  indexOid);
8294 
8295  /*
8296  * Tell Phase 3 to check that the constraint is satisfied by existing
8297  * rows. We can skip this during table creation, when requested
8298  * explicitly by specifying NOT VALID in an ADD FOREIGN KEY command,
8299  * and when we're recreating a constraint following a SET DATA TYPE
8300  * operation that did not impugn its validity.
8301  */
8302  if (wqueue && !old_check_ok && !fkconstraint->skip_validation)
8303  {
8304  NewConstraint *newcon;
8305  AlteredTableInfo *tab;
8306 
8307  tab = ATGetQueueEntry(wqueue, rel);
8308 
8309  newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
8310  newcon->name = get_constraint_name(parentConstr);
8311  newcon->contype = CONSTR_FOREIGN;
8312  newcon->refrelid = RelationGetRelid(pkrel);
8313  newcon->refindid = indexOid;
8314  newcon->conid = parentConstr;
8315  newcon->qual = (Node *) fkconstraint;
8316 
8317  tab->constraints = lappend(tab->constraints, newcon);
8318  }
8319  }
8320  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
8321  {
8323 
8324  /*
8325  * Recurse to take appropriate action on each partition; either we
8326  * find an existing constraint to reparent to ours, or we create a new
8327  * one.
8328  */
8329  for (int i = 0; i < pd->nparts; i++)
8330  {
8331  Oid partitionId = pd->oids[i];
8332  Relation partition = table_open(partitionId, lockmode);
8333  List *partFKs;
8334  AttrNumber *attmap;
8335  AttrNumber mapped_fkattnum[INDEX_MAX_KEYS];
8336  bool attached;
8337  char *conname;
8338  Oid constrOid;
8339  ObjectAddress address,
8340  referenced;
8341  ListCell *cell;
8342 
8343  CheckTableNotInUse(partition, "ALTER TABLE");
8344 
8345  attmap = convert_tuples_by_name_map(RelationGetDescr(partition),
8346  RelationGetDescr(rel));
8347  for (int j = 0; j < numfks; j++)
8348  mapped_fkattnum[j] = attmap[fkattnum[j] - 1];
8349 
8350  /* Check whether an existing constraint can be repurposed */
8351  partFKs = copyObject(RelationGetFKeyList(partition));
8352  attached = false;
8353  foreach(cell, partFKs)
8354  {
8355  ForeignKeyCacheInfo *fk;
8356 
8357  fk = lfirst_node(ForeignKeyCacheInfo, cell);
8359  partitionId,
8360  parentConstr,
8361  numfks,
8362  mapped_fkattnum,
8363  pkattnum,
8364  pfeqoperators))
8365  {
8366  attached = true;
8367  break;
8368  }
8369  }
8370  if (attached)
8371  {
8372  table_close(partition, NoLock);
8373  continue;
8374  }
8375 
8376  /*
8377  * No luck finding a good constraint to reuse; create our own.
8378  */
8380  RelationGetRelid(partition),
8381  fkconstraint->conname))
8382  conname = ChooseConstraintName(RelationGetRelationName(partition),
8384  "fkey",
8385  RelationGetNamespace(partition), NIL);
8386  else
8387  conname = fkconstraint->conname;
8388  constrOid =
8389  CreateConstraintEntry(conname,
8390  RelationGetNamespace(partition),
8391  CONSTRAINT_FOREIGN,
8392  fkconstraint->deferrable,
8393  fkconstraint->initdeferred,
8394  fkconstraint->initially_valid,
8395  parentConstr,
8396  partitionId,
8397  mapped_fkattnum,
8398  numfks,
8399  numfks,
8400  InvalidOid,
8401  indexOid,
8402  RelationGetRelid(pkrel),
8403  pkattnum,
8404  pfeqoperators,
8405  ppeqoperators,
8406  ffeqoperators,
8407  numfks,
8408  fkconstraint->fk_upd_action,
8409  fkconstraint->fk_del_action,
8410  fkconstraint->fk_matchtype,
8411  NULL,
8412  NULL,
8413  NULL,
8414  false,
8415  1,
8416  false,
8417  false);
8418 
8419  /*
8420  * Give this constraint partition-type dependencies on the parent
8421  * constraint as well as the table.
8422  */
8423  ObjectAddressSet(address, ConstraintRelationId, constrOid);
8424  ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
8425  recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_PRI);
8426  ObjectAddressSet(referenced, RelationRelationId, partitionId);
8427  recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_SEC);
8428 
8429  /* Make all this visible before recursing */
8431 
8432  /* call ourselves to finalize the creation and we're done */
8433  addFkRecurseReferencing(wqueue, fkconstraint, partition, pkrel,
8434  indexOid,
8435  constrOid,
8436  numfks,
8437  pkattnum,
8438  mapped_fkattnum,
8439  pfeqoperators,
8440  ppeqoperators,
8441  ffeqoperators,
8442  old_check_ok,
8443  lockmode);
8444 
8445  table_close(partition, NoLock);
8446  }
8447  }
8448 }
#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:10011
bool ConstraintNameIsUsed(ConstraintCategory conCat, Oid objId, const char *conname)
char * name
Definition: tablecmds.c:183
static char * ChooseForeignKeyConstraintNameAddition(List *colnames)
Definition: tablecmds.c:7446
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define RelationGetDescr(relation)
Definition: rel.h:445
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:8268
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
Definition: nodes.h:525
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:8858
#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:453
static AlteredTableInfo * ATGetQueueEntry(List **wqueue, Relation rel)
Definition: tablecmds.c:5083
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:322
ConstrType contype
Definition: tablecmds.c:184
void * palloc0(Size size)
Definition: mcxt.c:980
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:641
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
AttrNumber * convert_tuples_by_name_map(TupleDesc indesc, TupleDesc outdesc)
Definition: tupconvert.c:245
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
bool skip_validation
Definition: parsenodes.h:2174
#define RelationGetRelid(relation)
Definition: rel.h:419
List * fk_attrs
Definition: parsenodes.h:2164
char fk_upd_action
Definition: parsenodes.h:2167
#define RelationGetPartitionDesc(relation)
Definition: rel.h:606
#define RelationGetNamespace(relation)
Definition: rel.h:460

◆ AlterIndexNamespaces()

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

Definition at line 14420 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().

14422 {
14423  List *indexList;
14424  ListCell *l;
14425 
14426  indexList = RelationGetIndexList(rel);
14427 
14428  foreach(l, indexList)
14429  {
14430  Oid indexOid = lfirst_oid(l);
14431  ObjectAddress thisobj;
14432 
14433  thisobj.classId = RelationRelationId;
14434  thisobj.objectId = indexOid;
14435  thisobj.objectSubId = 0;
14436 
14437  /*
14438  * Note: currently, the index will not have its own dependency on the
14439  * namespace, so we don't need to do changeDependencyFor(). There's no
14440  * row type in pg_type, either.
14441  *
14442  * XXX this objsMoved test may be pointless -- surely we have a single
14443  * dependency link from a relation to each index?
14444  */
14445  if (!object_address_present(&thisobj, objsMoved))
14446  {
14447  AlterRelationNamespaceInternal(classRel, indexOid,
14448  oldNspOid, newNspOid,
14449  false, objsMoved);
14450  add_exact_object_address(&thisobj, objsMoved);
14451  }
14452  }
14453 
14454  list_free(indexList);
14455 }
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2495
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2435
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:14350
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4348
void list_free(List *list)
Definition: list.c:1377
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 14350 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().

14354 {
14355  HeapTuple classTup;
14356  Form_pg_class classForm;
14357  ObjectAddress thisobj;
14358  bool already_done = false;
14359 
14360  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
14361  if (!HeapTupleIsValid(classTup))
14362  elog(ERROR, "cache lookup failed for relation %u", relOid);
14363  classForm = (Form_pg_class) GETSTRUCT(classTup);
14364 
14365  Assert(classForm->relnamespace == oldNspOid);
14366 
14367  thisobj.classId = RelationRelationId;
14368  thisobj.objectId = relOid;
14369  thisobj.objectSubId = 0;
14370 
14371  /*
14372  * If the object has already been moved, don't move it again. If it's
14373  * already in the right place, don't move it, but still fire the object
14374  * access hook.
14375  */
14376  already_done = object_address_present(&thisobj, objsMoved);
14377  if (!already_done && oldNspOid != newNspOid)
14378  {
14379  /* check for duplicate name (more friendly than unique-index failure) */
14380  if (get_relname_relid(NameStr(classForm->relname),
14381  newNspOid) != InvalidOid)
14382  ereport(ERROR,
14383  (errcode(ERRCODE_DUPLICATE_TABLE),
14384  errmsg("relation \"%s\" already exists in schema \"%s\"",
14385  NameStr(classForm->relname),
14386  get_namespace_name(newNspOid))));
14387 
14388  /* classTup is a copy, so OK to scribble on */
14389  classForm->relnamespace = newNspOid;
14390 
14391  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
14392 
14393  /* Update dependency on schema if caller said so */
14394  if (hasDependEntry &&
14395  changeDependencyFor(RelationRelationId,
14396  relOid,
14397  NamespaceRelationId,
14398  oldNspOid,
14399  newNspOid) != 1)
14400  elog(ERROR, "failed to change schema dependency for relation \"%s\"",
14401  NameStr(classForm->relname));
14402  }
14403  if (!already_done)
14404  {
14405  add_exact_object_address(&thisobj, objsMoved);
14406 
14407  InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
14408  }
14409 
14410  heap_freetuple(classTup);
14411 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2495
int errcode(int sqlerrcode)
Definition: elog.c:570
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2435
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 14465 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().

14468 {
14469  Relation depRel;
14470  SysScanDesc scan;
14471  ScanKeyData key[2];
14472  HeapTuple tup;
14473 
14474  /*
14475  * SERIAL sequences are those having an auto dependency on one of the
14476  * table's columns (we don't care *which* column, exactly).
14477  */
14478  depRel = table_open(DependRelationId, AccessShareLock);
14479 
14480  ScanKeyInit(&key[0],
14481  Anum_pg_depend_refclassid,
14482  BTEqualStrategyNumber, F_OIDEQ,
14483  ObjectIdGetDatum(RelationRelationId));
14484  ScanKeyInit(&key[1],
14485  Anum_pg_depend_refobjid,
14486  BTEqualStrategyNumber, F_OIDEQ,
14488  /* we leave refobjsubid unspecified */
14489 
14490  scan = systable_beginscan(depRel, DependReferenceIndexId, true,
14491  NULL, 2, key);
14492 
14493  while (HeapTupleIsValid(tup = systable_getnext(scan)))
14494  {
14495  Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
14496  Relation seqRel;
14497 
14498  /* skip dependencies other than auto dependencies on columns */
14499  if (depForm->refobjsubid == 0 ||
14500  depForm->classid != RelationRelationId ||
14501  depForm->objsubid != 0 ||
14502  !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
14503  continue;
14504 
14505  /* Use relation_open just in case it's an index */
14506  seqRel = relation_open(depForm->objid, lockmode);
14507 
14508  /* skip non-sequence relations */
14509  if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
14510  {
14511  /* No need to keep the lock */
14512  relation_close(seqRel, lockmode);
14513  continue;
14514  }
14515 
14516  /* Fix the pg_class and pg_depend entries */
14517  AlterRelationNamespaceInternal(classRel, depForm->objid,
14518  oldNspOid, newNspOid,
14519  true, objsMoved);
14520 
14521  /*
14522  * Sequences have entries in pg_type. We need to be careful to move
14523  * them to the new namespace, too.
14524  */
14526  newNspOid, false, false, objsMoved);
14527 
14528  /* Now we can close it. Keep the lock till end of transaction. */
14529  relation_close(seqRel, NoLock);
14530  }
14531 
14532  systable_endscan(scan);
14533 
14535 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:525
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define RelationGetForm(relation)
Definition: rel.h:413
#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:14350
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:419
#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:576
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:1695
#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:14863
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 12545 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().

12546 {
12547  List *relations = NIL;
12548  ListCell *l;
12549  ScanKeyData key[1];
12550  Relation rel;
12551  TableScanDesc scan;
12552  HeapTuple tuple;
12553  Oid orig_tablespaceoid;
12554  Oid new_tablespaceoid;
12555  List *role_oids = roleSpecsToIds(stmt->roles);
12556 
12557  /* Ensure we were not asked to move something we can't */
12558  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
12559  stmt->objtype != OBJECT_MATVIEW)
12560  ereport(ERROR,
12561  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
12562  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
12563 
12564  /* Get the orig and new tablespace OIDs */
12565  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
12566  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
12567 
12568  /* Can't move shared relations in to or out of pg_global */
12569  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
12570  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
12571  new_tablespaceoid == GLOBALTABLESPACE_OID)
12572  ereport(ERROR,
12573  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
12574  errmsg("cannot move relations in to or out of pg_global tablespace")));
12575 
12576  /*
12577  * Must have CREATE rights on the new tablespace, unless it is the
12578  * database default tablespace (which all users implicitly have CREATE
12579  * rights on).
12580  */
12581  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
12582  {
12583  AclResult aclresult;
12584 
12585  aclresult = pg_tablespace_aclcheck(new_tablespaceoid, GetUserId(),
12586  ACL_CREATE);
12587  if (aclresult != ACLCHECK_OK)
12588  aclcheck_error(aclresult, OBJECT_TABLESPACE,
12589  get_tablespace_name(new_tablespaceoid));
12590  }
12591 
12592  /*
12593  * Now that the checks are done, check if we should set either to
12594  * InvalidOid because it is our database's default tablespace.
12595  */
12596  if (orig_tablespaceoid == MyDatabaseTableSpace)
12597  orig_tablespaceoid = InvalidOid;
12598 
12599  if (new_tablespaceoid == MyDatabaseTableSpace)
12600  new_tablespaceoid = InvalidOid;
12601 
12602  /* no-op */
12603  if (orig_tablespaceoid == new_tablespaceoid)
12604  return new_tablespaceoid;
12605 
12606  /*
12607  * Walk the list of objects in the tablespace and move them. This will
12608  * only find objects in our database, of course.
12609  */
12610  ScanKeyInit(&key[0],
12611  Anum_pg_class_reltablespace,
12612  BTEqualStrategyNumber, F_OIDEQ,
12613  ObjectIdGetDatum(orig_tablespaceoid));
12614 
12615  rel = table_open(RelationRelationId, AccessShareLock);
12616  scan = table_beginscan_catalog(rel, 1, key);
12617  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
12618  {
12619  Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
12620  Oid relOid = relForm->oid;
12621 
12622  /*
12623  * Do not move objects in pg_catalog as part of this, if an admin
12624  * really wishes to do so, they can issue the individual ALTER
12625  * commands directly.
12626  *
12627  * Also, explicitly avoid any shared tables, temp tables, or TOAST
12628  * (TOAST will be moved with the main table).
12629  */
12630  if (IsCatalogNamespace(relForm->relnamespace) ||
12631  relForm->relisshared ||
12632  isAnyTempNamespace(relForm->relnamespace) ||
12633  IsToastNamespace(relForm->relnamespace))
12634  continue;
12635 
12636  /* Only move the object type requested */
12637  if ((stmt->objtype == OBJECT_TABLE &&
12638  relForm->relkind != RELKIND_RELATION &&
12639  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
12640  (stmt->objtype == OBJECT_INDEX &&
12641  relForm->relkind != RELKIND_INDEX &&
12642  relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
12643  (stmt->objtype == OBJECT_MATVIEW &&
12644  relForm->relkind != RELKIND_MATVIEW))
12645  continue;
12646 
12647  /* Check if we are only moving objects owned by certain roles */
12648  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
12649  continue;
12650 
12651  /*
12652  * Handle permissions-checking here since we are locking the tables
12653  * and also to avoid doing a bunch of work only to fail part-way. Note
12654  * that permissions will also be checked by AlterTableInternal().
12655  *
12656  * Caller must be considered an owner on the table to move it.
12657  */
12658  if (!pg_class_ownercheck(relOid, GetUserId()))
12660  NameStr(relForm->relname));
12661 
12662  if (stmt->nowait &&
12664  ereport(ERROR,
12665  (errcode(ERRCODE_OBJECT_IN_USE),
12666  errmsg("aborting because lock on relation \"%s.%s\" is not available",
12667  get_namespace_name(relForm->relnamespace),
12668  NameStr(relForm->relname))));
12669  else
12671 
12672  /* Add to our list of objects to move */
12673  relations = lappend_oid(relations, relOid);
12674  }
12675 
12676  table_endscan(scan);
12678 
12679  if (relations == NIL)
12680  ereport(NOTICE,
12681  (errcode(ERRCODE_NO_DATA_FOUND),
12682  errmsg("no matching relations in tablespace \"%s\" found",
12683  orig_tablespaceoid == InvalidOid ? "(database default)" :
12684  get_tablespace_name(orig_tablespaceoid))));
12685 
12686  /* Everything is locked, loop through and move all of the relations. */
12687  foreach(l, relations)
12688  {
12689  List *cmds = NIL;
12691 
12692  cmd->subtype = AT_SetTableSpace;
12693  cmd->name = stmt->new_tablespacename;
12694 
12695  cmds = lappend(cmds, cmd);
12696 
12698  /* OID is set by AlterTableInternal */
12699  AlterTableInternal(lfirst_oid(l), cmds, false);
12701  }
12702 
12703  return new_tablespaceoid;
12704 }
#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:525
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:358
#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:322
AclResult
Definition: acl.h:177
#define InvalidOid
Definition: postgres_ext.h:36
#define NOTICE
Definition: elog.h:37
#define makeNode(_type_)
Definition: nodes.h:573
List * roleSpecsToIds(List *memberNames)
Definition: user.c:1423
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:675
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 14241 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().

14242 {
14243  Relation rel;
14244  Oid relid;
14245  Oid oldNspOid;
14246  Oid nspOid;
14247  RangeVar *newrv;
14248  ObjectAddresses *objsMoved;
14249  ObjectAddress myself;
14250 
14252  stmt->missing_ok ? RVR_MISSING_OK : 0,
14254  (void *) stmt);
14255 
14256  if (!OidIsValid(relid))
14257  {
14258  ereport(NOTICE,
14259  (errmsg("relation \"%s\" does not exist, skipping",
14260  stmt->relation->relname)));
14261  return InvalidObjectAddress;
14262  }
14263 
14264  rel = relation_open(relid, NoLock);
14265 
14266  oldNspOid = RelationGetNamespace(rel);
14267 
14268  /* If it's an owned sequence, disallow moving it by itself. */
14269  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
14270  {
14271  Oid tableId;
14272  int32 colId;
14273 
14274  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
14275  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
14276  ereport(ERROR,
14277  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14278  errmsg("cannot move an owned sequence into another schema"),
14279  errdetail("Sequence \"%s\" is linked to table \"%s\".",
14281  get_rel_name(tableId))));
14282  }
14283 
14284  /* Get and lock schema OID and check its permissions. */
14285  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
14286  nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
14287 
14288  /* common checks on switching namespaces */
14289  CheckSetNamespace(oldNspOid, nspOid);
14290 
14291  objsMoved = new_object_addresses();
14292  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
14293  free_object_addresses(objsMoved);
14294 
14295  ObjectAddressSet(myself, RelationRelationId, relid);
14296 
14297  if (oldschema)
14298  *oldschema = oldNspOid;
14299 
14300  /* close rel, but keep lock until commit */
14301  relation_close(rel, NoLock);
14302 
14303  return myself;
14304 }
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:2380
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2675
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:14312
#define NoLock
Definition: lockdefs.h:34
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:14863
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define RelationGetRelationName(relation)
Definition: rel.h:453
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:460

◆ AlterTableNamespaceInternal()

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

Definition at line 14312 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().

14314 {
14315  Relation classRel;
14316 
14317  Assert(objsMoved != NULL);
14318 
14319  /* OK, modify the pg_class row and pg_depend entry */
14320  classRel = table_open(RelationRelationId, RowExclusiveLock);
14321 
14322  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
14323  nspOid, true, objsMoved);
14324 
14325  /* Fix the table's row type too */
14326  AlterTypeNamespaceInternal(rel->rd_rel->reltype,
14327  nspOid, false, false, objsMoved);
14328 
14329  /* Fix other dependent stuff */
14330  if (rel->rd_rel->relkind == RELKIND_RELATION ||
14331  rel->rd_rel->relkind == RELKIND_MATVIEW ||
14332  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
14333  {
14334  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
14335  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
14336  objsMoved, AccessExclusiveLock);
14337  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
14338  false, objsMoved);
14339  }
14340 
14341  table_close(classRel, RowExclusiveLock);
14342 }
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:14420
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:14465
#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:14350
#define AccessExclusiveLock
Definition: lockdefs.h:45
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:419

◆ 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 7488 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().

7491 {
7492  List *newcons;
7493  ListCell *lcon;
7494  List *children;
7495  ListCell *child;
7497 
7498  /* At top level, permission check was done in ATPrepCmd, else do it */
7499  if (recursing)
7501 
7502  /*
7503  * Call AddRelationNewConstraints to do the work, making sure it works on
7504  * a copy of the Constraint so transformExpr can't modify the original. It
7505  * returns a list of cooked constraints.
7506  *
7507  * If the constraint ends up getting merged with a pre-existing one, it's
7508  * omitted from the returned list, which is what we want: we do not need
7509  * to do any validation work. That can only happen at child tables,
7510  * though, since we disallow merging at the top level.
7511  */
7512  newcons = AddRelationNewConstraints(rel, NIL,
7513  list_make1(copyObject(constr)),
7514  recursing | is_readd, /* allow_merge */
7515  !recursing, /* is_local */
7516  is_readd, /* is_internal */
7517  NULL); /* queryString not available
7518  * here */
7519 
7520  /* we don't expect more than one constraint here */
7521  Assert(list_length(newcons) <= 1);
7522 
7523  /* Add each to-be-validated constraint to Phase 3's queue */
7524  foreach(lcon, newcons)
7525  {
7526  CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
7527 
7528  if (!ccon->skip_validation)
7529  {
7530  NewConstraint *newcon;
7531 
7532  newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
7533  newcon->name = ccon->name;
7534  newcon->contype = ccon->contype;
7535  newcon->qual = ccon->expr;
7536 
7537  tab->constraints = lappend(tab->constraints, newcon);
7538  }
7539 
7540  /* Save the actually assigned name if it was defaulted */
7541  if (constr->conname == NULL)
7542  constr->conname = ccon->name;
7543 
7544  ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
7545  }
7546 
7547  /* At this point we must have a locked-down name to use */
7548  Assert(constr->conname != NULL);
7549 
7550  /* Advance command counter in case same table is visited multiple times */
7552 
7553  /*
7554  * If the constraint got merged with an existing constraint, we're done.
7555  * We mustn't recurse to child tables in this case, because they've
7556  * already got the constraint, and visiting them again would lead to an
7557  * incorrect value for coninhcount.
7558  */
7559  if (newcons == NIL)
7560  return address;
7561 
7562  /*
7563  * If adding a NO INHERIT constraint, no need to find our children.
7564  */
7565  if (constr->is_no_inherit)
7566  return address;
7567 
7568  /*
7569  * Propagate to children as appropriate. Unlike most other ALTER
7570  * routines, we have to do this one level of recursion at a time; we can't
7571  * use find_all_inheritors to do it in one pass.
7572  */
7573  children = find_inheritance_children(RelationGetRelid(rel), lockmode);
7574 
7575  /*
7576  * Check if ONLY was specified with ALTER TABLE. If so, allow the
7577  * constraint creation only if there are no children currently. Error out
7578  * otherwise.
7579  */
7580  if (!recurse && children != NIL)
7581  ereport(ERROR,
7582  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7583  errmsg("constraint must be added to child tables too")));
7584 
7585  foreach(child, children)
7586  {
7587  Oid childrelid = lfirst_oid(child);
7588  Relation childrel;
7589  AlteredTableInfo *childtab;
7590 
7591  /* find_inheritance_children already got lock */
7592  childrel = table_open(childrelid, NoLock);
7593  CheckTableNotInUse(childrel, "ALTER TABLE");
7594 
7595  /* Find or create work queue entry for this table */
7596  childtab = ATGetQueueEntry(wqueue, childrel);
7597 
7598  /* Recurse to child */
7599  ATAddCheckConstraint(wqueue, childtab, childrel,
7600  constr, recurse, true, is_readd, lockmode);
7601 
7602  table_close(childrel, NoLock);
7603  }
7604 
7605  return address;
7606 }
#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:7488
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:5083
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:322
ConstrType contype
Definition: tablecmds.c:184
void * palloc0(Size size)
Definition: mcxt.c:980
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:5120
#define copyObject(obj)
Definition: nodes.h:641
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:419
#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 7624 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().

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

5287 {
5288  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
5289  {
5290  List *inh;
5291  ListCell *cell;
5292 
5293  inh = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
5294  /* first element is the parent rel; must ignore it */
5295  for_each_cell(cell, inh, list_second_cell(inh))
5296  {
5297  Relation childrel;
5298 
5299  /* find_all_inheritors already got lock */
5300  childrel = table_open(lfirst_oid(cell), NoLock);
5301  CheckTableNotInUse(childrel, "ALTER TABLE");
5302  table_close(childrel, NoLock);
5303  }
5304  list_free(inh);
5305  }
5306 }
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:1377
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:419
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ ATColumnChangeRequiresRewrite()

static bool ATColumnChangeRequiresRewrite ( Node expr,
AttrNumber  varattno 
)
static

Definition at line 10545 of file tablecmds.c.

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

Referenced by ATPrepAlterColumnType().

10546 {
10547  Assert(expr != NULL);
10548 
10549  for (;;)
10550  {
10551  /* only one varno, so no need to check that */
10552  if (IsA(expr, Var) &&((Var *) expr)->varattno == varattno)
10553  return false;
10554  else if (IsA(expr, RelabelType))
10555  expr = (Node *) ((RelabelType *) expr)->arg;
10556  else if (IsA(expr, CoerceToDomain))
10557  {
10558  CoerceToDomain *d = (CoerceToDomain *) expr;
10559 
10561  return true;
10562  expr = (Node *) d->arg;
10563  }
10564  else if (IsA(expr, FuncExpr))
10565  {
10566  FuncExpr *f = (FuncExpr *) expr;
10567 
10568  switch (f->funcid)
10569  {
10570  case F_TIMESTAMPTZ_TIMESTAMP:
10571  case F_TIMESTAMP_TIMESTAMPTZ:
10573  return true;
10574  else
10575  expr = linitial(f->args);
10576  break;
10577  default:
10578  return true;
10579  }
10580  }
10581  else
10582  return true;
10583  }
10584 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
List * args
Definition: primnodes.h:463
Definition: nodes.h:525
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:5170

◆ 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:4501
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 16681 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().

16682 {
16683  List *constraints;
16684  ListCell *cell;
16685 
16686  constraints = GetParentedForeignKeyRefs(partition);
16687 
16688  foreach(cell, constraints)
16689  {
16690  Oid constrOid = lfirst_oid(cell);
16691  HeapTuple tuple;
16692  Form_pg_constraint constrForm;
16693  Relation rel;
16694  Trigger trig;
16695 
16696  tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
16697  if (!HeapTupleIsValid(tuple))
16698  elog(ERROR, "cache lookup failed for constraint %u", constrOid);
16699  constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
16700 
16701  Assert(OidIsValid(constrForm->conparentid));
16702  Assert(constrForm->confrelid == RelationGetRelid(partition));
16703 
16704  /* prevent data changes into the referencing table until commit */
16705  rel = table_open(constrForm->conrelid, ShareLock);
16706 
16707  MemSet(&trig, 0, sizeof(trig));
16708  trig.tgoid = InvalidOid;
16709  trig.tgname = NameStr(constrForm->conname);
16711  trig.tgisinternal = true;
16712  trig.tgconstrrelid = RelationGetRelid(partition);
16713  trig.tgconstrindid = constrForm->conindid;
16714  trig.tgconstraint = constrForm->oid;
16715  trig.tgdeferrable = false;
16716  trig.tginitdeferred = false;
16717  /* we needn't fill in remaining fields */
16718 
16719  RI_PartitionRemove_Check(&trig, rel, partition);
16720 
16721  ReleaseSysCache(tuple);
16722 
16723  table_close(rel, NoLock);
16724  }
16725 }
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:16628
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:419
#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 14741 of file tablecmds.c.

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

14743 {
14744  ListCell *cur_item;
14745 
14746  foreach(cur_item, on_commits)
14747  {
14748  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
14749 
14750  if (!isCommit && oc->creating_subid == mySubid)
14751  {
14752  /* cur_item must be removed */
14754  pfree(oc);
14755  }
14756  else
14757  {
14758  /* cur_item must be preserved */
14759  if (oc->creating_subid == mySubid)
14760  oc->creating_subid = parentSubid;
14761  if (oc->deleting_subid == mySubid)
14762  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
14763  }
14764  }
14765 }
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:1056
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 14709 of file tablecmds.c.

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

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

14710 {
14711  ListCell *cur_item;
14712 
14713  foreach(cur_item, on_commits)
14714  {
14715  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
14716 
14717  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
14719  {
14720  /* cur_item must be removed */
14722  pfree(oc);
14723  }
14724  else
14725  {
14726  /* cur_item must be preserved */
14729  }
14730  }
14731 }
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:1056
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 5591 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().

5595 {
5596  Oid myrelid = RelationGetRelid(rel);
5597  Relation pgclass,
5598  attrdesc;
5599  HeapTuple reltup;
5600  FormData_pg_attribute attribute;
5601  int newattnum;
5602  char relkind;
5603  HeapTuple typeTuple;
5604  Oid typeOid;
5605  int32 typmod;
5606  Oid collOid;
5607  Form_pg_type tform;
5608  Expr *defval;
5609  List *children;
5610  ListCell *child;
5611  AclResult aclresult;
5612  ObjectAddress address;
5613 
5614  /* At top level, permission check was done in ATPrepCmd, else do it */
5615  if (recursing)
5617 
5618  if (rel->rd_rel->relispartition && !recursing)
5619  ereport(ERROR,
5620  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5621  errmsg("cannot add column to a partition")));
5622 
5623  attrdesc = table_open(AttributeRelationId, RowExclusiveLock);
5624 
5625  /*
5626  * Are we adding the column to a recursion child? If so, check whether to
5627  * merge with an existing definition for the column. If we do merge, we
5628  * must not recurse. Children will already have the column, and recursing
5629  * into them would mess up attinhcount.
5630  */
5631  if (colDef->inhcount > 0)
5632  {
5633  HeapTuple tuple;
5634 
5635  /* Does child already have a column by this name? */
5636  tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
5637  if (HeapTupleIsValid(tuple))
5638  {
5639  Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
5640  Oid ctypeId;
5641  int32 ctypmod;
5642  Oid ccollid;
5643 
5644  /* Child column must match on type, typmod, and collation */
5645  typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
5646  if (ctypeId != childatt->atttypid ||
5647  ctypmod != childatt->atttypmod)
5648  ereport(ERROR,
5649  (errcode(ERRCODE_DATATYPE_MISMATCH),
5650  errmsg("child table \"%s\" has different type for column \"%s\"",
5651  RelationGetRelationName(rel), colDef->colname)));
5652  ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
5653  if (ccollid != childatt->attcollation)
5654  ereport(ERROR,
5655  (errcode(ERRCODE_COLLATION_MISMATCH),
5656  errmsg("child table \"%s\" has different collation for column \"%s\"",
5657  RelationGetRelationName(rel), colDef->colname),
5658  errdetail("\"%s\" versus \"%s\"",
5659  get_collation_name(ccollid),
5660  get_collation_name(childatt->attcollation))));
5661 
5662  /* Bump the existing child att's inhcount */
5663  childatt->attinhcount++;
5664  CatalogTupleUpdate(attrdesc, &tuple->t_self, tuple);
5665 
5666  heap_freetuple(tuple);
5667 
5668  /* Inform the user about the merge */
5669  ereport(NOTICE,
5670  (errmsg("merging definition of column \"%s\" for child \"%s\"",
5671  colDef->colname, RelationGetRelationName(rel))));
5672 
5673  table_close(attrdesc, RowExclusiveLock);
5674  return InvalidObjectAddress;
5675  }
5676  }
5677 
5678  pgclass = table_open(RelationRelationId, RowExclusiveLock);
5679 
5680  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
5681  if (!HeapTupleIsValid(reltup))
5682  elog(ERROR, "cache lookup failed for relation %u", myrelid);
5683  relkind = ((Form_pg_class) GETSTRUCT(reltup))->relkind;
5684 
5685  /*
5686  * Cannot add identity column if table has children, because identity does
5687  * not inherit. (Adding column and identity separately will work.)
5688  */
5689  if (colDef->identity &&
5690  recurse &&
5691  find_inheritance_children(myrelid, NoLock) != NIL)
5692  ereport(ERROR,
5693  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5694  errmsg("cannot recursively add identity column to table that has child tables")));
5695 
5696  /* skip if the name already exists and if_not_exists is true */
5697  if (!check_for_column_name_collision(rel, colDef->colname, if_not_exists))
5698  {
5699  table_close(attrdesc, RowExclusiveLock);
5700  heap_freetuple(reltup);
5701  table_close(pgclass, RowExclusiveLock);
5702  return InvalidObjectAddress;
5703  }
5704 
5705  /* Determine the new attribute's number */
5706  newattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts + 1;
5707  if (newattnum > MaxHeapAttributeNumber)
5708  ereport(ERROR,
5709  (errcode(ERRCODE_TOO_MANY_COLUMNS),
5710  errmsg("tables can have at most %d columns",
5712 
5713  typeTuple = typenameType(NULL, colDef->typeName, &typmod);
5714  tform = (Form_pg_type) GETSTRUCT(typeTuple);
5715  typeOid = tform->oid;
5716 
5717  aclresult = pg_type_aclcheck(typeOid, GetUserId(), ACL_USAGE);
5718  if (aclresult != ACLCHECK_OK)
5719  aclcheck_error_type(aclresult, typeOid);
5720 
5721  collOid = GetColumnDefCollation(NULL, colDef, typeOid);
5722 
5723  /* make sure datatype is legal for a column */
5724  CheckAttributeType(colDef->colname, typeOid, collOid,
5725  list_make1_oid(rel->rd_rel->reltype),
5726  0);
5727 
5728  /* construct new attribute's pg_attribute entry */
5729  attribute.attrelid = myrelid;
5730  namestrcpy(&(attribute.attname), colDef->colname);
5731  attribute.atttypid = typeOid;
5732  attribute.attstattarget = (newattnum > 0) ? -1 : 0;
5733  attribute.attlen = tform->typlen;
5734  attribute.atttypmod = typmod;
5735  attribute.attnum = newattnum;
5736  attribute.attbyval = tform->typbyval;
5737  attribute.attndims = list_length(colDef->typeName->arrayBounds);
5738  attribute.attstorage = tform->typstorage;
5739  attribute.attalign = tform->typalign;
5740  attribute.attnotnull = colDef->is_not_null;
5741  attribute.atthasdef = false;
5742  attribute.atthasmissing = false;
5743  attribute.attidentity = colDef->identity;
5744  attribute.attgenerated = colDef->generated;
5745  attribute.attisdropped = false;
5746  attribute.attislocal = colDef->is_local;
5747  attribute.attinhcount = colDef->inhcount;
5748  attribute.attcollation = collOid;
5749  /* attribute.attacl is handled by InsertPgAttributeTuple */
5750 
5751  ReleaseSysCache(typeTuple);
5752 
5753  InsertPgAttributeTuple(attrdesc, &attribute, NULL);
5754 
5755  table_close(attrdesc, RowExclusiveLock);
5756 
5757  /*
5758  * Update pg_class tuple as appropriate
5759  */
5760  ((Form_pg_class) GETSTRUCT(reltup))->relnatts = newattnum;
5761 
5762  CatalogTupleUpdate(pgclass, &reltup->t_self, reltup);
5763 
5764  heap_freetuple(reltup);
5765 
5766  /* Post creation hook for new attribute */
5767  InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
5768 
5769  table_close(pgclass, RowExclusiveLock);
5770 
5771  /* Make the attribute's catalog entry visible */
5773 
5774  /*
5775  * Store the DEFAULT, if any, in the catalogs
5776  */
5777  if (colDef->raw_default)
5778  {
5779  RawColumnDefault *rawEnt;
5780 
5781  rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
5782  rawEnt->attnum = attribute.attnum;
5783  rawEnt->raw_default = copyObject(colDef->raw_default);
5784 
5785  /*
5786  * Attempt to skip a complete table rewrite by storing the specified
5787  * DEFAULT value outside of the heap. This may be disabled inside
5788  * AddRelationNewConstraints if the optimization cannot be applied.
5789  */
5790  rawEnt->missingMode = (!colDef->generated);
5791 
5792  rawEnt->generated = colDef->generated;
5793 
5794  /*
5795  * This function is intended for CREATE TABLE, so it processes a
5796  * _list_ of defaults, but we just do one.
5797  */
5799  false, true, false, NULL);
5800 
5801  /* Make the additional catalog changes visible */
5803 
5804  /*
5805  * Did the request for a missing value work? If not we'll have to do a
5806  * rewrite
5807  */
5808  if (!rawEnt->missingMode)
5810  }
5811 
5812  /*
5813  * Tell Phase 3 to fill in the default expression, if there is one.
5814  *
5815  * If there is no default, Phase 3 doesn't have to do anything, because
5816  * that effectively means that the default is NULL. The heap tuple access
5817  * routines always check for attnum > # of attributes in tuple, and return
5818  * NULL if so, so without any modification of the tuple data we will get
5819  * the effect of NULL values in the new column.
5820  *
5821  * An exception occurs when the new column is of a domain type: the domain
5822  * might have a NOT NULL constraint, or a check constraint that indirectly
5823  * rejects nulls. If there are any domain constraints then we construct
5824  * an explicit NULL default value that will be passed through
5825  * CoerceToDomain processing. (This is a tad inefficient, since it causes
5826  * rewriting the table which we really don't have to do, but the present
5827  * design of domain processing doesn't offer any simple way of checking
5828  * the constraints more directly.)
5829  *
5830  * Note: we use build_column_default, and not just the cooked default
5831  * returned by AddRelationNewConstraints, so that the right thing happens
5832  * when a datatype's default applies.
5833  *
5834  * We skip this step completely for views and foreign tables. For a view,
5835  * we can only get here from CREATE OR REPLACE VIEW, which historically
5836  * doesn't set up defaults, not even for domain-typed columns. And in any
5837  * case we mustn't invoke Phase 3 on a view or foreign table, since they
5838  * have no storage.
5839  */
5840  if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE
5841  && relkind != RELKIND_FOREIGN_TABLE && attribute.attnum > 0)
5842  {
5843  /*
5844  * For an identity column, we can't use build_column_default(),
5845  * because the sequence ownership isn't set yet. So do it manually.
5846  */
5847  if (colDef->identity)
5848  {
5850 
5851  nve->seqid = RangeVarGetRelid(colDef->identitySequence, NoLock, false);
5852  nve->typeId = typeOid;
5853 
5854  defval = (Expr *) nve;
5855 
5856  /* must do a rewrite for identity columns */
5858  }
5859  else
5860  defval = (Expr *) build_column_default(rel, attribute.attnum);
5861 
5862  if (!defval && DomainHasConstraints(typeOid))
5863  {
5864  Oid baseTypeId;
5865  int32 baseTypeMod;
5866  Oid baseTypeColl;
5867 
5868  baseTypeMod = typmod;
5869  baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
5870  baseTypeColl = get_typcollation(baseTypeId);
5871  defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
5872  defval = (Expr *) coerce_to_target_type(NULL,
5873  (Node *) defval,
5874  baseTypeId,
5875  typeOid,
5876  typmod,
5879  -1);
5880  if (defval == NULL) /* should not happen */
5881  elog(ERROR, "failed to coerce base type to domain");
5882  }
5883 
5884  if (defval)
5885  {
5887 
5888  newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
5889  newval->attnum = attribute.attnum;
5890  newval->expr = expression_planner(defval);
5891 
5892  tab->newvals = lappend(tab->newvals, newval);
5893  }
5894 
5895  if (DomainHasConstraints(typeOid))
5897 
5898  if (!TupleDescAttr(rel->rd_att, attribute.attnum - 1)->atthasmissing)
5899  {
5900  /*
5901  * If the new column is NOT NULL, and there is no missing value,
5902  * tell Phase 3 it needs to check for NULLs.
5903  */
5904  tab->verify_new_notnull |= colDef->is_not_null;
5905  }
5906  }
5907 
5908  /*
5909  * Add needed dependency entries for the new column.
5910  */
5911  add_column_datatype_dependency(myrelid, newattnum, attribute.atttypid);
5912  add_column_collation_dependency(myrelid, newattnum, attribute.attcollation);
5913 
5914  /*
5915  * Propagate to children as appropriate. Unlike most other ALTER
5916  * routines, we have to do this one level of recursion at a time; we can't
5917  * use find_all_inheritors to do it in one pass.
5918  */
5919  children = find_inheritance_children(RelationGetRelid(rel), lockmode);
5920 
5921  /*
5922  * If we are told not to recurse, there had better not be any child
5923  * tables; else the addition would put them out of step.
5924  */
5925  if (children && !recurse)
5926  ereport(ERROR,
5927  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5928  errmsg("column must be added to child tables too")));
5929 
5930  /* Children should see column as singly inherited */
5931  if (!recursing)
5932  {
5933  colDef = copyObject(colDef);
5934  colDef->inhcount = 1;
5935  colDef->is_local = false;
5936  }
5937 
5938  foreach(child, children)
5939  {
5940  Oid childrelid = lfirst_oid(child);
5941  Relation childrel;
5942  AlteredTableInfo *childtab;
5943 
5944  /* find_inheritance_children already got lock */
5945  childrel = table_open(childrelid, NoLock);
5946  CheckTableNotInUse(childrel, "ALTER TABLE");
5947 
5948  /* Find or create work queue entry for this table */
5949  childtab = ATGetQueueEntry(wqueue, childrel);
5950 
5951  /* Recurse to child; return value is ignored */
5952  ATExecAddColumn(wqueue, childtab, childrel,
5953  colDef, recurse, true,
5954  if_not_exists, lockmode);
5955 
5956  table_close(childrel, NoLock);
5957  }
5958 
5959  ObjectAddressSubSet(address, RelationRelationId, myrelid, newattnum);
5960  return address;
5961 }
#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:525
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:6021
#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:6039
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:453
static AlteredTableInfo * ATGetQueueEntry(List **wqueue, Relation rel)
Definition: tablecmds.c:5083
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:322
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:980
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:573
#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:949
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:5968
#define elog(elevel,...)
Definition: elog.h:226
int inhcount
Definition: parsenodes.h:648
static void ATSimplePermissions(Relation rel, int allowed_targets)
Definition: tablecmds.c:5120
char * colname
Definition: parsenodes.h:646
#define copyObject(obj)
Definition: nodes.h:641
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:419
#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:5591
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 7373 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().

7376 {
7378 
7379  Assert(IsA(newConstraint, Constraint));
7380 
7381  /*
7382  * Currently, we only expect to see CONSTR_CHECK and CONSTR_FOREIGN nodes
7383  * arriving here (see the preprocessing done in parse_utilcmd.c). Use a
7384  * switch anyway to make it easier to add more code later.
7385  */
7386  switch (newConstraint->contype)
7387  {
7388  case CONSTR_CHECK:
7389  address =
7390  ATAddCheckConstraint(wqueue, tab, rel,
7391  newConstraint, recurse, false, is_readd,
7392  lockmode);
7393  break;
7394 
7395  case CONSTR_FOREIGN:
7396 
7397  /*
7398  * Assign or validate constraint name
7399  */
7400  if (newConstraint->conname)
7401  {
7403  RelationGetRelid(rel),
7404  newConstraint->conname))
7405  ereport(ERROR,
7407  errmsg("constraint \"%s\" for relation \"%s\" already exists",
7408  newConstraint->conname,
7409  RelationGetRelationName(rel))));
7410  }
7411  else
7412  newConstraint->conname =
7415  "fkey",
7416  RelationGetNamespace(rel),
7417  NIL);
7418 
7419  address = ATAddForeignKeyConstraint(wqueue, tab, rel,
7420  newConstraint, InvalidOid,
7421  recurse, false,
7422  lockmode);
7423  break;
7424 
7425  default:
7426  elog(ERROR, "unrecognized constraint type: %d",
7427  (int) newConstraint->contype);
7428  }
7429 
7430  return address;
7431 }
#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:576
bool ConstraintNameIsUsed(ConstraintCategory conCat, Oid objId, const char *conname)
static char * ChooseForeignKeyConstraintNameAddition(List *colnames)
Definition: tablecmds.c:7446
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:7488
char * conname
Definition: parsenodes.h:2132
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:453
#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:7624
ConstrType contype
Definition: parsenodes.h:2129
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:33
#define RelationGetRelid(relation)
Definition: rel.h:419
List * fk_attrs
Definition: parsenodes.h:2164
#define RelationGetNamespace(relation)
Definition: rel.h:460

◆ ATExecAddIdentity()

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

Definition at line 6472 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().

6474 {
6475  Relation attrelation;
6476  HeapTuple tuple;
6477  Form_pg_attribute attTup;
6479  ObjectAddress address;
6480  ColumnDef *cdef = castNode(ColumnDef, def);
6481 
6482  attrelation = table_open(AttributeRelationId, RowExclusiveLock);
6483 
6484  tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
6485  if (!HeapTupleIsValid(tuple))
6486  ereport(ERROR,
6487  (errcode(ERRCODE_UNDEFINED_COLUMN),
6488  errmsg("column \"%s\" of relation \"%s\" does not exist",
6489  colName, RelationGetRelationName(rel))));
6490  attTup = (Form_pg_attribute) GETSTRUCT(tuple);
6491  attnum = attTup->attnum;
6492 
6493  /* Can't alter a system attribute */
6494  if (attnum <= 0)
6495  ereport(ERROR,
6496  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6497  errmsg("cannot alter system column \"%s\"",
6498  colName)));
6499 
6500  /*
6501  * Creating a column as identity implies NOT NULL, so adding the identity
6502  * to an existing column that is not NOT NULL would create a state that
6503  * cannot be reproduced without contortions.
6504  */
6505  if (!attTup->attnotnull)
6506  ereport(ERROR,
6507  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6508  errmsg("column \"%s\" of relation \"%s\" must be declared NOT NULL before identity can be added",
6509  colName, RelationGetRelationName(rel))));
6510 
6511  if (attTup->attidentity)
6512  ereport(ERROR,
6513  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6514  errmsg("column \"%s\" of relation \"%s\" is already an identity column",
6515  colName, RelationGetRelationName(rel))));
6516 
6517  if (attTup->atthasdef)
6518  ereport(ERROR,
6519  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6520  errmsg("column \"%s\" of relation \"%s\" already has a default value",
6521  colName, RelationGetRelationName(rel))));
6522 
6523  attTup->attidentity = cdef->identity;
6524  CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
6525 
6526  InvokeObjectPostAlterHook(RelationRelationId,
6527  RelationGetRelid(rel),
6528  attTup->attnum);
6529  ObjectAddressSubSet(address, RelationRelationId,
6530  RelationGetRelid(rel), attnum);
6531  heap_freetuple(tuple);
6532 
6533  table_close(attrelation, RowExclusiveLock);
6534 
6535  return address;
6536 }
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:594
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:453
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:419

◆ ATExecAddIndex()

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

Definition at line 7226 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().

7228 {
7229  bool check_rights;
7230  bool skip_build;
7231  bool quiet;
7232  ObjectAddress address;
7233 
7234  Assert(IsA(stmt, IndexStmt));
7235  Assert(!stmt->concurrent);
7236 
7237  /* The IndexStmt has already been through transformIndexStmt */
7238  Assert(stmt->transformed);
7239 
7240  /* suppress schema rights check when rebuilding existing index */
7241  check_rights = !is_rebuild;
7242  /* skip index build if phase 3 will do it or we're reusing an old one */
7243  skip_build = tab->rewrite > 0 || OidIsValid(stmt->oldNode);
7244  /* suppress notices when rebuilding existing index */
7245  quiet = is_rebuild;
7246 
7247  address = DefineIndex(RelationGetRelid(rel),
7248  stmt,
7249  InvalidOid, /* no predefined OID */
7250  InvalidOid, /* no parent index */
7251  InvalidOid, /* no parent constraint */
7252  true, /* is_alter_table */
7253  check_rights,
7254  false, /* check_not_in_use - we did it already */
7255  skip_build,
7256  quiet);
7257 
7258  /*
7259  * If TryReuseIndex() stashed a relfilenode for us, we used it for the new
7260  * index instead of building from scratch. The DROP of the old edition of
7261  * this index will have scheduled the storage for deletion at commit, so
7262  * cancel that pending deletion.
7263  */
7264  if (OidIsValid(stmt->oldNode))
7265  {
7266  Relation irel = index_open(address.objectId, NoLock);
7267 
7268  RelationPreserveStorage(irel->rd_node, true);
7269  index_close(irel, NoLock);
7270  }
7271 
7272  return address;
7273 }
void RelationPreserveStorage(RelFileNode rnode, bool atCommit)
Definition: storage.c:193
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
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:430
#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:419
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 7281 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().

7283 {
7284  Oid index_oid = stmt->indexOid;
7285  Relation indexRel;
7286  char *indexName;
7287  IndexInfo *indexInfo;
7288  char *constraintName;
7289  char constraintType;
7290  ObjectAddress address;
7291  bits16 flags;
7292 
7293  Assert(IsA(stmt, IndexStmt));
7294  Assert(OidIsValid(index_oid));
7295  Assert(stmt->isconstraint);
7296 
7297  /*
7298  * Doing this on partitioned tables is not a simple feature to implement,
7299  * so let's punt for now.
7300  */
7301  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
7302  ereport(ERROR,
7303  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7304  errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX is not supported on partitioned tables")));
7305 
7306  indexRel = index_open(index_oid, AccessShareLock);
7307 
7308  indexName = pstrdup(RelationGetRelationName(indexRel));
7309 
7310  indexInfo = BuildIndexInfo(indexRel);
7311 
7312  /* this should have been checked at parse time */
7313  if (!indexInfo->ii_Unique)
7314  elog(ERROR, "index \"%s\" is not unique", indexName);
7315 
7316  /*
7317  * Determine name to assign to constraint. We require a constraint to
7318  * have the same name as the underlying index; therefore, use the index's
7319  * existing name as the default constraint name, and if the user
7320  * explicitly gives some other name for the constraint, rename the index
7321  * to match.
7322  */
7323  constraintName = stmt->idxname;
7324  if (constraintName == NULL)
7325  constraintName = indexName;
7326  else if (strcmp(constraintName, indexName) != 0)
7327  {
7328  ereport(NOTICE,
7329  (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
7330  indexName, constraintName)));
7331  RenameRelationInternal(index_oid, constraintName, false, true);
7332  }
7333 
7334  /* Extra checks needed if making primary key */
7335  if (stmt->primary)
7336  index_check_primary_key(rel, indexInfo, true, stmt);
7337 
7338  /* Note we currently don't support EXCLUSION constraints here */
7339  if (stmt->primary)
7340  constraintType = CONSTRAINT_PRIMARY;
7341  else
7342  constraintType = CONSTRAINT_UNIQUE;
7343 
7344  /* Create the catalog entries for the constraint */
7350 
7351  address = index_constraint_create(rel,
7352  index_oid,
7353  InvalidOid,
7354  indexInfo,
7355  constraintName,
7356  constraintType,
7357  flags,
7359  false); /* is_internal */
7360 
7361  index_close(indexRel, NoLock);
7362 
7363  return address;
7364 }
bool deferrable
Definition: parsenodes.h:2768
bool primary
Definition: parsenodes.h:2766
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
uint16 bits16
Definition: c.h:366
char * pstrdup(const char *in)
Definition: mcxt.c:1186
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:570
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2275
#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:453
#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:1782

◆ ATExecAddInherit()

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

Definition at line 12815 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().

12816 {
12817  Relation parent_rel;
12818  List *children;
12819  ObjectAddress address;
12820  const char *trigger_name;
12821 
12822  /*
12823  * A self-exclusive lock is needed here. See the similar case in
12824  * MergeAttributes() for a full explanation.
12825  */
12826  parent_rel = table_openrv(parent, ShareUpdateExclusiveLock);
12827 
12828  /*
12829  * Must be owner of both parent and child -- child was checked by
12830  * ATSimplePermissions call in ATPrepCmd
12831  */
12833 
12834  /* Permanent rels cannot inherit from temporary ones */
12835  if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
12836  child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
12837  ereport(ERROR,
12838  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12839  errmsg("cannot inherit from temporary relation \"%s\"",
12840  RelationGetRelationName(parent_rel))));
12841 
12842  /* If parent rel is temp, it must belong to this session */
12843  if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
12844  !parent_rel->rd_islocaltemp)
12845  ereport(ERROR,
12846  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12847  errmsg("cannot inherit from temporary relation of another session")));
12848 
12849  /* Ditto for the child */
12850  if (child_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
12851  !child_rel->rd_islocaltemp)
12852  ereport(ERROR,
12853  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12854  errmsg("cannot inherit to temporary relation of another session")));
12855 
12856  /* Prevent partitioned tables from becoming inheritance parents */
12857  if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
12858  ereport(ERROR,
12859  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12860  errmsg("cannot inherit from partitioned table \"%s\"",
12861  parent->relname)));
12862 
12863  /* Likewise for partitions */
12864  if (parent_rel->rd_rel->relispartition)
12865  ereport(ERROR,
12866  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
12867  errmsg("cannot inherit from a partition")));
12868 
12869  /*
12870  * Prevent circularity by seeing if proposed parent inherits from child.
12871  * (In particular, this disallows making a rel inherit from itself.)
12872  *
12873  * This is not completely bulletproof because of race conditions: in
12874  * multi-level inheritance trees, someone else could concurrently be
12875  * making another inheritance link that closes the loop but does not join
12876  * either of the rels we have locked. Preventing that seems to require
12877  * exclusive locks on the entire inheritance tree, which is a cure worse
12878  * than the disease. find_all_inheritors() will cope with circularity
12879  * anyway, so don't sweat it too much.
12880  *
12881  * We use weakest lock we can on child's children, namely AccessShareLock.
12882  */
12883  children = find_all_inheritors(RelationGetRelid(child_rel),
12884  AccessShareLock, NULL);
12885 
12886  if (list_member_oid(children, RelationGetRelid(parent_rel)))
12887  ereport(ERROR,
12888  (errcode(ERRCODE_DUPLICATE_TABLE),
12889  errmsg("circular inheritance not allowed"),
12890  errdetail("\"%s\" is already a child of \"%s\".",
12891  parent->relname,
12892  RelationGetRelationName(child_rel))));
12893 
12894  /*
12895  * If child_rel has row-level triggers with transition tables, we
12896  * currently don't allow it to become an inheritance child. See also
12897  * prohibitions in ATExecAttachPartition() and CreateTrigger().
12898  */
12899  trigger_name = FindTriggerIncompatibleWithInheritance(child_rel->trigdesc);
12900  if (trigger_name != NULL)
12901  ereport(ERROR,
12902  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
12903  errmsg("trigger \"%s\" prevents table \"%s\" from becoming an inheritance child",
12904  trigger_name, RelationGetRelationName(child_rel)),
12905  errdetail("ROW triggers with transition tables are not supported in inheritance hierarchies.")));
12906 
12907  /* OK to create inheritance */
12908  CreateInheritance(child_rel, parent_rel);
12909 
12910  ObjectAddressSet(address, RelationRelationId,
12911  RelationGetRelid(parent_rel));
12912 
12913  /* keep our lock on the parent relation until commit */
12914  table_close(parent_rel, NoLock);
12915 
12916  return address;
12917 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
bool rd_islocaltemp
Definition: rel.h:59