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/sysattr.h"
#include "access/tableam.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 149 of file tablecmds.c.

Referenced by ATRewriteCatalogs().

◆ AT_PASS_ADD_COL

#define AT_PASS_ADD_COL   4 /* ADD COLUMN */

Definition at line 144 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ AT_PASS_ADD_CONSTR

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

Definition at line 147 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ AT_PASS_ADD_INDEX

#define AT_PASS_ADD_INDEX   6 /* ADD indexes */

Definition at line 146 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ AT_PASS_ALTER_TYPE

#define AT_PASS_ALTER_TYPE   1 /* ALTER COLUMN TYPE */

Definition at line 140 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 145 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ AT_PASS_DROP

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

Definition at line 139 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ AT_PASS_MISC

#define AT_PASS_MISC   8 /* other stuff */

Definition at line 148 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ AT_PASS_OLD_CONSTR

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

Definition at line 142 of file tablecmds.c.

Referenced by ATPostAlterTypeParse().

◆ AT_PASS_OLD_INDEX

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

Definition at line 141 of file tablecmds.c.

Referenced by ATPostAlterTypeParse().

◆ AT_PASS_UNSET

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

Definition at line 138 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ ATT_COMPOSITE_TYPE

#define ATT_COMPOSITE_TYPE   0x0010

Definition at line 288 of file tablecmds.c.

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

◆ ATT_FOREIGN_TABLE

◆ ATT_INDEX

#define ATT_INDEX   0x0008

Definition at line 287 of file tablecmds.c.

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

◆ ATT_MATVIEW

#define ATT_MATVIEW   0x0004

Definition at line 286 of file tablecmds.c.

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

◆ ATT_PARTITIONED_INDEX

#define ATT_PARTITIONED_INDEX   0x0040

Definition at line 290 of file tablecmds.c.

Referenced by ATPrepCmd(), and ATSimplePermissions().

◆ ATT_TABLE

◆ ATT_VIEW

#define ATT_VIEW   0x0002

Definition at line 285 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 297 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 6046 of file tablecmds.c.

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

Referenced by ATExecAddColumn(), and ATExecAlterColumnType().

6047 {
6048  ObjectAddress myself,
6049  referenced;
6050 
6051  /* We know the default collation is pinned, so don't bother recording it */
6052  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
6053  {
6054  myself.classId = RelationRelationId;
6055  myself.objectId = relid;
6056  myself.objectSubId = attnum;
6057  referenced.classId = CollationRelationId;
6058  referenced.objectId = collid;
6059  referenced.objectSubId = 0;
6060  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
6061  }
6062 }
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
#define OidIsValid(objectId)
Definition: c.h:645
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 6028 of file tablecmds.c.

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

Referenced by ATExecAddColumn(), and ATExecAlterColumnType().

6029 {
6030  ObjectAddress myself,
6031  referenced;
6032 
6033  myself.classId = RelationRelationId;
6034  myself.objectId = relid;
6035  myself.objectSubId = attnum;
6036  referenced.classId = TypeRelationId;
6037  referenced.objectId = typid;
6038  referenced.objectSubId = 0;
6039  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
6040 }
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 8070 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().

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

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

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

◆ AlterIndexNamespaces()

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

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

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

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

◆ AlterSeqNamespaces()

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

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

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

◆ AlterTable()

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

Definition at line 3502 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3503 {
3504  Relation rel;
3505 
3506  /* Caller is required to provide an adequate lock. */
3507  rel = relation_open(relid, NoLock);
3508 
3509  CheckTableNotInUse(rel, "ALTER TABLE");
3510 
3511  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode);
3512 }
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
Definition: tablecmds.c:3832
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:3423
bool inh
Definition: primnodes.h:69
RangeVar * relation
Definition: parsenodes.h:1753

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)

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

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

◆ AlterTableInternal()

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

Definition at line 3526 of file tablecmds.c.

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

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

3527 {
3528  Relation rel;
3529  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
3530 
3531  rel = relation_open(relid, lockmode);
3532 
3534 
3535  ATController(NULL, rel, cmds, recurse, lockmode);
3536 }
int LOCKMODE
Definition: lockdefs.h:26
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
Definition: tablecmds.c:3832
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:3571
void EventTriggerAlterTableRelid(Oid objectId)

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 3451 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3452 {
3453  return RangeVarGetRelidExtended(stmt->relation, lockmode,
3454  stmt->missing_ok ? RVR_MISSING_OK : 0,
3456  (void *) stmt);
3457 }
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:14872
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 12554 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().

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

14251 {
14252  Relation rel;
14253  Oid relid;
14254  Oid oldNspOid;
14255  Oid nspOid;
14256  RangeVar *newrv;
14257  ObjectAddresses *objsMoved;
14258  ObjectAddress myself;
14259 
14261  stmt->missing_ok ? RVR_MISSING_OK : 0,
14263  (void *) stmt);
14264 
14265  if (!OidIsValid(relid))
14266  {
14267  ereport(NOTICE,
14268  (errmsg("relation \"%s\" does not exist, skipping",
14269  stmt->relation->relname)));
14270  return InvalidObjectAddress;
14271  }
14272 
14273  rel = relation_open(relid, NoLock);
14274 
14275  oldNspOid = RelationGetNamespace(rel);
14276 
14277  /* If it's an owned sequence, disallow moving it by itself. */
14278  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
14279  {
14280  Oid tableId;
14281  int32 colId;
14282 
14283  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
14284  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
14285  ereport(ERROR,
14286  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14287  errmsg("cannot move an owned sequence into another schema"),
14288  errdetail("Sequence \"%s\" is linked to table \"%s\".",
14290  get_rel_name(tableId))));
14291  }
14292 
14293  /* Get and lock schema OID and check its permissions. */
14294  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
14295  nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
14296 
14297  /* common checks on switching namespaces */
14298  CheckSetNamespace(oldNspOid, nspOid);
14299 
14300  objsMoved = new_object_addresses();
14301  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
14302  free_object_addresses(objsMoved);
14303 
14304  ObjectAddressSet(myself, RelationRelationId, relid);
14305 
14306  if (oldschema)
14307  *oldschema = oldNspOid;
14308 
14309  /* close rel, but keep lock until commit */
14310  relation_close(rel, NoLock);
14311 
14312  return myself;
14313 }
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition: pg_depend.c:663
int errcode(int sqlerrcode)
Definition: elog.c:608
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2402
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2697
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
signed int int32
Definition: c.h:347
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:14321
#define NoLock
Definition: lockdefs.h:34
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:14872
int errdetail(const char *fmt,...)
Definition: elog.c:955
#define RelationGetRelationName(relation)
Definition: rel.h:456
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:822
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:463

◆ AlterTableNamespaceInternal()

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

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

14323 {
14324  Relation classRel;
14325 
14326  Assert(objsMoved != NULL);
14327 
14328  /* OK, modify the pg_class row and pg_depend entry */
14329  classRel = table_open(RelationRelationId, RowExclusiveLock);
14330 
14331  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
14332  nspOid, true, objsMoved);
14333 
14334  /* Fix the table's row type too */
14335  AlterTypeNamespaceInternal(rel->rd_rel->reltype,
14336  nspOid, false, false, objsMoved);
14337 
14338  /* Fix other dependent stuff */
14339  if (rel->rd_rel->relkind == RELKIND_RELATION ||
14340  rel->rd_rel->relkind == RELKIND_MATVIEW ||
14341  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
14342  {
14343  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
14344  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
14345  objsMoved, AccessExclusiveLock);
14346  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
14347  false, objsMoved);
14348  }
14349 
14350  table_close(classRel, RowExclusiveLock);
14351 }
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:14429
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:14474
#define RowExclusiveLock
Definition: lockdefs.h:38
#define Assert(condition)
Definition: c.h:739
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:14359
#define AccessExclusiveLock
Definition: lockdefs.h:45
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:422

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

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

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

5294 {
5295  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
5296  {
5297  List *inh;
5298  ListCell *cell;
5299 
5300  inh = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
5301  /* first element is the parent rel; must ignore it */
5302  for_each_cell(cell, inh, list_second_cell(inh))
5303  {
5304  Relation childrel;
5305 
5306  /* find_all_inheritors already got lock */
5307  childrel = table_open(lfirst_oid(cell), NoLock);
5308  CheckTableNotInUse(childrel, "ALTER TABLE");
5309  table_close(childrel, NoLock);
5310  }
5311  list_free(inh);
5312  }
5313 }
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:3423
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:422
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ ATColumnChangeRequiresRewrite()

static bool ATColumnChangeRequiresRewrite ( Node expr,
AttrNumber  varattno 
)
static

Definition at line 10552 of file tablecmds.c.

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

Referenced by ATPrepAlterColumnType().

10553 {
10554  Assert(expr != NULL);
10555 
10556  for (;;)
10557  {
10558  /* only one varno, so no need to check that */
10559  if (IsA(expr, Var) &&((Var *) expr)->varattno == varattno)
10560  return false;
10561  else if (IsA(expr, RelabelType))
10562  expr = (Node *) ((RelabelType *) expr)->arg;
10563  else if (IsA(expr, CoerceToDomain))
10564  {
10565  CoerceToDomain *d = (CoerceToDomain *) expr;
10566 
10568  return true;
10569  expr = (Node *) d->arg;
10570  }
10571  else if (IsA(expr, FuncExpr))
10572  {
10573  FuncExpr *f = (FuncExpr *) expr;
10574 
10575  switch (f->funcid)
10576  {
10577  case F_TIMESTAMPTZ_TIMESTAMP:
10578  case F_TIMESTAMP_TIMESTAMPTZ:
10580  return true;
10581  else
10582  expr = linitial(f->args);
10583  break;
10584  default:
10585  return true;
10586  }
10587  }
10588  else
10589  return true;
10590  }
10591 }
#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:739
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 3832 of file tablecmds.c.

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

Referenced by AlterTable(), and AlterTableInternal().

3834 {
3835  List *wqueue = NIL;
3836  ListCell *lcmd;
3837 
3838  /* Phase 1: preliminary examination of commands, create work queue */
3839  foreach(lcmd, cmds)
3840  {
3841  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3842 
3843  ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode);
3844  }
3845 
3846  /* Close the relation, but keep lock until commit */
3847  relation_close(rel, NoLock);
3848 
3849  /* Phase 2: update system catalogs */
3850  ATRewriteCatalogs(&wqueue, lockmode);
3851 
3852  /* Phase 3: scan/rewrite tables as needed */
3853  ATRewriteTables(parsetree, &wqueue, lockmode);
3854 }
#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:4508
static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
Definition: tablecmds.c:3866
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:4161
Definition: pg_list.h:50

◆ ATDetachCheckNoForeignKeyRefs()

static void ATDetachCheckNoForeignKeyRefs ( Relation  partition)
static

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

16691 {
16692  List *constraints;
16693  ListCell *cell;
16694 
16695  constraints = GetParentedForeignKeyRefs(partition);
16696 
16697  foreach(cell, constraints)
16698  {
16699  Oid constrOid = lfirst_oid(cell);
16700  HeapTuple tuple;
16701  Form_pg_constraint constrForm;
16702  Relation rel;
16703  Trigger trig;
16704 
16705  tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
16706  if (!HeapTupleIsValid(tuple))
16707  elog(ERROR, "cache lookup failed for constraint %u", constrOid);
16708  constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
16709 
16710  Assert(OidIsValid(constrForm->conparentid));
16711  Assert(constrForm->confrelid == RelationGetRelid(partition));
16712 
16713  /* prevent data changes into the referencing table until commit */
16714  rel = table_open(constrForm->conrelid, ShareLock);
16715 
16716  MemSet(&trig, 0, sizeof(trig));
16717  trig.tgoid = InvalidOid;
16718  trig.tgname = NameStr(constrForm->conname);
16720  trig.tgisinternal = true;
16721  trig.tgconstrrelid = RelationGetRelid(partition);
16722  trig.tgconstrindid = constrForm->conindid;
16723  trig.tgconstraint = constrForm->oid;
16724  trig.tgdeferrable = false;
16725  trig.tginitdeferred = false;
16726  /* we needn't fill in remaining fields */
16727 
16728  RI_PartitionRemove_Check(&trig, rel, partition);
16729 
16730  ReleaseSysCache(tuple);
16731 
16732  table_close(rel, NoLock);
16733  }
16734 }
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:16637
Oid tgoid
Definition: reltrigger.h:25
bool tgisinternal
Definition: reltrigger.h:31
#define MemSet(start, val, len)
Definition: c.h:962
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
#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:1570
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:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#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:739
Oid tgconstrindid
Definition: reltrigger.h:33
#define elog(elevel,...)
Definition: elog.h:228
#define ShareLock
Definition: lockdefs.h:41
#define NameStr(name)
Definition: c.h:616
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:422
#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 14750 of file tablecmds.c.

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

14752 {
14753  ListCell *cur_item;
14754 
14755  foreach(cur_item, on_commits)
14756  {
14757  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
14758 
14759  if (!isCommit && oc->creating_subid == mySubid)
14760  {
14761  /* cur_item must be removed */
14763  pfree(oc);
14764  }
14765  else
14766  {
14767  /* cur_item must be preserved */
14768  if (oc->creating_subid == mySubid)
14769  oc->creating_subid = parentSubid;
14770  if (oc->deleting_subid == mySubid)
14771  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
14772  }
14773  }
14774 }
SubTransactionId creating_subid
Definition: tablecmds.c:117
#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:121
SubTransactionId deleting_subid
Definition: tablecmds.c:118
#define lfirst(lc)
Definition: pg_list.h:190
#define InvalidSubTransactionId
Definition: c.h:520

◆ AtEOXact_on_commit_actions()

void AtEOXact_on_commit_actions ( bool  isCommit)

Definition at line 14718 of file tablecmds.c.

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

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

14719 {
14720  ListCell *cur_item;
14721 
14722  foreach(cur_item, on_commits)
14723  {
14724  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
14725 
14726  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
14728  {
14729  /* cur_item must be removed */
14731  pfree(oc);
14732  }
14733  else
14734  {
14735  /* cur_item must be preserved */
14738  }
14739  }
14740 }
SubTransactionId creating_subid
Definition: tablecmds.c:117
#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:121
SubTransactionId deleting_subid
Definition: tablecmds.c:118
#define lfirst(lc)
Definition: pg_list.h:190
#define InvalidSubTransactionId
Definition: c.h:520

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

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

◆ ATExecAddConstraint()

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

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

7383 {
7385 
7386  Assert(IsA(newConstraint, Constraint));
7387 
7388  /*
7389  * Currently, we only expect to see CONSTR_CHECK and CONSTR_FOREIGN nodes
7390  * arriving here (see the preprocessing done in parse_utilcmd.c). Use a
7391  * switch anyway to make it easier to add more code later.
7392  */
7393  switch (newConstraint->contype)
7394  {
7395  case CONSTR_CHECK:
7396  address =
7397  ATAddCheckConstraint(wqueue, tab, rel,
7398  newConstraint, recurse, false, is_readd,
7399  lockmode);
7400  break;
7401 
7402  case CONSTR_FOREIGN:
7403 
7404  /*
7405  * Assign or validate constraint name
7406  */
7407  if (newConstraint->conname)
7408  {
7410  RelationGetRelid(rel),
7411  newConstraint->conname))
7412  ereport(ERROR,
7414  errmsg("constraint \"%s\" for relation \"%s\" already exists",
7415  newConstraint->conname,
7416  RelationGetRelationName(rel))));
7417  }
7418  else
7419  newConstraint->conname =
7422  "fkey",
7423  RelationGetNamespace(rel),
7424  NIL);
7425 
7426  address = ATAddForeignKeyConstraint(wqueue, tab, rel,
7427  newConstraint, InvalidOid,
7428  recurse, false,
7429  lockmode);
7430  break;
7431 
7432  default:
7433  elog(ERROR, "unrecognized constraint type: %d",
7434  (int) newConstraint->contype);
7435  }
7436 
7437  return address;
7438 }
#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:7453
int errcode(int sqlerrcode)
Definition: elog.c:608
static ObjectAddress ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *constr, bool recurse, bool recursing, bool is_readd, LOCKMODE lockmode)
Definition: tablecmds.c:7495
char * conname
Definition: parsenodes.h:2132
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:456
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:739
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
static ObjectAddress ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *fkconstraint, Oid parentConstr, bool recurse, bool recursing, LOCKMODE lockmode)
Definition: tablecmds.c:7631
ConstrType contype
Definition: parsenodes.h:2129
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:31
#define RelationGetRelid(relation)
Definition: rel.h:422
List * fk_attrs
Definition: parsenodes.h:2164
#define RelationGetNamespace(relation)
Definition: rel.h:463

◆ ATExecAddIdentity()

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

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

6481 {
6482  Relation attrelation;
6483  HeapTuple tuple;
6484  Form_pg_attribute attTup;
6486  ObjectAddress address;
6487  ColumnDef *cdef = castNode(ColumnDef, def);
6488 
6489  attrelation = table_open(AttributeRelationId, RowExclusiveLock);
6490 
6491  tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
6492  if (!HeapTupleIsValid(tuple))
6493  ereport(ERROR,
6494  (errcode(ERRCODE_UNDEFINED_COLUMN),
6495  errmsg("column \"%s\" of relation \"%s\" does not exist",
6496  colName, RelationGetRelationName(rel))));
6497  attTup = (Form_pg_attribute) GETSTRUCT(tuple);
6498  attnum = attTup->attnum;
6499 
6500  /* Can't alter a system attribute */
6501  if (attnum <= 0)
6502  ereport(ERROR,
6503  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6504  errmsg("cannot alter system column \"%s\"",
6505  colName)));
6506 
6507  /*
6508  * Creating a column as identity implies NOT NULL, so adding the identity
6509  * to an existing column that is not NOT NULL would create a state that
6510  * cannot be reproduced without contortions.
6511  */
6512  if (!attTup->attnotnull)
6513  ereport(ERROR,
6514  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6515  errmsg("column \"%s\" of relation \"%s\" must be declared NOT NULL before identity can be added",
6516  colName, RelationGetRelationName(rel))));
6517 
6518  if (attTup->attidentity)
6519  ereport(ERROR,
6520  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6521  errmsg("column \"%s\" of relation \"%s\" is already an identity column",
6522  colName, RelationGetRelationName(rel))));
6523 
6524  if (attTup->atthasdef)
6525  ereport(ERROR,
6526  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6527  errmsg("column \"%s\" of relation \"%s\" already has a default value",
6528  colName, RelationGetRelationName(rel))));
6529 
6530  attTup->attidentity = cdef->identity;
6531  CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
6532 
6533  InvokeObjectPostAlterHook(RelationRelationId,
6534  RelationGetRelid(rel),
6535  attTup->attnum);
6536  ObjectAddressSubSet(address, RelationRelationId,
6537  RelationGetRelid(rel), attnum);
6538  heap_freetuple(tuple);
6539 
6540  table_close(attrelation, RowExclusiveLock);
6541 
6542  return address;
6543 }
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:608
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:1280
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:456
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:175
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:822
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:422

◆ ATExecAddIndex()

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

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

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

7290 {
7291  Oid index_oid = stmt->indexOid;
7292  Relation indexRel;
7293  char *indexName;
7294  IndexInfo *indexInfo;
7295  char *constraintName;
7296  char constraintType;
7297  ObjectAddress address;
7298  bits16 flags;
7299 
7300  Assert(IsA(stmt, IndexStmt));
7301  Assert(OidIsValid(index_oid));
7302  Assert(stmt->isconstraint);
7303 
7304  /*
7305  * Doing this on partitioned tables is not a simple feature to implement,
7306  * so let's punt for now.
7307  */
7308  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
7309  ereport(ERROR,
7310  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7311  errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX is not supported on partitioned tables")));
7312 
7313  indexRel = index_open(index_oid, AccessShareLock);
7314 
7315  indexName = pstrdup(RelationGetRelationName(indexRel));
7316 
7317  indexInfo = BuildIndexInfo(indexRel);
7318 
7319  /* this should have been checked at parse time */
7320  if (!indexInfo->ii_Unique)
7321  elog(ERROR, "index \"%s\" is not unique", indexName);
7322 
7323  /*
7324  * Determine name to assign to constraint. We require a constraint to
7325  * have the same name as the underlying index; therefore, use the index's
7326  * existing name as the default constraint name, and if the user
7327  * explicitly gives some other name for the constraint, rename the index
7328  * to match.
7329  */
7330  constraintName = stmt->idxname;
7331  if (constraintName == NULL)
7332  constraintName = indexName;
7333  else if (strcmp(constraintName, indexName) != 0)
7334  {
7335  ereport(NOTICE,
7336  (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
7337  indexName, constraintName)));
7338  RenameRelationInternal(index_oid, constraintName, false, true);
7339  }
7340 
7341  /* Extra checks needed if making primary key */
7342  if (stmt->primary)
7343  index_check_primary_key(rel, indexInfo, true, stmt);
7344 
7345  /* Note we currently don't support EXCLUSION constraints here */
7346  if (stmt->primary)
7347  constraintType = CONSTRAINT_PRIMARY;
7348  else
7349  constraintType = CONSTRAINT_UNIQUE;
7350 
7351  /* Create the catalog entries for the constraint */
7357 
7358  address = index_constraint_create(rel,
7359  index_oid,
7360  InvalidOid,
7361  indexInfo,
7362  constraintName,
7363  constraintType,
7364  flags,
7366  false); /* is_internal */
7367 
7368  index_close(indexRel, NoLock);
7369 
7370  return address;
7371 }
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:367
char * pstrdup(const char *in)
Definition: mcxt.c:1186
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:608
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2285
#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:200
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
#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:456
#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:169
#define Assert(condition)
Definition: c.h:739
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:822
#define elog(elevel,...)
Definition: elog.h:228
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
Definition: tablecmds.c:3321
#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:1788

◆ ATExecAddInherit()

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

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

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