PostgreSQL Source Code  git master
tablecmds.c File Reference
#include "postgres.h"
#include "access/attmap.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/toast_compression.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "access/xloginsert.h"
#include "catalog/catalog.h"
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/namespace.h"
#include "catalog/objectaccess.h"
#include "catalog/partition.h"
#include "catalog/pg_am.h"
#include "catalog/pg_attrdef.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_largeobject.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_statistic_ext.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 "commands/vacuum.h"
#include "executor/executor.h"
#include "foreign/fdwapi.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 "tcop/utility.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 "utils/usercontext.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  ForeignTruncateInfo
 
struct  AttachIndexCallbackState
 

Macros

#define AT_NUM_PASSES   (AT_PASS_MISC + 1)
 
#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 ATT_SEQUENCE   0x0080
 
#define child_dependency_type(child_is_partition)    ((child_is_partition) ? DEPENDENCY_AUTO : DEPENDENCY_NORMAL)
 

Typedefs

typedef struct OnCommitItem OnCommitItem
 
typedef enum AlterTablePass AlterTablePass
 
typedef struct AlteredTableInfo AlteredTableInfo
 
typedef struct NewConstraint NewConstraint
 
typedef struct NewColumnValue NewColumnValue
 
typedef struct ForeignTruncateInfo ForeignTruncateInfo
 

Enumerations

enum  AlterTablePass {
  AT_PASS_UNSET = -1 , AT_PASS_DROP , AT_PASS_ALTER_TYPE , AT_PASS_ADD_COL ,
  AT_PASS_SET_EXPRESSION , AT_PASS_OLD_INDEX , AT_PASS_OLD_CONSTR , AT_PASS_ADD_CONSTR ,
  AT_PASS_COL_ATTRS , AT_PASS_ADD_INDEXCONSTR , AT_PASS_ADD_INDEX , AT_PASS_ADD_OTHERCONSTR ,
  AT_PASS_MISC
}
 

Functions

static void truncate_check_rel (Oid relid, Form_pg_class reltuple)
 
static void truncate_check_perms (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 *columns, const List *supers, char relpersistence, bool is_partition, List **supconstr, List **supnotnulls)
 
static ListMergeCheckConstraint (List *constraints, const char *name, Node *expr)
 
static void MergeChildAttribute (List *inh_columns, int exist_attno, int newcol_attno, const ColumnDef *newdef)
 
static ColumnDefMergeInheritedAttribute (List *inh_columns, int exist_attno, const ColumnDef *newdef)
 
static void MergeAttributesIntoExisting (Relation child_rel, Relation parent_rel, bool ispartition)
 
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, const List *columns)
 
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 bool ATExecAlterConstrRecurse (Constraint *cmdcon, Relation conrel, Relation tgrel, Relation rel, HeapTuple contuple, List **otherrelids, LOCKMODE lockmode)
 
static ObjectAddress ATExecValidateConstraint (List **wqueue, 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 validateForeignKeyConstraint (char *conname, Relation rel, Relation pkrel, Oid pkindOid, Oid constraintOid)
 
static void ATController (AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
static void ATPrepCmd (List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
static void ATRewriteCatalogs (List **wqueue, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
static void ATExecCmd (List **wqueue, AlteredTableInfo *tab, AlterTableCmd *cmd, LOCKMODE lockmode, AlterTablePass cur_pass, AlterTableUtilityContext *context)
 
static AlterTableCmdATParseTransformCmd (List **wqueue, AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode, AlterTablePass cur_pass, AlterTableUtilityContext *context)
 
static void ATRewriteTables (AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
static void ATRewriteTable (AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode)
 
static AlteredTableInfoATGetQueueEntry (List **wqueue, Relation rel)
 
static void ATSimplePermissions (AlterTableType cmdtype, Relation rel, int allowed_targets)
 
static void ATSimpleRecursion (List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
static void ATCheckPartitionsNotInUse (Relation rel, LOCKMODE lockmode)
 
static void ATTypedTableRecursion (List **wqueue, Relation rel, AlterTableCmd *cmd, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
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, AlterTableUtilityContext *context)
 
static ObjectAddress ATExecAddColumn (List **wqueue, AlteredTableInfo *tab, Relation rel, AlterTableCmd **cmd, bool recurse, bool recursing, LOCKMODE lockmode, AlterTablePass cur_pass, AlterTableUtilityContext *context)
 
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 ObjectAddress ATExecDropNotNull (Relation rel, const char *colName, bool recurse, LOCKMODE lockmode)
 
static bool set_attnotnull (List **wqueue, Relation rel, AttrNumber attnum, bool recurse, LOCKMODE lockmode)
 
static ObjectAddress ATExecSetNotNull (List **wqueue, Relation rel, char *constrname, char *colName, bool recurse, bool recursing, List **readyRels, LOCKMODE lockmode)
 
static ObjectAddress ATExecSetAttNotNull (List **wqueue, 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 ATExecCookedColumnDefault (Relation rel, AttrNumber attnum, Node *newDefault)
 
static ObjectAddress ATExecAddIdentity (Relation rel, const char *colName, Node *def, LOCKMODE lockmode, bool recurse, bool recursing)
 
static ObjectAddress ATExecSetIdentity (Relation rel, const char *colName, Node *def, LOCKMODE lockmode, bool recurse, bool recursing)
 
static ObjectAddress ATExecDropIdentity (Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode, bool recurse, bool recursing)
 
static ObjectAddress ATExecSetExpression (AlteredTableInfo *tab, Relation rel, const char *colName, Node *newExpr, LOCKMODE lockmode)
 
static void ATPrepDropExpression (Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
 
static ObjectAddress ATExecDropExpression (Relation rel, const char *colName, bool missing_ok, 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, AlterTableUtilityContext *context)
 
static ObjectAddress ATExecDropColumn (List **wqueue, Relation rel, const char *colName, DropBehavior behavior, bool recurse, bool recursing, bool missing_ok, LOCKMODE lockmode, ObjectAddresses *addrs)
 
static void ATPrepAddPrimaryKey (List **wqueue, Relation rel, AlterTableCmd *cmd, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
static ObjectAddress ATExecAddIndex (AlteredTableInfo *tab, Relation rel, IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
 
static ObjectAddress ATExecAddStatistics (AlteredTableInfo *tab, Relation rel, CreateStatsStmt *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 ATAddCheckNNConstraint (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, 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, int numfkdelsetcols, int16 *fkdelsetcols, bool old_check_ok, Oid parentDelTrigger, Oid parentUpdTrigger)
 
static void validateFkOnDeleteSetColumns (int numfks, const int16 *fkattnums, int numfksetcols, const int16 *fksetcolsattnums, List *fksetcols)
 
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, int numfkdelsetcols, int16 *fkdelsetcols, bool old_check_ok, LOCKMODE lockmode, Oid parentInsTrigger, Oid parentUpdTrigger)
 
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, Oid parentInsTrigger, Oid parentUpdTrigger, Oid *insertTrigOid, Oid *updateTrigOid)
 
static void createForeignKeyActionTriggers (Relation rel, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid, Oid parentDelTrigger, Oid parentUpdTrigger, Oid *deleteTrigOid, Oid *updateTrigOid)
 
static bool tryAttachPartitionForeignKey (ForeignKeyCacheInfo *fk, Oid partRelid, Oid parentConstrOid, int numfks, AttrNumber *mapped_conkey, AttrNumber *confkey, Oid *conpfeqop, Oid parentInsTrigger, Oid parentUpdTrigger, Relation trigrel)
 
static void GetForeignKeyActionTriggers (Relation trigrel, Oid conoid, Oid confrelid, Oid conrelid, Oid *deleteTriggerOid, Oid *updateTriggerOid)
 
static void GetForeignKeyCheckTriggers (Relation trigrel, Oid conoid, Oid confrelid, Oid conrelid, Oid *insertTriggerOid, Oid *updateTriggerOid)
 
static void ATExecDropConstraint (Relation rel, const char *constrName, DropBehavior behavior, bool recurse, bool missing_ok, LOCKMODE lockmode)
 
static ObjectAddress dropconstraint_internal (Relation rel, HeapTuple constraintTup, DropBehavior behavior, bool recurse, bool recursing, bool missing_ok, List **readyRels, LOCKMODE lockmode)
 
static void ATPrepAlterColumnType (List **wqueue, AlteredTableInfo *tab, Relation rel, bool recurse, bool recursing, AlterTableCmd *cmd, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
static bool ATColumnChangeRequiresRewrite (Node *expr, AttrNumber varattno)
 
static ObjectAddress ATExecAlterColumnType (AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static void RememberAllDependentForRebuilding (AlteredTableInfo *tab, AlterTableType subtype, Relation rel, AttrNumber attnum, const char *colName)
 
static void RememberConstraintForRebuilding (Oid conoid, AlteredTableInfo *tab)
 
static void RememberIndexForRebuilding (Oid indoid, AlteredTableInfo *tab)
 
static void RememberStatisticsForRebuilding (Oid stxoid, 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, AlterTablePass 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 void ATPrepSetAccessMethod (AlteredTableInfo *tab, Relation rel, const char *amname)
 
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, bool recurse, 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 ATExecSetRowSecurity (Relation rel, bool rls)
 
static void ATExecForceNoForceRowSecurity (Relation rel, bool force_rls)
 
static ObjectAddress ATExecSetCompression (Relation rel, const char *column, Node *newValue, LOCKMODE lockmode)
 
static void index_copy_data (Relation rel, RelFileLocator newrlocator)
 
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)
 
static void ComputePartitionAttrs (ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs, List **partexprs, Oid *partopclass, Oid *partcollation, PartitionStrategy strategy)
 
static void CreateInheritance (Relation child_rel, Relation parent_rel, bool ispartition)
 
static void RemoveInheritance (Relation child_rel, Relation parent_rel, bool expect_detached)
 
static void ATInheritAdjustNotNulls (Relation parent_rel, Relation child_rel, int inhcount)
 
static ObjectAddress ATExecAttachPartition (List **wqueue, Relation rel, PartitionCmd *cmd, AlterTableUtilityContext *context)
 
static void AttachPartitionEnsureIndexes (List **wqueue, Relation rel, Relation attachrel)
 
static void QueuePartitionConstraintValidation (List **wqueue, Relation scanrel, List *partConstraint, bool validate_default)
 
static void CloneRowTriggersToPartition (Relation parent, Relation partition)
 
static void DetachAddConstraintIfNeeded (List **wqueue, Relation partRel)
 
static void DropClonedTriggersFromPartition (Oid partitionId)
 
static ObjectAddress ATExecDetachPartition (List **wqueue, AlteredTableInfo *tab, Relation rel, RangeVar *name, bool concurrent)
 
static void DetachPartitionFinalize (Relation rel, Relation partRel, bool concurrent, Oid defaultPartOid)
 
static ObjectAddress ATExecDetachPartitionFinalize (Relation rel, RangeVar *name)
 
static ObjectAddress ATExecAttachPartitionIdx (List **wqueue, Relation parentIdx, RangeVar *name)
 
static void validatePartitionedIndex (Relation partedIdx, Relation partedTbl)
 
static void refuseDupeIndexAttach (Relation parentIdx, Relation partIdx, Relation partitionTbl)
 
static void verifyPartitionIndexNotNull (IndexInfo *iinfo, Relation partIdx)
 
static ListGetParentedForeignKeyRefs (Relation partition)
 
static void ATDetachCheckNoForeignKeyRefs (Relation partition)
 
static char GetAttributeCompression (Oid atttypid, const char *compression)
 
static char GetAttributeStorage (Oid atttypid, const char *storagemode)
 
ObjectAddress DefineRelation (CreateStmt *stmt, char relkind, Oid ownerId, ObjectAddress *typaddress, const char *queryString)
 
TupleDesc BuildDescForRelation (const List *columns)
 
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, bool run_as_table_owner)
 
void SetRelationHasSubclass (Oid relationId, bool relhassubclass)
 
bool CheckRelationTableSpaceMove (Relation rel, Oid newTableSpaceId)
 
void SetRelationTableSpace (Relation rel, Oid newTableSpaceId, RelFileNumber newRelFilenumber)
 
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 ResetRelRewrite (Oid myrelid)
 
void CheckTableNotInUse (Relation rel, const char *stmt)
 
Oid AlterTableLookupRelation (AlterTableStmt *stmt, LOCKMODE lockmode)
 
void AlterTable (AlterTableStmt *stmt, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
void AlterTableInternal (Oid relid, List *cmds, bool recurse)
 
LOCKMODE AlterTableGetLockLevel (List *cmds)
 
static const char * alter_table_type_to_string (AlterTableType cmdtype)
 
void find_composite_type_dependencies (Oid typeOid, Relation origRelation, const char *origTypeName)
 
void check_of_type (HeapTuple typetuple)
 
static void SetIndexStorageProperties (Relation rel, Relation attrelation, AttrNumber attnum, bool setstorage, char newstorage, bool setcompression, char newcompression, LOCKMODE lockmode)
 
static Oid CreateFKCheckTrigger (Oid myRelOid, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid, Oid parentTrigOid, bool on_insert)
 
static void RememberReplicaIdentityForRebuilding (Oid indoid, AlteredTableInfo *tab)
 
static void RememberClusterOnForRebuilding (Oid indoid, AlteredTableInfo *tab)
 
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 MarkInheritDetached (Relation child_rel, Relation parent_rel)
 
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   (AT_PASS_MISC + 1)

Definition at line 163 of file tablecmds.c.

◆ ATT_COMPOSITE_TYPE

#define ATT_COMPOSITE_TYPE   0x0010

Definition at line 326 of file tablecmds.c.

◆ ATT_FOREIGN_TABLE

#define ATT_FOREIGN_TABLE   0x0020

Definition at line 327 of file tablecmds.c.

◆ ATT_INDEX

#define ATT_INDEX   0x0008

Definition at line 325 of file tablecmds.c.

◆ ATT_MATVIEW

#define ATT_MATVIEW   0x0004

Definition at line 324 of file tablecmds.c.

◆ ATT_PARTITIONED_INDEX

#define ATT_PARTITIONED_INDEX   0x0040

Definition at line 328 of file tablecmds.c.

◆ ATT_SEQUENCE

#define ATT_SEQUENCE   0x0080

Definition at line 329 of file tablecmds.c.

◆ ATT_TABLE

#define ATT_TABLE   0x0001

Definition at line 322 of file tablecmds.c.

◆ ATT_VIEW

#define ATT_VIEW   0x0002

Definition at line 323 of file tablecmds.c.

◆ child_dependency_type

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

Definition at line 350 of file tablecmds.c.

Typedef Documentation

◆ AlteredTableInfo

◆ AlterTablePass

◆ ForeignTruncateInfo

◆ NewColumnValue

◆ NewConstraint

typedef struct NewConstraint NewConstraint

◆ OnCommitItem

typedef struct OnCommitItem OnCommitItem

Enumeration Type Documentation

◆ AlterTablePass

Enumerator
AT_PASS_UNSET 
AT_PASS_DROP 
AT_PASS_ALTER_TYPE 
AT_PASS_ADD_COL 
AT_PASS_SET_EXPRESSION 
AT_PASS_OLD_INDEX 
AT_PASS_OLD_CONSTR 
AT_PASS_ADD_CONSTR 
AT_PASS_COL_ATTRS 
AT_PASS_ADD_INDEXCONSTR 
AT_PASS_ADD_INDEX 
AT_PASS_ADD_OTHERCONSTR 
AT_PASS_MISC 

Definition at line 145 of file tablecmds.c.

146 {
147  AT_PASS_UNSET = -1, /* UNSET will cause ERROR */
148  AT_PASS_DROP, /* DROP (all flavors) */
149  AT_PASS_ALTER_TYPE, /* ALTER COLUMN TYPE */
150  AT_PASS_ADD_COL, /* ADD COLUMN */
151  AT_PASS_SET_EXPRESSION, /* ALTER SET EXPRESSION */
152  AT_PASS_OLD_INDEX, /* re-add existing indexes */
153  AT_PASS_OLD_CONSTR, /* re-add existing constraints */
154  /* We could support a RENAME COLUMN pass here, but not currently used */
155  AT_PASS_ADD_CONSTR, /* ADD constraints (initial examination) */
156  AT_PASS_COL_ATTRS, /* set column attributes, eg NOT NULL */
157  AT_PASS_ADD_INDEXCONSTR, /* ADD index-based constraints */
158  AT_PASS_ADD_INDEX, /* ADD indexes */
159  AT_PASS_ADD_OTHERCONSTR, /* ADD other constraints, defaults */
160  AT_PASS_MISC, /* other stuff */
AlterTablePass
Definition: tablecmds.c:146
@ AT_PASS_ADD_CONSTR
Definition: tablecmds.c:155
@ AT_PASS_ADD_OTHERCONSTR
Definition: tablecmds.c:159
@ AT_PASS_OLD_CONSTR
Definition: tablecmds.c:153
@ AT_PASS_ADD_COL
Definition: tablecmds.c:150
@ AT_PASS_OLD_INDEX
Definition: tablecmds.c:152
@ AT_PASS_ALTER_TYPE
Definition: tablecmds.c:149
@ AT_PASS_ADD_INDEXCONSTR
Definition: tablecmds.c:157
@ AT_PASS_DROP
Definition: tablecmds.c:148
@ AT_PASS_MISC
Definition: tablecmds.c:160
@ AT_PASS_COL_ATTRS
Definition: tablecmds.c:156
@ AT_PASS_SET_EXPRESSION
Definition: tablecmds.c:151
@ AT_PASS_ADD_INDEX
Definition: tablecmds.c:158
@ AT_PASS_UNSET
Definition: tablecmds.c:147

Function Documentation

◆ add_column_collation_dependency()

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

Definition at line 7493 of file tablecmds.c.

7494 {
7495  ObjectAddress myself,
7496  referenced;
7497 
7498  /* We know the default collation is pinned, so don't bother recording it */
7499  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
7500  {
7501  myself.classId = RelationRelationId;
7502  myself.objectId = relid;
7503  myself.objectSubId = attnum;
7504  referenced.classId = CollationRelationId;
7505  referenced.objectId = collid;
7506  referenced.objectSubId = 0;
7507  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
7508  }
7509 }
#define OidIsValid(objectId)
Definition: c.h:764
Oid collid
@ DEPENDENCY_NORMAL
Definition: dependency.h:33
int16 attnum
Definition: pg_attribute.h:74
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44

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

Referenced by ATExecAddColumn(), and ATExecAlterColumnType().

◆ add_column_datatype_dependency()

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

Definition at line 7475 of file tablecmds.c.

7476 {
7477  ObjectAddress myself,
7478  referenced;
7479 
7480  myself.classId = RelationRelationId;
7481  myself.objectId = relid;
7482  myself.objectSubId = attnum;
7483  referenced.classId = TypeRelationId;
7484  referenced.objectId = typid;
7485  referenced.objectSubId = 0;
7486  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
7487 }

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

Referenced by ATExecAddColumn(), and ATExecAlterColumnType().

◆ 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,
int  numfkdelsetcols,
int16 fkdelsetcols,
bool  old_check_ok,
Oid  parentDelTrigger,
Oid  parentUpdTrigger 
)
static

Definition at line 10291 of file tablecmds.c.

10299 {
10300  ObjectAddress address;
10301  Oid constrOid;
10302  char *conname;
10303  bool conislocal;
10304  int coninhcount;
10305  bool connoinherit;
10306  Oid deleteTriggerOid,
10307  updateTriggerOid;
10308 
10309  /*
10310  * Verify relkind for each referenced partition. At the top level, this
10311  * is redundant with a previous check, but we need it when recursing.
10312  */
10313  if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
10314  pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
10315  ereport(ERROR,
10316  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10317  errmsg("referenced relation \"%s\" is not a table",
10318  RelationGetRelationName(pkrel))));
10319 
10320  /*
10321  * Caller supplies us with a constraint name; however, it may be used in
10322  * this partition, so come up with a different one in that case.
10323  */
10325  RelationGetRelid(rel),
10326  fkconstraint->conname))
10329  "fkey",
10330  RelationGetNamespace(rel), NIL);
10331  else
10332  conname = fkconstraint->conname;
10333 
10334  if (OidIsValid(parentConstr))
10335  {
10336  conislocal = false;
10337  coninhcount = 1;
10338  connoinherit = false;
10339  }
10340  else
10341  {
10342  conislocal = true;
10343  coninhcount = 0;
10344 
10345  /*
10346  * always inherit for partitioned tables, never for legacy inheritance
10347  */
10348  connoinherit = rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE;
10349  }
10350 
10351  /*
10352  * Record the FK constraint in pg_constraint.
10353  */
10354  constrOid = CreateConstraintEntry(conname,
10355  RelationGetNamespace(rel),
10356  CONSTRAINT_FOREIGN,
10357  fkconstraint->deferrable,
10358  fkconstraint->initdeferred,
10359  fkconstraint->initially_valid,
10360  parentConstr,
10361  RelationGetRelid(rel),
10362  fkattnum,
10363  numfks,
10364  numfks,
10365  InvalidOid, /* not a domain constraint */
10366  indexOid,
10367  RelationGetRelid(pkrel),
10368  pkattnum,
10369  pfeqoperators,
10370  ppeqoperators,
10371  ffeqoperators,
10372  numfks,
10373  fkconstraint->fk_upd_action,
10374  fkconstraint->fk_del_action,
10375  fkdelsetcols,
10376  numfkdelsetcols,
10377  fkconstraint->fk_matchtype,
10378  NULL, /* no exclusion constraint */
10379  NULL, /* no check constraint */
10380  NULL,
10381  conislocal, /* islocal */
10382  coninhcount, /* inhcount */
10383  connoinherit, /* conNoInherit */
10384  false, /* conWithoutOverlaps */
10385  false); /* is_internal */
10386 
10387  ObjectAddressSet(address, ConstraintRelationId, constrOid);
10388 
10389  /*
10390  * Mark the child constraint as part of the parent constraint; it must not
10391  * be dropped on its own. (This constraint is deleted when the partition
10392  * is detached, but a special check needs to occur that the partition
10393  * contains no referenced values.)
10394  */
10395  if (OidIsValid(parentConstr))
10396  {
10397  ObjectAddress referenced;
10398 
10399  ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
10400  recordDependencyOn(&address, &referenced, DEPENDENCY_INTERNAL);
10401  }
10402 
10403  /* make new constraint visible, in case we add more */
10405 
10406  /*
10407  * Create the action triggers that enforce the constraint.
10408  */
10410  fkconstraint,
10411  constrOid, indexOid,
10412  parentDelTrigger, parentUpdTrigger,
10413  &deleteTriggerOid, &updateTriggerOid);
10414 
10415  /*
10416  * If the referenced table is partitioned, recurse on ourselves to handle
10417  * each partition. We need one pg_constraint row created for each
10418  * partition in addition to the pg_constraint row for the parent table.
10419  */
10420  if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
10421  {
10422  PartitionDesc pd = RelationGetPartitionDesc(pkrel, true);
10423 
10424  for (int i = 0; i < pd->nparts; i++)
10425  {
10426  Relation partRel;
10427  AttrMap *map;
10428  AttrNumber *mapped_pkattnum;
10429  Oid partIndexId;
10430 
10431  partRel = table_open(pd->oids[i], ShareRowExclusiveLock);
10432 
10433  /*
10434  * Map the attribute numbers in the referenced side of the FK
10435  * definition to match the partition's column layout.
10436  */
10438  RelationGetDescr(pkrel),
10439  false);
10440  if (map)
10441  {
10442  mapped_pkattnum = palloc(sizeof(AttrNumber) * numfks);
10443  for (int j = 0; j < numfks; j++)
10444  mapped_pkattnum[j] = map->attnums[pkattnum[j] - 1];
10445  }
10446  else
10447  mapped_pkattnum = pkattnum;
10448 
10449  /* do the deed */
10450  partIndexId = index_get_partition(partRel, indexOid);
10451  if (!OidIsValid(partIndexId))
10452  elog(ERROR, "index for %u not found in partition %s",
10453  indexOid, RelationGetRelationName(partRel));
10454  addFkRecurseReferenced(wqueue, fkconstraint, rel, partRel,
10455  partIndexId, constrOid, numfks,
10456  mapped_pkattnum, fkattnum,
10457  pfeqoperators, ppeqoperators, ffeqoperators,
10458  numfkdelsetcols, fkdelsetcols,
10459  old_check_ok,
10460  deleteTriggerOid, updateTriggerOid);
10461 
10462  /* Done -- clean up (but keep the lock) */
10463  table_close(partRel, NoLock);
10464  if (map)
10465  {
10466  pfree(mapped_pkattnum);
10467  free_attrmap(map);
10468  }
10469  }
10470  }
10471 
10472  return address;
10473 }
void free_attrmap(AttrMap *map)
Definition: attmap.c:57
AttrMap * build_attrmap_by_name_if_req(TupleDesc indesc, TupleDesc outdesc, bool missing_ok)
Definition: attmap.c:264
int16 AttrNumber
Definition: attnum.h:21
@ DEPENDENCY_INTERNAL
Definition: dependency.h:35
int errcode(int sqlerrcode)
Definition: elog.c:860
int errmsg(const char *fmt,...)
Definition: elog.c:1075
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
int j
Definition: isn.c:74
int i
Definition: isn.c:73
#define NoLock
Definition: lockdefs.h:34
#define ShareRowExclusiveLock
Definition: lockdefs.h:41
void pfree(void *pointer)
Definition: mcxt.c:1431
void * palloc(Size size)
Definition: mcxt.c:1201
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
PartitionDesc RelationGetPartitionDesc(Relation rel, bool omit_detached)
Definition: partdesc.c:72
Oid index_get_partition(Relation partition, Oid indexId)
Definition: partition.c:177
char * ChooseConstraintName(const char *name1, const char *name2, const char *label, Oid namespaceid, List *others)
bool ConstraintNameIsUsed(ConstraintCategory conCat, Oid objId, const char *conname)
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, const int16 *fkDeleteSetCols, int numFkDeleteSetCols, char foreignMatchType, const Oid *exclOp, Node *conExpr, const char *conBin, bool conIsLocal, int conInhCount, bool conNoInherit, bool conWithoutOverlaps, bool is_internal)
Definition: pg_constraint.c:51
@ CONSTRAINT_RELATION
#define NIL
Definition: pg_list.h:68
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define RelationGetRelid(relation)
Definition: rel.h:504
#define RelationGetDescr(relation)
Definition: rel.h:530
#define RelationGetRelationName(relation)
Definition: rel.h:538
#define RelationGetNamespace(relation)
Definition: rel.h:545
Definition: attmap.h:35
AttrNumber * attnums
Definition: attmap.h:36
bool initdeferred
Definition: parsenodes.h:2573
char fk_upd_action
Definition: parsenodes.h:2605
char fk_matchtype
Definition: parsenodes.h:2604
bool initially_valid
Definition: parsenodes.h:2575
bool deferrable
Definition: parsenodes.h:2572
char * conname
Definition: parsenodes.h:2571
char fk_del_action
Definition: parsenodes.h:2606
List * fk_attrs
Definition: parsenodes.h:2602
Form_pg_class rd_rel
Definition: rel.h:111
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
static char * ChooseForeignKeyConstraintNameAddition(List *colnames)
Definition: tablecmds.c:9604
static void createForeignKeyActionTriggers(Relation rel, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid, Oid parentDelTrigger, Oid parentUpdTrigger, Oid *deleteTrigOid, Oid *updateTrigOid)
Definition: tablecmds.c:12497
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, int numfkdelsetcols, int16 *fkdelsetcols, bool old_check_ok, Oid parentDelTrigger, Oid parentUpdTrigger)
Definition: tablecmds.c:10291
void CommandCounterIncrement(void)
Definition: xact.c:1078

References AttrMap::attnums, build_attrmap_by_name_if_req(), ChooseConstraintName(), ChooseForeignKeyConstraintNameAddition(), CommandCounterIncrement(), Constraint::conname, CONSTRAINT_RELATION, ConstraintNameIsUsed(), 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, free_attrmap(), i, index_get_partition(), Constraint::initdeferred, Constraint::initially_valid, InvalidOid, j, 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().

◆ 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,
int  numfkdelsetcols,
int16 fkdelsetcols,
bool  old_check_ok,
LOCKMODE  lockmode,
Oid  parentInsTrigger,
Oid  parentUpdTrigger 
)
static

Definition at line 10512 of file tablecmds.c.

10519 {
10520  Oid insertTriggerOid,
10521  updateTriggerOid;
10522 
10523  Assert(OidIsValid(parentConstr));
10524 
10525  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
10526  ereport(ERROR,
10527  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10528  errmsg("foreign key constraints are not supported on foreign tables")));
10529 
10530  /*
10531  * Add the check triggers to it and, if necessary, schedule it to be
10532  * checked in Phase 3.
10533  *
10534  * If the relation is partitioned, drill down to do it to its partitions.
10535  */
10537  RelationGetRelid(pkrel),
10538  fkconstraint,
10539  parentConstr,
10540  indexOid,
10541  parentInsTrigger, parentUpdTrigger,
10542  &insertTriggerOid, &updateTriggerOid);
10543 
10544  if (rel->rd_rel->relkind == RELKIND_RELATION)
10545  {
10546  /*
10547  * Tell Phase 3 to check that the constraint is satisfied by existing
10548  * rows. We can skip this during table creation, when requested
10549  * explicitly by specifying NOT VALID in an ADD FOREIGN KEY command,
10550  * and when we're recreating a constraint following a SET DATA TYPE
10551  * operation that did not impugn its validity.
10552  */
10553  if (wqueue && !old_check_ok && !fkconstraint->skip_validation)
10554  {
10555  NewConstraint *newcon;
10556  AlteredTableInfo *tab;
10557 
10558  tab = ATGetQueueEntry(wqueue, rel);
10559 
10560  newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
10561  newcon->name = get_constraint_name(parentConstr);
10562  newcon->contype = CONSTR_FOREIGN;
10563  newcon->refrelid = RelationGetRelid(pkrel);
10564  newcon->refindid = indexOid;
10565  newcon->conid = parentConstr;
10566  newcon->qual = (Node *) fkconstraint;
10567 
10568  tab->constraints = lappend(tab->constraints, newcon);
10569  }
10570  }
10571  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
10572  {
10573  PartitionDesc pd = RelationGetPartitionDesc(rel, true);
10574  Relation trigrel;
10575 
10576  /*
10577  * Triggers of the foreign keys will be manipulated a bunch of times
10578  * in the loop below. To avoid repeatedly opening/closing the trigger
10579  * catalog relation, we open it here and pass it to the subroutines
10580  * called below.
10581  */
10582  trigrel = table_open(TriggerRelationId, RowExclusiveLock);
10583 
10584  /*
10585  * Recurse to take appropriate action on each partition; either we
10586  * find an existing constraint to reparent to ours, or we create a new
10587  * one.
10588  */
10589  for (int i = 0; i < pd->nparts; i++)
10590  {
10591  Oid partitionId = pd->oids[i];
10592  Relation partition = table_open(partitionId, lockmode);
10593  List *partFKs;
10594  AttrMap *attmap;
10595  AttrNumber mapped_fkattnum[INDEX_MAX_KEYS];
10596  bool attached;
10597  char *conname;
10598  Oid constrOid;
10599  ObjectAddress address,
10600  referenced;
10601  ListCell *cell;
10602 
10603  CheckTableNotInUse(partition, "ALTER TABLE");
10604 
10605  attmap = build_attrmap_by_name(RelationGetDescr(partition),
10606  RelationGetDescr(rel),
10607  false);
10608  for (int j = 0; j < numfks; j++)
10609  mapped_fkattnum[j] = attmap->attnums[fkattnum[j] - 1];
10610 
10611  /* Check whether an existing constraint can be repurposed */
10612  partFKs = copyObject(RelationGetFKeyList(partition));
10613  attached = false;
10614  foreach(cell, partFKs)
10615  {
10616  ForeignKeyCacheInfo *fk;
10617 
10618  fk = lfirst_node(ForeignKeyCacheInfo, cell);
10620  partitionId,
10621  parentConstr,
10622  numfks,
10623  mapped_fkattnum,
10624  pkattnum,
10625  pfeqoperators,
10626  insertTriggerOid,
10627  updateTriggerOid,
10628  trigrel))
10629  {
10630  attached = true;
10631  break;
10632  }
10633  }
10634  if (attached)
10635  {
10636  table_close(partition, NoLock);
10637  continue;
10638  }
10639 
10640  /*
10641  * No luck finding a good constraint to reuse; create our own.
10642  */
10644  RelationGetRelid(partition),
10645  fkconstraint->conname))
10646  conname = ChooseConstraintName(RelationGetRelationName(partition),
10648  "fkey",
10649  RelationGetNamespace(partition), NIL);
10650  else
10651  conname = fkconstraint->conname;
10652  constrOid =
10653  CreateConstraintEntry(conname,
10654  RelationGetNamespace(partition),
10655  CONSTRAINT_FOREIGN,
10656  fkconstraint->deferrable,
10657  fkconstraint->initdeferred,
10658  fkconstraint->initially_valid,
10659  parentConstr,
10660  partitionId,
10661  mapped_fkattnum,
10662  numfks,
10663  numfks,
10664  InvalidOid,
10665  indexOid,
10666  RelationGetRelid(pkrel),
10667  pkattnum,
10668  pfeqoperators,
10669  ppeqoperators,
10670  ffeqoperators,
10671  numfks,
10672  fkconstraint->fk_upd_action,
10673  fkconstraint->fk_del_action,
10674  fkdelsetcols,
10675  numfkdelsetcols,
10676  fkconstraint->fk_matchtype,
10677  NULL,
10678  NULL,
10679  NULL,
10680  false,
10681  1,
10682  false,
10683  false, /* conWithoutOverlaps */
10684  false);
10685 
10686  /*
10687  * Give this constraint partition-type dependencies on the parent
10688  * constraint as well as the table.
10689  */
10690  ObjectAddressSet(address, ConstraintRelationId, constrOid);
10691  ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
10692  recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_PRI);
10693  ObjectAddressSet(referenced, RelationRelationId, partitionId);
10694  recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_SEC);
10695 
10696  /* Make all this visible before recursing */
10698 
10699  /* call ourselves to finalize the creation and we're done */
10700  addFkRecurseReferencing(wqueue, fkconstraint, partition, pkrel,
10701  indexOid,
10702  constrOid,
10703  numfks,
10704  pkattnum,
10705  mapped_fkattnum,
10706  pfeqoperators,
10707  ppeqoperators,
10708  ffeqoperators,
10709  numfkdelsetcols,
10710  fkdelsetcols,
10711  old_check_ok,
10712  lockmode,
10713  insertTriggerOid,
10714  updateTriggerOid);
10715 
10716  table_close(partition, NoLock);
10717  }
10718 
10719  table_close(trigrel, RowExclusiveLock);
10720  }
10721 }
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc, bool missing_ok)
Definition: attmap.c:178
@ DEPENDENCY_PARTITION_PRI
Definition: dependency.h:36
@ DEPENDENCY_PARTITION_SEC
Definition: dependency.h:37
Assert(fmt[strlen(fmt) - 1] !='\n')
List * lappend(List *list, void *datum)
Definition: list.c:339
#define RowExclusiveLock
Definition: lockdefs.h:38
char * get_constraint_name(Oid conoid)
Definition: lsyscache.c:1080
void * palloc0(Size size)
Definition: mcxt.c:1232
#define copyObject(obj)
Definition: nodes.h:223
@ CONSTR_FOREIGN
Definition: parsenodes.h:2548
#define INDEX_MAX_KEYS
#define lfirst_node(type, lc)
Definition: pg_list.h:176
List * RelationGetFKeyList(Relation relation)
Definition: relcache.c:4646
List * constraints
Definition: tablecmds.c:184
bool skip_validation
Definition: parsenodes.h:2574
Definition: pg_list.h:54
char * name
Definition: tablecmds.c:211
ConstrType contype
Definition: tablecmds.c:212
Node * qual
Definition: tablecmds.c:216
Definition: nodes.h:129
static AlteredTableInfo * ATGetQueueEntry(List **wqueue, Relation rel)
Definition: tablecmds.c:6382
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:4335
static bool tryAttachPartitionForeignKey(ForeignKeyCacheInfo *fk, Oid partRelid, Oid parentConstrOid, int numfks, AttrNumber *mapped_conkey, AttrNumber *confkey, Oid *conpfeqop, Oid parentInsTrigger, Oid parentUpdTrigger, Relation trigrel)
Definition: tablecmds.c:11242
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, int numfkdelsetcols, int16 *fkdelsetcols, bool old_check_ok, LOCKMODE lockmode, Oid parentInsTrigger, Oid parentUpdTrigger)
Definition: tablecmds.c:10512
static void createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid, Oid parentInsTrigger, Oid parentUpdTrigger, Oid *insertTrigOid, Oid *updateTrigOid)
Definition: tablecmds.c:12632

References Assert(), ATGetQueueEntry(), AttrMap::attnums, build_attrmap_by_name(), CheckTableNotInUse(), ChooseConstraintName(), ChooseForeignKeyConstraintNameAddition(), CommandCounterIncrement(), NewConstraint::conid, Constraint::conname, CONSTR_FOREIGN, CONSTRAINT_RELATION, ConstraintNameIsUsed(), AlteredTableInfo::constraints, NewConstraint::contype, 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, j, 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, RowExclusiveLock, Constraint::skip_validation, table_close(), table_open(), and tryAttachPartitionForeignKey().

Referenced by ATAddForeignKeyConstraint(), and CloneFkReferencing().

◆ alter_table_type_to_string()

static const char* alter_table_type_to_string ( AlterTableType  cmdtype)
static

Definition at line 6415 of file tablecmds.c.

6416 {
6417  switch (cmdtype)
6418  {
6419  case AT_AddColumn:
6420  case AT_AddColumnToView:
6421  return "ADD COLUMN";
6422  case AT_ColumnDefault:
6424  return "ALTER COLUMN ... SET DEFAULT";
6425  case AT_DropNotNull:
6426  return "ALTER COLUMN ... DROP NOT NULL";
6427  case AT_SetNotNull:
6428  return "ALTER COLUMN ... SET NOT NULL";
6429  case AT_SetAttNotNull:
6430  return NULL; /* not real grammar */
6431  case AT_SetExpression:
6432  return "ALTER COLUMN ... SET EXPRESSION";
6433  case AT_DropExpression:
6434  return "ALTER COLUMN ... DROP EXPRESSION";
6435  case AT_SetStatistics:
6436  return "ALTER COLUMN ... SET STATISTICS";
6437  case AT_SetOptions:
6438  return "ALTER COLUMN ... SET";
6439  case AT_ResetOptions:
6440  return "ALTER COLUMN ... RESET";
6441  case AT_SetStorage:
6442  return "ALTER COLUMN ... SET STORAGE";
6443  case AT_SetCompression:
6444  return "ALTER COLUMN ... SET COMPRESSION";
6445  case AT_DropColumn:
6446  return "DROP COLUMN";
6447  case AT_AddIndex:
6448  case AT_ReAddIndex:
6449  return NULL; /* not real grammar */
6450  case AT_AddConstraint:
6451  case AT_ReAddConstraint:
6453  case AT_AddIndexConstraint:
6454  return "ADD CONSTRAINT";
6455  case AT_AlterConstraint:
6456  return "ALTER CONSTRAINT";
6457  case AT_ValidateConstraint:
6458  return "VALIDATE CONSTRAINT";
6459  case AT_DropConstraint:
6460  return "DROP CONSTRAINT";
6461  case AT_ReAddComment:
6462  return NULL; /* not real grammar */
6463  case AT_AlterColumnType:
6464  return "ALTER COLUMN ... SET DATA TYPE";
6466  return "ALTER COLUMN ... OPTIONS";
6467  case AT_ChangeOwner:
6468  return "OWNER TO";
6469  case AT_ClusterOn:
6470  return "CLUSTER ON";
6471  case AT_DropCluster:
6472  return "SET WITHOUT CLUSTER";
6473  case AT_SetAccessMethod:
6474  return "SET ACCESS METHOD";
6475  case AT_SetLogged:
6476  return "SET LOGGED";
6477  case AT_SetUnLogged:
6478  return "SET UNLOGGED";
6479  case AT_DropOids:
6480  return "SET WITHOUT OIDS";
6481  case AT_SetTableSpace:
6482  return "SET TABLESPACE";
6483  case AT_SetRelOptions:
6484  return "SET";
6485  case AT_ResetRelOptions:
6486  return "RESET";
6487  case AT_ReplaceRelOptions:
6488  return NULL; /* not real grammar */
6489  case AT_EnableTrig:
6490  return "ENABLE TRIGGER";
6491  case AT_EnableAlwaysTrig:
6492  return "ENABLE ALWAYS TRIGGER";
6493  case AT_EnableReplicaTrig:
6494  return "ENABLE REPLICA TRIGGER";
6495  case AT_DisableTrig:
6496  return "DISABLE TRIGGER";
6497  case AT_EnableTrigAll:
6498  return "ENABLE TRIGGER ALL";
6499  case AT_DisableTrigAll:
6500  return "DISABLE TRIGGER ALL";
6501  case AT_EnableTrigUser:
6502  return "ENABLE TRIGGER USER";
6503  case AT_DisableTrigUser:
6504  return "DISABLE TRIGGER USER";
6505  case AT_EnableRule:
6506  return "ENABLE RULE";
6507  case AT_EnableAlwaysRule:
6508  return "ENABLE ALWAYS RULE";
6509  case AT_EnableReplicaRule:
6510  return "ENABLE REPLICA RULE";
6511  case AT_DisableRule:
6512  return "DISABLE RULE";
6513  case AT_AddInherit:
6514  return "INHERIT";
6515  case AT_DropInherit:
6516  return "NO INHERIT";
6517  case AT_AddOf:
6518  return "OF";
6519  case AT_DropOf:
6520  return "NOT OF";
6521  case AT_ReplicaIdentity:
6522  return "REPLICA IDENTITY";
6523  case AT_EnableRowSecurity:
6524  return "ENABLE ROW SECURITY";
6525  case AT_DisableRowSecurity:
6526  return "DISABLE ROW SECURITY";
6527  case AT_ForceRowSecurity:
6528  return "FORCE ROW SECURITY";
6529  case AT_NoForceRowSecurity:
6530  return "NO FORCE ROW SECURITY";
6531  case AT_GenericOptions:
6532  return "OPTIONS";
6533  case AT_AttachPartition:
6534  return "ATTACH PARTITION";
6535  case AT_DetachPartition:
6536  return "DETACH PARTITION";
6538  return "DETACH PARTITION ... FINALIZE";
6539  case AT_AddIdentity:
6540  return "ALTER COLUMN ... ADD IDENTITY";
6541  case AT_SetIdentity:
6542  return "ALTER COLUMN ... SET";
6543  case AT_DropIdentity:
6544  return "ALTER COLUMN ... DROP IDENTITY";
6545  case AT_ReAddStatistics:
6546  return NULL; /* not real grammar */
6547  }
6548 
6549  return NULL;
6550 }
@ AT_AddIndexConstraint
Definition: parsenodes.h:2210
@ AT_DropOf
Definition: parsenodes.h:2241
@ AT_SetOptions
Definition: parsenodes.h:2198
@ AT_DropIdentity
Definition: parsenodes.h:2253
@ AT_SetAttNotNull
Definition: parsenodes.h:2194
@ AT_DisableTrigUser
Definition: parsenodes.h:2233
@ AT_DropNotNull
Definition: parsenodes.h:2192
@ AT_AddOf
Definition: parsenodes.h:2240
@ AT_ResetOptions
Definition: parsenodes.h:2199
@ AT_ReplicaIdentity
Definition: parsenodes.h:2242
@ AT_ReplaceRelOptions
Definition: parsenodes.h:2225
@ AT_EnableRowSecurity
Definition: parsenodes.h:2243
@ AT_AddColumnToView
Definition: parsenodes.h:2189
@ AT_ResetRelOptions
Definition: parsenodes.h:2224
@ AT_EnableReplicaTrig
Definition: parsenodes.h:2228
@ AT_DropOids
Definition: parsenodes.h:2220
@ AT_SetIdentity
Definition: parsenodes.h:2252
@ AT_ReAddStatistics
Definition: parsenodes.h:2254
@ AT_SetUnLogged
Definition: parsenodes.h:2219
@ AT_DisableTrig
Definition: parsenodes.h:2229
@ AT_SetCompression
Definition: parsenodes.h:2201
@ AT_DropExpression
Definition: parsenodes.h:2196
@ AT_AddIndex
Definition: parsenodes.h:2203
@ AT_EnableReplicaRule
Definition: parsenodes.h:2236
@ AT_ReAddIndex
Definition: parsenodes.h:2204
@ AT_DropConstraint
Definition: parsenodes.h:2211
@ AT_SetNotNull
Definition: parsenodes.h:2193
@ AT_ClusterOn
Definition: parsenodes.h:2216
@ AT_AddIdentity
Definition: parsenodes.h:2251
@ AT_ForceRowSecurity
Definition: parsenodes.h:2245
@ AT_EnableAlwaysRule
Definition: parsenodes.h:2235
@ AT_SetAccessMethod
Definition: parsenodes.h:2221
@ AT_AlterColumnType
Definition: parsenodes.h:2213
@ AT_DetachPartitionFinalize
Definition: parsenodes.h:2250
@ AT_AddInherit
Definition: parsenodes.h:2238
@ AT_ReAddDomainConstraint
Definition: parsenodes.h:2207
@ AT_EnableTrig
Definition: parsenodes.h:2226
@ AT_DropColumn
Definition: parsenodes.h:2202
@ AT_ReAddComment
Definition: parsenodes.h:2212
@ AT_AlterColumnGenericOptions
Definition: parsenodes.h:2214
@ AT_DisableTrigAll
Definition: parsenodes.h:2231
@ AT_EnableRule
Definition: parsenodes.h:2234
@ AT_NoForceRowSecurity
Definition: parsenodes.h:2246
@ AT_DetachPartition
Definition: parsenodes.h:2249
@ AT_SetStatistics
Definition: parsenodes.h:2197
@ AT_AttachPartition
Definition: parsenodes.h:2248
@ AT_AddConstraint
Definition: parsenodes.h:2205
@ AT_DropInherit
Definition: parsenodes.h:2239
@ AT_EnableAlwaysTrig
Definition: parsenodes.h:2227
@ AT_SetLogged
Definition: parsenodes.h:2218
@ AT_SetStorage
Definition: parsenodes.h:2200
@ AT_DisableRule
Definition: parsenodes.h:2237
@ AT_DisableRowSecurity
Definition: parsenodes.h:2244
@ AT_SetRelOptions
Definition: parsenodes.h:2223
@ AT_ChangeOwner
Definition: parsenodes.h:2215
@ AT_EnableTrigUser
Definition: parsenodes.h:2232
@ AT_SetExpression
Definition: parsenodes.h:2195
@ AT_ReAddConstraint
Definition: parsenodes.h:2206
@ AT_SetTableSpace
Definition: parsenodes.h:2222
@ AT_GenericOptions
Definition: parsenodes.h:2247
@ AT_ColumnDefault
Definition: parsenodes.h:2190
@ AT_CookedColumnDefault
Definition: parsenodes.h:2191
@ AT_AlterConstraint
Definition: parsenodes.h:2208
@ AT_EnableTrigAll
Definition: parsenodes.h:2230
@ AT_DropCluster
Definition: parsenodes.h:2217
@ AT_ValidateConstraint
Definition: parsenodes.h:2209
@ AT_AddColumn
Definition: parsenodes.h:2188

References AT_AddColumn, AT_AddColumnToView, AT_AddConstraint, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AddInherit, AT_AddOf, AT_AlterColumnGenericOptions, AT_AlterColumnType, AT_AlterConstraint, AT_AttachPartition, AT_ChangeOwner, AT_ClusterOn, AT_ColumnDefault, AT_CookedColumnDefault, AT_DetachPartition, AT_DetachPartitionFinalize, AT_DisableRowSecurity, AT_DisableRule, AT_DisableTrig, AT_DisableTrigAll, AT_DisableTrigUser, AT_DropCluster, AT_DropColumn, AT_DropConstraint, AT_DropExpression, 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_ReAddComment, AT_ReAddConstraint, AT_ReAddDomainConstraint, AT_ReAddIndex, AT_ReAddStatistics, AT_ReplaceRelOptions, AT_ReplicaIdentity, AT_ResetOptions, AT_ResetRelOptions, AT_SetAccessMethod, AT_SetAttNotNull, AT_SetCompression, AT_SetExpression, AT_SetIdentity, AT_SetLogged, AT_SetNotNull, AT_SetOptions, AT_SetRelOptions, AT_SetStatistics, AT_SetStorage, AT_SetTableSpace, AT_SetUnLogged, and AT_ValidateConstraint.

Referenced by ATSimplePermissions().

◆ AlterIndexNamespaces()

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

Definition at line 17742 of file tablecmds.c.

17744 {
17745  List *indexList;
17746  ListCell *l;
17747 
17748  indexList = RelationGetIndexList(rel);
17749 
17750  foreach(l, indexList)
17751  {
17752  Oid indexOid = lfirst_oid(l);
17753  ObjectAddress thisobj;
17754 
17755  thisobj.classId = RelationRelationId;
17756  thisobj.objectId = indexOid;
17757  thisobj.objectSubId = 0;
17758 
17759  /*
17760  * Note: currently, the index will not have its own dependency on the
17761  * namespace, so we don't need to do changeDependencyFor(). There's no
17762  * row type in pg_type, either.
17763  *
17764  * XXX this objsMoved test may be pointless -- surely we have a single
17765  * dependency link from a relation to each index?
17766  */
17767  if (!object_address_present(&thisobj, objsMoved))
17768  {
17769  AlterRelationNamespaceInternal(classRel, indexOid,
17770  oldNspOid, newNspOid,
17771  false, objsMoved);
17772  add_exact_object_address(&thisobj, objsMoved);
17773  }
17774  }
17775 
17776  list_free(indexList);
17777 }
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2648
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2588
void list_free(List *list)
Definition: list.c:1546
#define lfirst_oid(lc)
Definition: pg_list.h:174
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4755
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:17672

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

Referenced by AlterTableNamespaceInternal().

◆ AlterRelationNamespaceInternal()

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

Definition at line 17672 of file tablecmds.c.

17676 {
17677  HeapTuple classTup;
17678  Form_pg_class classForm;
17679  ObjectAddress thisobj;
17680  bool already_done = false;
17681 
17682  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
17683  if (!HeapTupleIsValid(classTup))
17684  elog(ERROR, "cache lookup failed for relation %u", relOid);
17685  classForm = (Form_pg_class) GETSTRUCT(classTup);
17686 
17687  Assert(classForm->relnamespace == oldNspOid);
17688 
17689  thisobj.classId = RelationRelationId;
17690  thisobj.objectId = relOid;
17691  thisobj.objectSubId = 0;
17692 
17693  /*
17694  * If the object has already been moved, don't move it again. If it's
17695  * already in the right place, don't move it, but still fire the object
17696  * access hook.
17697  */
17698  already_done = object_address_present(&thisobj, objsMoved);
17699  if (!already_done && oldNspOid != newNspOid)
17700  {
17701  /* check for duplicate name (more friendly than unique-index failure) */
17702  if (get_relname_relid(NameStr(classForm->relname),
17703  newNspOid) != InvalidOid)
17704  ereport(ERROR,
17705  (errcode(ERRCODE_DUPLICATE_TABLE),
17706  errmsg("relation \"%s\" already exists in schema \"%s\"",
17707  NameStr(classForm->relname),
17708  get_namespace_name(newNspOid))));
17709 
17710  /* classTup is a copy, so OK to scribble on */
17711  classForm->relnamespace = newNspOid;
17712 
17713  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
17714 
17715  /* Update dependency on schema if caller said so */
17716  if (hasDependEntry &&
17717  changeDependencyFor(RelationRelationId,
17718  relOid,
17719  NamespaceRelationId,
17720  oldNspOid,
17721  newNspOid) != 1)
17722  elog(ERROR, "could not change schema dependency for relation \"%s\"",
17723  NameStr(classForm->relname));
17724  }
17725  if (!already_done)
17726  {
17727  add_exact_object_address(&thisobj, objsMoved);
17728 
17729  InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
17730  }
17731 
17732  heap_freetuple(classTup);
17733 }
#define NameStr(name)
Definition: c.h:735
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1435
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:313
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3321
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1862
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:197
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:456
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
ItemPointerData t_self
Definition: htup.h:65
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:86

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, SearchSysCacheCopy1, and HeapTupleData::t_self.

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

◆ AlterSeqNamespaces()

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

Definition at line 17787 of file tablecmds.c.

17790 {
17791  Relation depRel;
17792  SysScanDesc scan;
17793  ScanKeyData key[2];
17794  HeapTuple tup;
17795 
17796  /*
17797  * SERIAL sequences are those having an auto dependency on one of the
17798  * table's columns (we don't care *which* column, exactly).
17799  */
17800  depRel = table_open(DependRelationId, AccessShareLock);
17801 
17802  ScanKeyInit(&key[0],
17803  Anum_pg_depend_refclassid,
17804  BTEqualStrategyNumber, F_OIDEQ,
17805  ObjectIdGetDatum(RelationRelationId));
17806  ScanKeyInit(&key[1],
17807  Anum_pg_depend_refobjid,
17808  BTEqualStrategyNumber, F_OIDEQ,
17810  /* we leave refobjsubid unspecified */
17811 
17812  scan = systable_beginscan(depRel, DependReferenceIndexId, true,
17813  NULL, 2, key);
17814 
17815  while (HeapTupleIsValid(tup = systable_getnext(scan)))
17816  {
17817  Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
17818  Relation seqRel;
17819 
17820  /* skip dependencies other than auto dependencies on columns */
17821  if (depForm->refobjsubid == 0 ||
17822  depForm->classid != RelationRelationId ||
17823  depForm->objsubid != 0 ||
17824  !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
17825  continue;
17826 
17827  /* Use relation_open just in case it's an index */
17828  seqRel = relation_open(depForm->objid, lockmode);
17829 
17830  /* skip non-sequence relations */
17831  if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
17832  {
17833  /* No need to keep the lock */
17834  relation_close(seqRel, lockmode);
17835  continue;
17836  }
17837 
17838  /* Fix the pg_class and pg_depend entries */
17839  AlterRelationNamespaceInternal(classRel, depForm->objid,
17840  oldNspOid, newNspOid,
17841  true, objsMoved);
17842 
17843  /*
17844  * Sequences used to have entries in pg_type, but no longer do. If we
17845  * ever re-instate that, we'll need to move the pg_type entry to the
17846  * new namespace, too (using AlterTypeNamespaceInternal).
17847  */
17848  Assert(RelationGetForm(seqRel)->reltype == InvalidOid);
17849 
17850  /* Now we can close it. Keep the lock till end of transaction. */
17851  relation_close(seqRel, NoLock);
17852  }
17853 
17854  systable_endscan(scan);
17855 
17857 }
@ DEPENDENCY_AUTO
Definition: dependency.h:34
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:599
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:506
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:387
#define AccessShareLock
Definition: lockdefs.h:36
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:72
#define RelationGetForm(relation)
Definition: rel.h:498
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define BTEqualStrategyNumber
Definition: stratnum.h:31

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

Referenced by AlterTableNamespaceInternal().

◆ AlterTable()

void AlterTable ( AlterTableStmt stmt,
LOCKMODE  lockmode,
AlterTableUtilityContext context 
)

Definition at line 4422 of file tablecmds.c.

4424 {
4425  Relation rel;
4426 
4427  /* Caller is required to provide an adequate lock. */
4428  rel = relation_open(context->relid, NoLock);
4429 
4430  CheckTableNotInUse(rel, "ALTER TABLE");
4431 
4432  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4433 }
#define stmt
Definition: indent_codes.h:59
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:4759

References ATController(), CheckTableNotInUse(), NoLock, relation_open(), AlterTableUtilityContext::relid, and stmt.

Referenced by ProcessUtilitySlow().

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)

Definition at line 4496 of file tablecmds.c.

4497 {
4498  /*
4499  * This only works if we read catalog tables using MVCC snapshots.
4500  */
4501  ListCell *lcmd;
4503 
4504  foreach(lcmd, cmds)
4505  {
4506  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4507  LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
4508 
4509  switch (cmd->subtype)
4510  {
4511  /*
4512  * These subcommands rewrite the heap, so require full locks.
4513  */
4514  case AT_AddColumn: /* may rewrite heap, in some cases and visible
4515  * to SELECT */
4516  case AT_SetAccessMethod: /* must rewrite heap */
4517  case AT_SetTableSpace: /* must rewrite heap */
4518  case AT_AlterColumnType: /* must rewrite heap */
4519  cmd_lockmode = AccessExclusiveLock;
4520  break;
4521 
4522  /*
4523  * These subcommands may require addition of toast tables. If
4524  * we add a toast table to a table currently being scanned, we
4525  * might miss data added to the new toast table by concurrent
4526  * insert transactions.
4527  */
4528  case AT_SetStorage: /* may add toast tables, see
4529  * ATRewriteCatalogs() */
4530  cmd_lockmode = AccessExclusiveLock;
4531  break;
4532 
4533  /*
4534  * Removing constraints can affect SELECTs that have been
4535  * optimized assuming the constraint holds true. See also
4536  * CloneFkReferenced.
4537  */
4538  case AT_DropConstraint: /* as DROP INDEX */
4539  case AT_DropNotNull: /* may change some SQL plans */
4540  cmd_lockmode = AccessExclusiveLock;
4541  break;
4542 
4543  /*
4544  * Subcommands that may be visible to concurrent SELECTs
4545  */
4546  case AT_DropColumn: /* change visible to SELECT */
4547  case AT_AddColumnToView: /* CREATE VIEW */
4548  case AT_DropOids: /* used to equiv to DropColumn */
4549  case AT_EnableAlwaysRule: /* may change SELECT rules */
4550  case AT_EnableReplicaRule: /* may change SELECT rules */
4551  case AT_EnableRule: /* may change SELECT rules */
4552  case AT_DisableRule: /* may change SELECT rules */
4553  cmd_lockmode = AccessExclusiveLock;
4554  break;
4555 
4556  /*
4557  * Changing owner may remove implicit SELECT privileges
4558  */
4559  case AT_ChangeOwner: /* change visible to SELECT */
4560  cmd_lockmode = AccessExclusiveLock;
4561  break;
4562 
4563  /*
4564  * Changing foreign table options may affect optimization.
4565  */
4566  case AT_GenericOptions:
4568  cmd_lockmode = AccessExclusiveLock;
4569  break;
4570 
4571  /*
4572  * These subcommands affect write operations only.
4573  */
4574  case AT_EnableTrig:
4575  case AT_EnableAlwaysTrig:
4576  case AT_EnableReplicaTrig:
4577  case AT_EnableTrigAll:
4578  case AT_EnableTrigUser:
4579  case AT_DisableTrig:
4580  case AT_DisableTrigAll:
4581  case AT_DisableTrigUser:
4582  cmd_lockmode = ShareRowExclusiveLock;
4583  break;
4584 
4585  /*
4586  * These subcommands affect write operations only. XXX
4587  * Theoretically, these could be ShareRowExclusiveLock.
4588  */
4589  case AT_ColumnDefault:
4591  case AT_AlterConstraint:
4592  case AT_AddIndex: /* from ADD CONSTRAINT */
4593  case AT_AddIndexConstraint:
4594  case AT_ReplicaIdentity:
4595  case AT_SetNotNull:
4596  case AT_SetAttNotNull:
4597  case AT_EnableRowSecurity:
4598  case AT_DisableRowSecurity:
4599  case AT_ForceRowSecurity:
4600  case AT_NoForceRowSecurity:
4601  case AT_AddIdentity:
4602  case AT_DropIdentity:
4603  case AT_SetIdentity:
4604  case AT_SetExpression:
4605  case AT_DropExpression:
4606  case AT_SetCompression:
4607  cmd_lockmode = AccessExclusiveLock;
4608  break;
4609 
4610  case AT_AddConstraint:
4611  case AT_ReAddConstraint: /* becomes AT_AddConstraint */
4612  case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
4613  if (IsA(cmd->def, Constraint))
4614  {
4615  Constraint *con = (Constraint *) cmd->def;
4616 
4617  switch (con->contype)
4618  {
4619  case CONSTR_EXCLUSION:
4620  case CONSTR_PRIMARY:
4621  case CONSTR_UNIQUE:
4622 
4623  /*
4624  * Cases essentially the same as CREATE INDEX. We
4625  * could reduce the lock strength to ShareLock if
4626  * we can work out how to allow concurrent catalog
4627  * updates. XXX Might be set down to
4628  * ShareRowExclusiveLock but requires further
4629  * analysis.
4630  */
4631  cmd_lockmode = AccessExclusiveLock;
4632  break;
4633  case CONSTR_FOREIGN:
4634 
4635  /*
4636  * We add triggers to both tables when we add a
4637  * Foreign Key, so the lock level must be at least
4638  * as strong as CREATE TRIGGER.
4639  */
4640  cmd_lockmode = ShareRowExclusiveLock;
4641  break;
4642 
4643  default:
4644  cmd_lockmode = AccessExclusiveLock;
4645  }
4646  }
4647  break;
4648 
4649  /*
4650  * These subcommands affect inheritance behaviour. Queries
4651  * started before us will continue to see the old inheritance
4652  * behaviour, while queries started after we commit will see
4653  * new behaviour. No need to prevent reads or writes to the
4654  * subtable while we hook it up though. Changing the TupDesc
4655  * may be a problem, so keep highest lock.
4656  */
4657  case AT_AddInherit:
4658  case AT_DropInherit:
4659  cmd_lockmode = AccessExclusiveLock;
4660  break;
4661 
4662  /*
4663  * These subcommands affect implicit row type conversion. They
4664  * have affects similar to CREATE/DROP CAST on queries. don't
4665  * provide for invalidating parse trees as a result of such
4666  * changes, so we keep these at AccessExclusiveLock.
4667  */
4668  case AT_AddOf:
4669  case AT_DropOf:
4670  cmd_lockmode = AccessExclusiveLock;
4671  break;
4672 
4673  /*
4674  * Only used by CREATE OR REPLACE VIEW which must conflict
4675  * with an SELECTs currently using the view.
4676  */
4677  case AT_ReplaceRelOptions:
4678  cmd_lockmode = AccessExclusiveLock;
4679  break;
4680 
4681  /*
4682  * These subcommands affect general strategies for performance
4683  * and maintenance, though don't change the semantic results
4684  * from normal data reads and writes. Delaying an ALTER TABLE
4685  * behind currently active writes only delays the point where
4686  * the new strategy begins to take effect, so there is no
4687  * benefit in waiting. In this case the minimum restriction
4688  * applies: we don't currently allow concurrent catalog
4689  * updates.
4690  */
4691  case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
4692  case AT_ClusterOn: /* Uses MVCC in getIndexes() */
4693  case AT_DropCluster: /* Uses MVCC in getIndexes() */
4694  case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
4695  case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
4696  cmd_lockmode = ShareUpdateExclusiveLock;
4697  break;
4698 
4699  case AT_SetLogged:
4700  case AT_SetUnLogged:
4701  cmd_lockmode = AccessExclusiveLock;
4702  break;
4703 
4704  case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
4705  cmd_lockmode = ShareUpdateExclusiveLock;
4706  break;
4707 
4708  /*
4709  * Rel options are more complex than first appears. Options
4710  * are set here for tables, views and indexes; for historical
4711  * reasons these can all be used with ALTER TABLE, so we can't
4712  * decide between them using the basic grammar.
4713  */
4714  case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
4715  * getTables() */
4716  case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
4717  * getTables() */
4718  cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
4719  break;
4720 
4721  case AT_AttachPartition:
4722  cmd_lockmode = ShareUpdateExclusiveLock;
4723  break;
4724 
4725  case AT_DetachPartition:
4726  if (((PartitionCmd *) cmd->def)->concurrent)
4727  cmd_lockmode = ShareUpdateExclusiveLock;
4728  else
4729  cmd_lockmode = AccessExclusiveLock;
4730  break;
4731 
4733  cmd_lockmode = ShareUpdateExclusiveLock;
4734  break;
4735 
4736  default: /* oops */
4737  elog(ERROR, "unrecognized alter table type: %d",
4738  (int) cmd->subtype);
4739  break;
4740  }
4741 
4742  /*
4743  * Take the greatest lockmode from any subcommand
4744  */
4745  if (cmd_lockmode > lockmode)
4746  lockmode = cmd_lockmode;
4747  }
4748 
4749  return lockmode;
4750 }
int LOCKMODE
Definition: lockdefs.h:26
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
@ CONSTR_UNIQUE
Definition: parsenodes.h:2546
@ CONSTR_EXCLUSION
Definition: parsenodes.h:2547
@ CONSTR_PRIMARY
Definition: parsenodes.h:2545
#define lfirst(lc)
Definition: pg_list.h:172
LOCKMODE AlterTableGetRelOptionsLockLevel(List *defList)
Definition: reloptions.c:2110
AlterTableType subtype
Definition: parsenodes.h:2267
ConstrType contype
Definition: parsenodes.h:2570

References AccessExclusiveLock, AlterTableGetRelOptionsLockLevel(), AT_AddColumn, AT_AddColumnToView, AT_AddConstraint, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AddInherit, AT_AddOf, AT_AlterColumnGenericOptions, AT_AlterColumnType, AT_AlterConstraint, AT_AttachPartition, AT_ChangeOwner, AT_ClusterOn, AT_ColumnDefault, AT_CookedColumnDefault, AT_DetachPartition, AT_DetachPartitionFinalize, AT_DisableRowSecurity, AT_DisableRule, AT_DisableTrig, AT_DisableTrigAll, AT_DisableTrigUser, AT_DropCluster, AT_DropColumn, AT_DropConstraint, AT_DropExpression, 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_ReAddConstraint, AT_ReAddDomainConstraint, AT_ReplaceRelOptions, AT_ReplicaIdentity, AT_ResetOptions, AT_ResetRelOptions, AT_SetAccessMethod, AT_SetAttNotNull, AT_SetCompression, AT_SetExpression, 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().

◆ AlterTableInternal()

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

Definition at line 4451 of file tablecmds.c.

4452 {
4453  Relation rel;
4454  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4455 
4456  rel = relation_open(relid, lockmode);
4457 
4459 
4460  ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4461 }
void EventTriggerAlterTableRelid(Oid objectId)
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:4496

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

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 4363 of file tablecmds.c.

4364 {
4365  return RangeVarGetRelidExtended(stmt->relation, lockmode,
4366  stmt->missing_ok ? RVR_MISSING_OK : 0,
4368  (void *) stmt);
4369 }
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:426
@ RVR_MISSING_OK
Definition: namespace.h:71
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:18193

References RangeVarCallbackForAlterRelation(), RangeVarGetRelidExtended(), RVR_MISSING_OK, and stmt.

Referenced by ProcessUtilitySlow().

◆ AlterTableMoveAll()

Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

Definition at line 15594 of file tablecmds.c.

15595 {
15596  List *relations = NIL;
15597  ListCell *l;
15598  ScanKeyData key[1];
15599  Relation rel;
15600  TableScanDesc scan;
15601  HeapTuple tuple;
15602  Oid orig_tablespaceoid;
15603  Oid new_tablespaceoid;
15604  List *role_oids = roleSpecsToIds(stmt->roles);
15605 
15606  /* Ensure we were not asked to move something we can't */
15607  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
15608  stmt->objtype != OBJECT_MATVIEW)
15609  ereport(ERROR,
15610  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
15611  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
15612 
15613  /* Get the orig and new tablespace OIDs */
15614  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
15615  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
15616 
15617  /* Can't move shared relations in to or out of pg_global */
15618  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
15619  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
15620  new_tablespaceoid == GLOBALTABLESPACE_OID)
15621  ereport(ERROR,
15622  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
15623  errmsg("cannot move relations in to or out of pg_global tablespace")));
15624 
15625  /*
15626  * Must have CREATE rights on the new tablespace, unless it is the
15627  * database default tablespace (which all users implicitly have CREATE
15628  * rights on).
15629  */
15630  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
15631  {
15632  AclResult aclresult;
15633 
15634  aclresult = object_aclcheck(TableSpaceRelationId, new_tablespaceoid, GetUserId(),
15635  ACL_CREATE);
15636  if (aclresult != ACLCHECK_OK)
15637  aclcheck_error(aclresult, OBJECT_TABLESPACE,
15638  get_tablespace_name(new_tablespaceoid));
15639  }
15640 
15641  /*
15642  * Now that the checks are done, check if we should set either to
15643  * InvalidOid because it is our database's default tablespace.
15644  */
15645  if (orig_tablespaceoid == MyDatabaseTableSpace)
15646  orig_tablespaceoid = InvalidOid;
15647 
15648  if (new_tablespaceoid == MyDatabaseTableSpace)
15649  new_tablespaceoid = InvalidOid;
15650 
15651  /* no-op */
15652  if (orig_tablespaceoid == new_tablespaceoid)
15653  return new_tablespaceoid;
15654 
15655  /*
15656  * Walk the list of objects in the tablespace and move them. This will
15657  * only find objects in our database, of course.
15658  */
15659  ScanKeyInit(&key[0],
15660  Anum_pg_class_reltablespace,
15661  BTEqualStrategyNumber, F_OIDEQ,
15662  ObjectIdGetDatum(orig_tablespaceoid));
15663 
15664  rel = table_open(RelationRelationId, AccessShareLock);
15665  scan = table_beginscan_catalog(rel, 1, key);
15666  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
15667  {
15668  Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
15669  Oid relOid = relForm->oid;
15670 
15671  /*
15672  * Do not move objects in pg_catalog as part of this, if an admin
15673  * really wishes to do so, they can issue the individual ALTER
15674  * commands directly.
15675  *
15676  * Also, explicitly avoid any shared tables, temp tables, or TOAST
15677  * (TOAST will be moved with the main table).
15678  */
15679  if (IsCatalogNamespace(relForm->relnamespace) ||
15680  relForm->relisshared ||
15681  isAnyTempNamespace(relForm->relnamespace) ||
15682  IsToastNamespace(relForm->relnamespace))
15683  continue;
15684 
15685  /* Only move the object type requested */
15686  if ((stmt->objtype == OBJECT_TABLE &&
15687  relForm->relkind != RELKIND_RELATION &&
15688  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
15689  (stmt->objtype == OBJECT_INDEX &&
15690  relForm->relkind != RELKIND_INDEX &&
15691  relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
15692  (stmt->objtype == OBJECT_MATVIEW &&
15693  relForm->relkind != RELKIND_MATVIEW))
15694  continue;
15695 
15696  /* Check if we are only moving objects owned by certain roles */
15697  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
15698  continue;
15699 
15700  /*
15701  * Handle permissions-checking here since we are locking the tables
15702  * and also to avoid doing a bunch of work only to fail part-way. Note
15703  * that permissions will also be checked by AlterTableInternal().
15704  *
15705  * Caller must be considered an owner on the table to move it.
15706  */
15707  if (!object_ownercheck(RelationRelationId, relOid, GetUserId()))
15709  NameStr(relForm->relname));
15710 
15711  if (stmt->nowait &&
15713  ereport(ERROR,
15714  (errcode(ERRCODE_OBJECT_IN_USE),
15715  errmsg("aborting because lock on relation \"%s.%s\" is not available",
15716  get_namespace_name(relForm->relnamespace),
15717  NameStr(relForm->relname))));
15718  else
15720 
15721  /* Add to our list of objects to move */
15722  relations = lappend_oid(relations, relOid);
15723  }
15724 
15725  table_endscan(scan);
15727 
15728  if (relations == NIL)
15729  ereport(NOTICE,
15730  (errcode(ERRCODE_NO_DATA_FOUND),
15731  errmsg("no matching relations in tablespace \"%s\" found",
15732  orig_tablespaceoid == InvalidOid ? "(database default)" :
15733  get_tablespace_name(orig_tablespaceoid))));
15734 
15735  /* Everything is locked, loop through and move all of the relations. */
15736  foreach(l, relations)
15737  {
15738  List *cmds = NIL;
15740 
15741  cmd->subtype = AT_SetTableSpace;
15742  cmd->name = stmt->new_tablespacename;
15743 
15744  cmds = lappend(cmds, cmd);
15745 
15747  /* OID is set by AlterTableInternal */
15748  AlterTableInternal(lfirst_oid(l), cmds, false);
15750  }
15751 
15752  return new_tablespaceoid;
15753 }
AclResult
Definition: acl.h:181
@ ACLCHECK_OK
Definition: acl.h:182
@ ACLCHECK_NOT_OWNER
Definition: acl.h:184
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2701
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3878
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4132
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1478
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1432
List * roleSpecsToIds(List *memberNames)
Definition: user.c:1653
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:202
bool IsCatalogNamespace(Oid namespaceId)
Definition: catalog.c:184
#define NOTICE
Definition: elog.h:35
void EventTriggerAlterTableStart(Node *parsetree)
void EventTriggerAlterTableEnd(void)
Oid MyDatabaseTableSpace
Definition: globals.c:92
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1086
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:722
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:152
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:109
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1980
Oid GetUserId(void)
Definition: miscinit.c:515
bool isAnyTempNamespace(Oid namespaceId)
Definition: namespace.c:3672
#define makeNode(_type_)
Definition: nodes.h:155
ObjectType get_relkind_objtype(char relkind)
@ OBJECT_MATVIEW
Definition: parsenodes.h:2119
@ OBJECT_TABLESPACE
Definition: parsenodes.h:2138
@ OBJECT_INDEX
Definition: parsenodes.h:2116
@ OBJECT_TABLE
Definition: parsenodes.h:2137
#define ACL_CREATE
Definition: parsenodes.h:85
@ ForwardScanDirection
Definition: sdir.h:28
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:1009
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:4451

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, NIL, NOTICE, object_aclcheck(), OBJECT_INDEX, OBJECT_MATVIEW, object_ownercheck(), OBJECT_TABLE, OBJECT_TABLESPACE, ObjectIdGetDatum(), OidIsValid, roleSpecsToIds(), ScanKeyInit(), stmt, AlterTableCmd::subtype, table_beginscan_catalog(), table_close(), table_endscan(), and table_open().

Referenced by ProcessUtilitySlow().

◆ AlterTableNamespace()

ObjectAddress AlterTableNamespace ( AlterObjectSchemaStmt stmt,
Oid oldschema 
)

Definition at line 17562 of file tablecmds.c.

17563 {
17564  Relation rel;
17565  Oid relid;
17566  Oid oldNspOid;
17567  Oid nspOid;
17568  RangeVar *newrv;
17569  ObjectAddresses *objsMoved;
17570  ObjectAddress myself;
17571 
17573  stmt->missing_ok ? RVR_MISSING_OK : 0,
17575  (void *) stmt);
17576 
17577  if (!OidIsValid(relid))
17578  {
17579  ereport(NOTICE,
17580  (errmsg("relation \"%s\" does not exist, skipping",
17581  stmt->relation->relname)));
17582  return InvalidObjectAddress;
17583  }
17584 
17585  rel = relation_open(relid, NoLock);
17586 
17587  oldNspOid = RelationGetNamespace(rel);
17588 
17589  /* If it's an owned sequence, disallow moving it by itself. */
17590  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
17591  {
17592  Oid tableId;
17593  int32 colId;
17594 
17595  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
17596  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
17597  ereport(ERROR,
17598  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
17599  errmsg("cannot move an owned sequence into another schema"),
17600  errdetail("Sequence \"%s\" is linked to table \"%s\".",
17602  get_rel_name(tableId))));
17603  }
17604 
17605  /* Get and lock schema OID and check its permissions. */
17606  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
17607  nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
17608 
17609  /* common checks on switching namespaces */
17610  CheckSetNamespace(oldNspOid, nspOid);
17611 
17612  objsMoved = new_object_addresses();
17613  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
17614  free_object_addresses(objsMoved);
17615 
17616  ObjectAddressSet(myself, RelationRelationId, relid);
17617 
17618  if (oldschema)
17619  *oldschema = oldNspOid;
17620 
17621  /* close rel, but keep lock until commit */
17622  relation_close(rel, NoLock);
17623 
17624  return myself;
17625 }
signed int int32
Definition: c.h:483
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2539
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2828
int errdetail(const char *fmt,...)
Definition: elog.c:1208
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1905
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:425
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:724
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition: namespace.c:3444
const ObjectAddress InvalidObjectAddress
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition: pg_depend.c:827
void AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:17633

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

Referenced by ExecAlterObjectSchemaStmt().

◆ AlterTableNamespaceInternal()

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

Definition at line 17633 of file tablecmds.c.

17635 {
17636  Relation classRel;
17637 
17638  Assert(objsMoved != NULL);
17639 
17640  /* OK, modify the pg_class row and pg_depend entry */
17641  classRel = table_open(RelationRelationId, RowExclusiveLock);
17642 
17643  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
17644  nspOid, true, objsMoved);
17645 
17646  /* Fix the table's row type too, if it has one */
17647  if (OidIsValid(rel->rd_rel->reltype))
17648  AlterTypeNamespaceInternal(rel->rd_rel->reltype,
17649  nspOid, false, false, objsMoved);
17650 
17651  /* Fix other dependent stuff */
17652  if (rel->rd_rel->relkind == RELKIND_RELATION ||
17653  rel->rd_rel->relkind == RELKIND_MATVIEW ||
17654  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
17655  {
17656  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
17657  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
17658  objsMoved, AccessExclusiveLock);
17659  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
17660  false, objsMoved);
17661  }
17662 
17663  table_close(classRel, RowExclusiveLock);
17664 }
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:17787
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:17742
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:3981

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

Referenced by AlterObjectNamespace_oid(), and AlterTableNamespace().

◆ ATAddCheckNNConstraint()

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

Definition at line 9646 of file tablecmds.c.

9649 {
9650  List *newcons;
9651  ListCell *lcon;
9652  List *children;
9653  ListCell *child;
9655 
9656  /* Guard against stack overflow due to overly deep inheritance tree. */
9658 
9659  /* At top level, permission check was done in ATPrepCmd, else do it */
9660  if (recursing)
9662 
9663  /*
9664  * Call AddRelationNewConstraints to do the work, making sure it works on
9665  * a copy of the Constraint so transformExpr can't modify the original. It
9666  * returns a list of cooked constraints.
9667  *
9668  * If the constraint ends up getting merged with a pre-existing one, it's
9669  * omitted from the returned list, which is what we want: we do not need
9670  * to do any validation work. That can only happen at child tables,
9671  * though, since we disallow merging at the top level.
9672  */
9673  newcons = AddRelationNewConstraints(rel, NIL,
9674  list_make1(copyObject(constr)),
9675  recursing || is_readd, /* allow_merge */
9676  !recursing, /* is_local */
9677  is_readd, /* is_internal */
9678  NULL); /* queryString not available
9679  * here */
9680 
9681  /* we don't expect more than one constraint here */
9682  Assert(list_length(newcons) <= 1);
9683 
9684  /* Add each to-be-validated constraint to Phase 3's queue */
9685  foreach(lcon, newcons)
9686  {
9687  CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
9688 
9689  if (!ccon->skip_validation && ccon->contype != CONSTR_NOTNULL)
9690  {
9691  NewConstraint *newcon;
9692 
9693  newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
9694  newcon->name = ccon->name;
9695  newcon->contype = ccon->contype;
9696  newcon->qual = ccon->expr;
9697 
9698  tab->constraints = lappend(tab->constraints, newcon);
9699  }
9700 
9701  /* Save the actually assigned name if it was defaulted */
9702  if (constr->conname == NULL)
9703  constr->conname = ccon->name;
9704 
9705  /*
9706  * If adding a not-null constraint, set the pg_attribute flag and tell
9707  * phase 3 to verify existing rows, if needed.
9708  */
9709  if (constr->contype == CONSTR_NOTNULL)
9710  set_attnotnull(wqueue, rel, ccon->attnum,
9711  !ccon->is_no_inherit, lockmode);
9712 
9713  ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
9714  }
9715 
9716  /* At this point we must have a locked-down name to use */
9717  Assert(newcons == NIL || constr->conname != NULL);
9718 
9719  /* Advance command counter in case same table is visited multiple times */
9721 
9722  /*
9723  * If the constraint got merged with an existing constraint, we're done.
9724  * We mustn't recurse to child tables in this case, because they've
9725  * already got the constraint, and visiting them again would lead to an
9726  * incorrect value for coninhcount.
9727  */
9728  if (newcons == NIL)
9729  return address;
9730 
9731  /*
9732  * If adding a NO INHERIT constraint, no need to find our children.
9733  */
9734  if (constr->is_no_inherit)
9735  return address;
9736 
9737  /*
9738  * Propagate to children as appropriate. Unlike most other ALTER
9739  * routines, we have to do this one level of recursion at a time; we can't
9740  * use find_all_inheritors to do it in one pass.
9741  */
9742  children =
9744 
9745  /*
9746  * Check if ONLY was specified with ALTER TABLE. If so, allow the
9747  * constraint creation only if there are no children currently. Error out
9748  * otherwise.
9749  */
9750  if (!recurse && children != NIL)
9751  ereport(ERROR,
9752  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9753  errmsg("constraint must be added to child tables too")));
9754 
9755  /*
9756  * The constraint must appear as inherited in children, so create a
9757  * modified constraint object to use.
9758  */
9759  constr = copyObject(constr);
9760  constr->inhcount = 1;
9761  foreach(child, children)
9762  {
9763  Oid childrelid = lfirst_oid(child);
9764  Relation childrel;
9765  AlteredTableInfo *childtab;
9766 
9767  /* find_inheritance_children already got lock */
9768  childrel = table_open(childrelid, NoLock);
9769  CheckTableNotInUse(childrel, "ALTER TABLE");
9770 
9771  /* Find or create work queue entry for this table */
9772  childtab = ATGetQueueEntry(wqueue, childrel);
9773 
9774  /*
9775  * Recurse to child. XXX if we didn't create a constraint on the
9776  * parent because it already existed, and we do create one on a child,
9777  * should we return that child's constraint ObjectAddress here?
9778  */
9779  ATAddCheckNNConstraint(wqueue, childtab, childrel,
9780  constr, recurse, true, is_readd, lockmode);
9781 
9782  table_close(childrel, NoLock);
9783  }
9784 
9785  return address;
9786 }
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal, const char *queryString)
Definition: heap.c:2297
@ CONSTR_NOTNULL
Definition: parsenodes.h:2540
List * find_inheritance_children(Oid parentrelId, LOCKMODE lockmode)
Definition: pg_inherits.c:59
static int list_length(const List *l)
Definition: pg_list.h:152
#define list_make1(x1)
Definition: pg_list.h:212
void check_stack_depth(void)
Definition: postgres.c:3523
bool is_no_inherit
Definition: parsenodes.h:2576
Oid conoid
Definition: heap.h:39
char * name
Definition: heap.h:40
AttrNumber attnum
Definition: heap.h:41
bool skip_validation
Definition: heap.h:43
bool is_no_inherit
Definition: heap.h:46
ConstrType contype
Definition: heap.h:37
Node * expr
Definition: heap.h:42
#define ATT_TABLE
Definition: tablecmds.c:322
static ObjectAddress ATAddCheckNNConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *constr, bool recurse, bool recursing, bool is_readd, LOCKMODE lockmode)
Definition: tablecmds.c:9646
static void ATSimplePermissions(AlterTableType cmdtype, Relation rel, int allowed_targets)
Definition: tablecmds.c:6560
#define ATT_FOREIGN_TABLE
Definition: tablecmds.c:327
static bool set_attnotnull(List **wqueue, Relation rel, AttrNumber attnum, bool recurse, LOCKMODE lockmode)
Definition: tablecmds.c:7663

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

Referenced by ATExecAddConstraint(), and DetachAddConstraintIfNeeded().

◆ ATAddForeignKeyConstraint()

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

Definition at line 9804 of file tablecmds.c.

9807 {
9808  Relation pkrel;
9809  int16 pkattnum[INDEX_MAX_KEYS] = {0};
9810  int16 fkattnum[INDEX_MAX_KEYS] = {0};
9811  Oid pktypoid[INDEX_MAX_KEYS] = {0};
9812  Oid fktypoid[INDEX_MAX_KEYS] = {0};
9813  Oid opclasses[INDEX_MAX_KEYS] = {0};
9814  Oid pfeqoperators[INDEX_MAX_KEYS] = {0};
9815  Oid ppeqoperators[INDEX_MAX_KEYS] = {0};
9816  Oid ffeqoperators[INDEX_MAX_KEYS] = {0};
9817  int16 fkdelsetcols[INDEX_MAX_KEYS] = {0};
9818  int i;
9819  int numfks,
9820  numpks,
9821  numfkdelsetcols;
9822  Oid indexOid;
9823  bool old_check_ok;
9824  ObjectAddress address;
9825  ListCell *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
9826 
9827  /*
9828  * Grab ShareRowExclusiveLock on the pk table, so that someone doesn't
9829  * delete rows out from under us.
9830  */
9831  if (OidIsValid(fkconstraint->old_pktable_oid))
9832  pkrel = table_open(fkconstraint->old_pktable_oid, ShareRowExclusiveLock);
9833  else
9834  pkrel = table_openrv(fkconstraint->pktable, ShareRowExclusiveLock);
9835 
9836  /*
9837  * Validity checks (permission checks wait till we have the column
9838  * numbers)
9839  */
9840  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
9841  {
9842  if (!recurse)
9843  ereport(ERROR,
9844  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9845  errmsg("cannot use ONLY for foreign key on partitioned table \"%s\" referencing relation \"%s\"",
9847  RelationGetRelationName(pkrel))));
9848  if (fkconstraint->skip_validation && !fkconstraint->initially_valid)
9849  ereport(ERROR,
9850  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9851  errmsg("cannot add NOT VALID foreign key on partitioned table \"%s\" referencing relation \"%s\"",
9853  RelationGetRelationName(pkrel)),
9854  errdetail("This feature is not yet supported on partitioned tables.")));
9855  }
9856 
9857  if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
9858  pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
9859  ereport(ERROR,
9860  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
9861  errmsg("referenced relation \"%s\" is not a table",
9862  RelationGetRelationName(pkrel))));
9863 
9864  if (!allowSystemTableMods && IsSystemRelation(pkrel))
9865  ereport(ERROR,
9866  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
9867  errmsg("permission denied: \"%s\" is a system catalog",
9868  RelationGetRelationName(pkrel))));
9869 
9870  /*
9871  * References from permanent or unlogged tables to temp tables, and from
9872  * permanent tables to unlogged tables, are disallowed because the
9873  * referenced data can vanish out from under us. References from temp
9874  * tables to any other table type are also disallowed, because other
9875  * backends might need to run the RI triggers on the perm table, but they
9876  * can't reliably see tuples in the local buffers of other backends.
9877  */
9878  switch (rel->rd_rel->relpersistence)
9879  {
9880  case RELPERSISTENCE_PERMANENT:
9881  if (!RelationIsPermanent(pkrel))
9882  ereport(ERROR,
9883  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9884  errmsg("constraints on permanent tables may reference only permanent tables")));
9885  break;
9886  case RELPERSISTENCE_UNLOGGED:
9887  if (!RelationIsPermanent(pkrel)
9888  && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
9889  ereport(ERROR,
9890  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9891  errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
9892  break;
9893  case RELPERSISTENCE_TEMP:
9894  if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
9895  ereport(ERROR,
9896  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9897  errmsg("constraints on temporary tables may reference only temporary tables")));
9898  if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
9899  ereport(ERROR,
9900  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
9901  errmsg("constraints on temporary tables must involve temporary tables of this session")));
9902  break;
9903  }
9904 
9905  /*
9906  * Look up the referencing attributes to make sure they exist, and record
9907  * their attnums and type OIDs.
9908  */
9910  fkconstraint->fk_attrs,
9911  fkattnum, fktypoid);
9912 
9913  numfkdelsetcols = transformColumnNameList(RelationGetRelid(rel),
9914  fkconstraint->fk_del_set_cols,
9915  fkdelsetcols, NULL);
9916  validateFkOnDeleteSetColumns(numfks, fkattnum,
9917  numfkdelsetcols, fkdelsetcols,
9918  fkconstraint->fk_del_set_cols);
9919 
9920  /*
9921  * If the attribute list for the referenced table was omitted, lookup the
9922  * definition of the primary key and use it. Otherwise, validate the
9923  * supplied attribute list. In either case, discover the index OID and
9924  * index opclasses, and the attnums and type OIDs of the attributes.
9925  */
9926  if (fkconstraint->pk_attrs == NIL)
9927  {
9928  numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
9929  &fkconstraint->pk_attrs,
9930  pkattnum, pktypoid,
9931  opclasses);
9932  }
9933  else
9934  {
9935  numpks = transformColumnNameList(RelationGetRelid(pkrel),
9936  fkconstraint->pk_attrs,
9937  pkattnum, pktypoid);
9938  /* Look for an index matching the column list */
9939  indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
9940  opclasses);
9941  }
9942 
9943  /*
9944  * Now we can check permissions.
9945  */
9946  checkFkeyPermissions(pkrel, pkattnum, numpks);
9947 
9948  /*
9949  * Check some things for generated columns.
9950  */
9951  for (i = 0; i < numfks; i++)
9952  {
9953  char attgenerated = TupleDescAttr(RelationGetDescr(rel), fkattnum[i] - 1)->attgenerated;
9954 
9955  if (attgenerated)
9956  {
9957  /*
9958  * Check restrictions on UPDATE/DELETE actions, per SQL standard
9959  */
9960  if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
9961  fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT ||
9962  fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE)
9963  ereport(ERROR,
9964  (errcode(ERRCODE_SYNTAX_ERROR),
9965  errmsg("invalid %s action for foreign key constraint containing generated column",
9966  "ON UPDATE")));
9967  if (fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
9968  fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
9969  ereport(ERROR,
9970  (errcode(ERRCODE_SYNTAX_ERROR),
9971  errmsg("invalid %s action for foreign key constraint containing generated column",
9972  "ON DELETE")));
9973  }
9974  }
9975 
9976  /*
9977  * Look up the equality operators to use in the constraint.
9978  *
9979  * Note that we have to be careful about the difference between the actual
9980  * PK column type and the opclass' declared input type, which might be
9981  * only binary-compatible with it. The declared opcintype is the right
9982  * thing to probe pg_amop with.
9983  */
9984  if (numfks != numpks)
9985  ereport(ERROR,
9986  (errcode(ERRCODE_INVALID_FOREIGN_KEY),
9987  errmsg("number of referencing and referenced columns for foreign key disagree")));
9988 
9989  /*
9990  * On the strength of a previous constraint, we might avoid scanning
9991  * tables to validate this one. See below.
9992  */
9993  old_check_ok = (fkconstraint->old_conpfeqop != NIL);
9994  Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
9995 
9996  for (i = 0; i < numpks; i++)
9997  {
9998  Oid pktype = pktypoid[i];
9999  Oid fktype = fktypoid[i];
10000  Oid fktyped;
10001  HeapTuple cla_ht;
10002  Form_pg_opclass cla_tup;
10003  Oid amid;
10004  Oid opfamily;
10005  Oid opcintype;
10006  Oid pfeqop;
10007  Oid ppeqop;
10008  Oid ffeqop;
10009  int16 eqstrategy;
10010  Oid pfeqop_right;
10011 
10012  /* We need several fields out of the pg_opclass entry */
10013  cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
10014  if (!HeapTupleIsValid(cla_ht))
10015  elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
10016  cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
10017  amid = cla_tup->opcmethod;
10018  opfamily = cla_tup->opcfamily;
10019  opcintype = cla_tup->opcintype;
10020  ReleaseSysCache(cla_ht);
10021 
10022  /*
10023  * Check it's a btree; currently this can never fail since no other
10024  * index AMs support unique indexes. If we ever did have other types
10025  * of unique indexes, we'd need a way to determine which operator
10026  * strategy number is equality. (Is it reasonable to insist that
10027  * every such index AM use btree's number for equality?)
10028  */
10029  if (amid != BTREE_AM_OID)
10030  elog(ERROR, "only b-tree indexes are supported for foreign keys");
10031  eqstrategy = BTEqualStrategyNumber;
10032 
10033  /*
10034  * There had better be a primary equality operator for the index.
10035  * We'll use it for PK = PK comparisons.
10036  */
10037  ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
10038  eqstrategy);
10039 
10040  if (!OidIsValid(ppeqop))
10041  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
10042  eqstrategy, opcintype, opcintype, opfamily);
10043 
10044  /*
10045  * Are there equality operators that take exactly the FK type? Assume
10046  * we should look through any domain here.
10047  */
10048  fktyped = getBaseType(fktype);
10049 
10050  pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
10051  eqstrategy);
10052  if (OidIsValid(pfeqop))
10053  {
10054  pfeqop_right = fktyped;
10055  ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
10056  eqstrategy);
10057  }
10058  else
10059  {
10060  /* keep compiler quiet */
10061  pfeqop_right = InvalidOid;
10062  ffeqop = InvalidOid;
10063  }
10064 
10065  if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
10066  {
10067  /*
10068  * Otherwise, look for an implicit cast from the FK type to the
10069  * opcintype, and if found, use the primary equality operator.
10070  * This is a bit tricky because opcintype might be a polymorphic
10071  * type such as ANYARRAY or ANYENUM; so what we have to test is
10072  * whether the two actual column types can be concurrently cast to
10073  * that type. (Otherwise, we'd fail to reject combinations such
10074  * as int[] and point[].)
10075  */
10076  Oid input_typeids[2];
10077  Oid target_typeids[2];
10078 
10079  input_typeids[0] = pktype;
10080  input_typeids[1] = fktype;
10081  target_typeids[0] = opcintype;
10082  target_typeids[1] = opcintype;
10083  if (can_coerce_type(2, input_typeids, target_typeids,
10085  {
10086  pfeqop = ffeqop = ppeqop;
10087  pfeqop_right = opcintype;
10088  }
10089  }
10090 
10091  if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
10092  ereport(ERROR,
10093  (errcode(ERRCODE_DATATYPE_MISMATCH),
10094  errmsg("foreign key constraint \"%s\" cannot be implemented",
10095  fkconstraint->conname),
10096  errdetail("Key columns \"%s\" and \"%s\" "
10097  "are of incompatible types: %s and %s.",
10098  strVal(list_nth(fkconstraint->fk_attrs, i)),
10099  strVal(list_nth(fkconstraint->pk_attrs, i)),
10100  format_type_be(fktype),
10101  format_type_be(pktype))));
10102 
10103  if (old_check_ok)
10104  {
10105  /*
10106  * When a pfeqop changes, revalidate the constraint. We could
10107  * permit intra-opfamily changes, but that adds subtle complexity
10108  * without any concrete benefit for core types. We need not
10109  * assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
10110  */
10111  old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
10112  old_pfeqop_item = lnext(fkconstraint->old_conpfeqop,
10113  old_pfeqop_item);
10114  }
10115  if (old_check_ok)
10116  {
10117  Oid old_fktype;
10118  Oid new_fktype;
10119  CoercionPathType old_pathtype;
10120  CoercionPathType new_pathtype;
10121  Oid old_castfunc;
10122  Oid new_castfunc;
10124  fkattnum[i] - 1);
10125 
10126  /*
10127  * Identify coercion pathways from each of the old and new FK-side
10128  * column types to the right (foreign) operand type of the pfeqop.
10129  * We may assume that pg_constraint.conkey is not changing.
10130  */
10131  old_fktype = attr->atttypid;
10132  new_fktype = fktype;
10133  old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
10134  &old_castfunc);
10135  new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
10136  &new_castfunc);
10137 
10138  /*
10139  * Upon a change to the cast from the FK column to its pfeqop
10140  * operand, revalidate the constraint. For this evaluation, a
10141  * binary coercion cast is equivalent to no cast at all. While
10142  * type implementors should design implicit casts with an eye
10143  * toward consistency of operations like equality, we cannot
10144  * assume here that they have done so.
10145  *
10146  * A function with a polymorphic argument could change behavior
10147  * arbitrarily in response to get_fn_expr_argtype(). Therefore,
10148  * when the cast destination is polymorphic, we only avoid
10149  * revalidation if the input type has not changed at all. Given
10150  * just the core data types and operator classes, this requirement
10151  * prevents no would-be optimizations.
10152  *
10153  * If the cast converts from a base type to a domain thereon, then
10154  * that domain type must be the opcintype of the unique index.
10155  * Necessarily, the primary key column must then be of the domain
10156  * type. Since the constraint was previously valid, all values on
10157  * the foreign side necessarily exist on the primary side and in
10158  * turn conform to the domain. Consequently, we need not treat
10159  * domains specially here.
10160  *
10161  * Since we require that all collations share the same notion of
10162  * equality (which they do, because texteq reduces to bitwise
10163  * equality), we don't compare collation here.
10164  *
10165  * We need not directly consider the PK type. It's necessarily
10166  * binary coercible to the opcintype of the unique index column,
10167  * and ri_triggers.c will only deal with PK datums in terms of
10168  * that opcintype. Changing the opcintype also changes pfeqop.
10169  */
10170  old_check_ok = (new_pathtype == old_pathtype &&
10171  new_castfunc == old_castfunc &&
10172  (!IsPolymorphicType(pfeqop_right) ||
10173  new_fktype == old_fktype));
10174  }
10175 
10176  pfeqoperators[i] = pfeqop;
10177  ppeqoperators[i] = ppeqop;
10178  ffeqoperators[i] = ffeqop;
10179  }
10180 
10181  /*
10182  * Create all the constraint and trigger objects, recursing to partitions
10183  * as necessary. First handle the referenced side.
10184  */
10185  address = addFkRecurseReferenced(wqueue, fkconstraint, rel, pkrel,
10186  indexOid,
10187  InvalidOid, /* no parent constraint */
10188  numfks,
10189  pkattnum,
10190  fkattnum,
10191  pfeqoperators,
10192  ppeqoperators,
10193  ffeqoperators,
10194  numfkdelsetcols,
10195  fkdelsetcols,
10196  old_check_ok,
10198 
10199  /* Now handle the referencing side. */
10200  addFkRecurseReferencing(wqueue, fkconstraint, rel, pkrel,
10201  indexOid,
10202  address.objectId,
10203  numfks,
10204  pkattnum,
10205  fkattnum,
10206  pfeqoperators,
10207  ppeqoperators,
10208  ffeqoperators,
10209  numfkdelsetcols,
10210  fkdelsetcols,
10211  old_check_ok,
10212  lockmode,
10214 
10215  /*
10216  * Done. Close pk table, but keep lock until we've committed.
10217  */
10218  table_close(pkrel, NoLock);
10219 
10220  return address;
10221 }
signed short int16
Definition: c.h:482
bool IsSystemRelation(Relation relation)
Definition: catalog.c:75
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
bool allowSystemTableMods
Definition: globals.c:127
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:165
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2476
bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:556
CoercionPathType
Definition: parse_coerce.h:25
#define FKCONSTR_ACTION_SETDEFAULT
Definition: parsenodes.h:2560
#define FKCONSTR_ACTION_CASCADE
Definition: parsenodes.h:2558
#define FKCONSTR_ACTION_SETNULL
Definition: parsenodes.h:2559
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
@ COERCION_IMPLICIT
Definition: primnodes.h:649
#define RelationIsPermanent(relation)
Definition: rel.h:616
TupleDesc oldDesc
Definition: tablecmds.c:170
List * pk_attrs
Definition: parsenodes.h:2603
List * fk_del_set_cols
Definition: parsenodes.h:2607
Oid old_pktable_oid
Definition: parsenodes.h:2609
List * old_conpfeqop
Definition: parsenodes.h:2608
RangeVar * pktable
Definition: parsenodes.h:2601
bool rd_islocaltemp
Definition: rel.h:61
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:267
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:219
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:83
static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid, List **attnamelist, int16 *attnums, Oid *atttypids, Oid *opclasses)
Definition: tablecmds.c:12041
static CoercionPathType findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
Definition: tablecmds.c:12279
static int transformColumnNameList(Oid relId, List *colList, int16 *attnums, Oid *atttypids)
Definition: tablecmds.c:11989
static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
Definition: tablecmds.c:12308
static Oid transformFkeyCheckAttrs(Relation pkrel, int numattrs, int16 *attnums, Oid *opclasses)
Definition: tablecmds.c:12140
static void validateFkOnDeleteSetColumns(int numfks, const int16 *fkattnums, int numfksetcols, const int16 *fksetcolsattnums, List *fksetcols)
Definition: tablecmds.c:10229
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define strVal(v)
Definition: value.h:82

References addFkRecurseReferenced(), addFkRecurseReferencing(), allowSystemTableMods, Assert(), BTEqualStrategyNumber, can_coerce_type(), checkFkeyPermissions(), COERCION_IMPLICIT, Constraint::conname, elog(), ereport, errcode(), errdetail(), errmsg(), ERROR, findFkeyCast(), Constraint::fk_attrs, Constraint::fk_del_action, Constraint::fk_del_set_cols, 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(), 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, RelationIsPermanent, ReleaseSysCache(), SearchSysCache1(), ShareRowExclusiveLock, Constraint::skip_validation, strVal, table_close(), table_open(), table_openrv(), transformColumnNameList(), transformFkeyCheckAttrs(), transformFkeyGetPrimaryKey(), TupleDescAttr, and validateFkOnDeleteSetColumns().

Referenced by ATExecAddConstraint().

◆ ATCheckPartitionsNotInUse()

static void ATCheckPartitionsNotInUse ( Relation  rel,
LOCKMODE  lockmode 
)
static

Definition at line 6680 of file tablecmds.c.

6681 {
6682  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
6683  {
6684  List *inh;
6685  ListCell *cell;
6686 
6687  inh = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
6688  /* first element is the parent rel; must ignore it */
6689  for_each_from(cell, inh, 1)
6690  {
6691  Relation childrel;
6692 
6693  /* find_all_inheritors already got lock */
6694  childrel = table_open(lfirst_oid(cell), NoLock);
6695  CheckTableNotInUse(childrel, "ALTER TABLE");
6696  table_close(childrel, NoLock);
6697  }
6698  list_free(inh);
6699  }
6700 }
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:256
#define for_each_from(cell, lst, N)
Definition: pg_list.h:414

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

Referenced by ATPrepCmd().

◆ ATColumnChangeRequiresRewrite()

static bool ATColumnChangeRequiresRewrite ( Node expr,
AttrNumber  varattno 
)
static

Definition at line 13437 of file tablecmds.c.

13438 {
13439  Assert(expr != NULL);
13440 
13441  for (;;)
13442  {
13443  /* only one varno, so no need to check that */
13444  if (IsA(expr, Var) && ((Var *) expr)->varattno == varattno)
13445  return false;
13446  else if (IsA(expr, RelabelType))
13447  expr = (Node *) ((RelabelType *) expr)->arg;
13448  else if (IsA(expr, CoerceToDomain))
13449  {
13450  CoerceToDomain *d = (CoerceToDomain *) expr;
13451 
13453  return true;
13454  expr = (Node *) d->arg;
13455  }
13456  else if (IsA(expr, FuncExpr))
13457  {
13458  FuncExpr *f = (FuncExpr *) expr;
13459 
13460  switch (f->funcid)
13461  {
13462  case F_TIMESTAMPTZ_TIMESTAMP:
13463  case F_TIMESTAMP_TIMESTAMPTZ:
13465  return true;
13466  else
13467  expr = linitial(f->args);
13468  break;
13469  default:
13470  return true;
13471  }
13472  }
13473  else
13474  return true;
13475  }
13476 }
bool TimestampTimestampTzRequiresRewrite(void)
Definition: timestamp.c:6228
void * arg
#define linitial(l)
Definition: pg_list.h:178
Oid funcid
Definition: primnodes.h:685
List * args
Definition: primnodes.h:703
Definition: primnodes.h:234
bool DomainHasConstraints(Oid type_id)
Definition: typcache.c:1401

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

Referenced by ATPrepAlterColumnType().

◆ ATController()

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

Definition at line 4759 of file tablecmds.c.

4762 {
4763  List *wqueue = NIL;
4764  ListCell *lcmd;
4765 
4766  /* Phase 1: preliminary examination of commands, create work queue */
4767  foreach(lcmd, cmds)
4768  {
4769  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
4770 
4771  ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode, context);
4772  }
4773 
4774  /* Close the relation, but keep lock until commit */
4775  relation_close(rel, NoLock);
4776 
4777  /* Phase 2: update system catalogs */
4778  ATRewriteCatalogs(&wqueue, lockmode, context);
4779 
4780  /* Phase 3: scan/rewrite tables as needed, and run afterStmts */
4781  ATRewriteTables(parsetree, &wqueue, lockmode, context);
4782 }
static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:5181
static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:4794
static void ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:5721

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

Referenced by AlterTable(), and AlterTableInternal().

◆ ATDetachCheckNoForeignKeyRefs()

static void ATDetachCheckNoForeignKeyRefs ( Relation  partition)
static

Definition at line 20480 of file tablecmds.c.

20481 {
20482  List *constraints;
20483  ListCell *cell;
20484 
20485  constraints = GetParentedForeignKeyRefs(partition);
20486 
20487  foreach(cell, constraints)
20488  {
20489  Oid constrOid = lfirst_oid(cell);
20490  HeapTuple tuple;
20491  Form_pg_constraint constrForm;
20492  Relation rel;
20493  Trigger trig = {0};
20494 
20495  tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
20496  if (!HeapTupleIsValid(tuple))
20497  elog(ERROR, "cache lookup failed for constraint %u", constrOid);
20498  constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
20499 
20500  Assert(OidIsValid(constrForm->conparentid));
20501  Assert(constrForm->confrelid == RelationGetRelid(partition));
20502 
20503  /* prevent data changes into the referencing table until commit */
20504  rel = table_open(constrForm->conrelid, ShareLock);
20505 
20506  trig.tgoid = InvalidOid;
20507  trig.tgname = NameStr(constrForm->conname);
20509  trig.tgisinternal = true;
20510  trig.tgconstrrelid = RelationGetRelid(partition);
20511  trig.tgconstrindid = constrForm->conindid;
20512  trig.tgconstraint = constrForm->oid;
20513  trig.tgdeferrable = false;
20514  trig.tginitdeferred = false;
20515  /* we needn't fill in remaining fields */
20516 
20517  RI_PartitionRemove_Check(&trig, rel, partition);
20518 
20519  ReleaseSysCache(tuple);
20520 
20521  table_close(rel, NoLock);
20522  }
20523 }
#define ShareLock
Definition: lockdefs.h:40
FormData_pg_constraint * Form_pg_constraint
void RI_PartitionRemove_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
Definition: ri_triggers.c:1663
char tgenabled
Definition: reltrigger.h:30
Oid tgoid
Definition: reltrigger.h:25
Oid tgconstrindid
Definition: reltrigger.h:34
Oid tgconstraint
Definition: reltrigger.h:35
Oid tgconstrrelid
Definition: reltrigger.h:33
char * tgname
Definition: reltrigger.h:27
bool tgdeferrable
Definition: reltrigger.h:36
bool tginitdeferred
Definition: reltrigger.h:37
bool tgisinternal
Definition: reltrigger.h:31
static List * GetParentedForeignKeyRefs(Relation partition)
Definition: tablecmds.c:20427
#define TRIGGER_FIRES_ON_ORIGIN
Definition: trigger.h:149

References Assert(), elog(), ERROR, GetParentedForeignKeyRefs(), GETSTRUCT, HeapTupleIsValid, InvalidOid, lfirst_oid, 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().

◆ AtEOSubXact_on_commit_actions()

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

Definition at line 18070 of file tablecmds.c.

18072 {
18073  ListCell *cur_item;
18074 
18075  foreach(cur_item, on_commits)
18076  {
18077  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
18078 
18079  if (!isCommit && oc->creating_subid == mySubid)
18080  {
18081  /* cur_item must be removed */
18083  pfree(oc);
18084  }
18085  else
18086  {
18087  /* cur_item must be preserved */
18088  if (oc->creating_subid == mySubid)
18089  oc->creating_subid = parentSubid;
18090  if (oc->deleting_subid == mySubid)
18091  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
18092  }
18093  }
18094 }
#define InvalidSubTransactionId
Definition: c.h:647
#define foreach_delete_current(lst, var_or_cell)
Definition: pg_list.h:391
SubTransactionId creating_subid
Definition: tablecmds.c:124
SubTransactionId deleting_subid
Definition: tablecmds.c:125
static List * on_commits
Definition: tablecmds.c:128

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

◆ AtEOXact_on_commit_actions()

void AtEOXact_on_commit_actions ( bool  isCommit)

Definition at line 18038 of file tablecmds.c.

18039 {
18040  ListCell *cur_item;
18041 
18042  foreach(cur_item, on_commits)
18043  {
18044  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
18045 
18046  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
18048  {
18049  /* cur_item must be removed */
18051  pfree(oc);
18052  }
18053  else
18054  {
18055  /* cur_item must be preserved */
18058  }
18059  }
18060 }

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

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

◆ ATExecAddColumn()

static ObjectAddress ATExecAddColumn ( List **  wqueue,
AlteredTableInfo tab,
Relation  rel,
AlterTableCmd **  cmd,
bool  recurse,
bool  recursing,
LOCKMODE  lockmode,
AlterTablePass  cur_pass,
AlterTableUtilityContext context 
)
static

Definition at line 7029 of file tablecmds.c.

7033 {
7034  Oid myrelid = RelationGetRelid(rel);
7035  ColumnDef *colDef = castNode(ColumnDef, (*cmd)->def);
7036  bool if_not_exists = (*cmd)->missing_ok;
7037  Relation pgclass,
7038  attrdesc;
7039  HeapTuple reltup;
7040  Form_pg_attribute attribute;
7041  int newattnum;
7042  char relkind;
7043  Expr *defval;
7044  List *children;
7045  ListCell *child;
7046  AlterTableCmd *childcmd;
7047  ObjectAddress address;
7048  TupleDesc tupdesc;
7049 
7050  /* since this function recurses, it could be driven to stack overflow */
7052 
7053  /* At top level, permission check was done in ATPrepCmd, else do it */
7054  if (recursing)
7055  ATSimplePermissions((*cmd)->subtype, rel, ATT_TABLE | ATT_FOREIGN_TABLE);
7056 
7057  if (rel->rd_rel->relispartition && !recursing)
7058  ereport(ERROR,
7059  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7060  errmsg("cannot add column to a partition")));
7061 
7062  attrdesc = table_open(AttributeRelationId, RowExclusiveLock);
7063 
7064  /*
7065  * Are we adding the column to a recursion child? If so, check whether to
7066  * merge with an existing definition for the column. If we do merge, we
7067  * must not recurse. Children will already have the column, and recursing
7068  * into them would mess up attinhcount.
7069  */
7070  if (colDef->inhcount > 0)
7071  {
7072  HeapTuple tuple;
7073 
7074  /* Does child already have a column by this name? */
7075  tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
7076  if (HeapTupleIsValid(tuple))
7077  {
7078  Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
7079  Oid ctypeId;
7080  int32 ctypmod;
7081  Oid ccollid;
7082 
7083  /* Child column must match on type, typmod, and collation */
7084  typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
7085  if (ctypeId != childatt->atttypid ||
7086  ctypmod != childatt->atttypmod)
7087  ereport(ERROR,
7088  (errcode(ERRCODE_DATATYPE_MISMATCH),
7089  errmsg("child table \"%s\" has different type for column \"%s\"",
7090  RelationGetRelationName(rel), colDef->colname)));
7091  ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
7092  if (ccollid != childatt->attcollation)
7093  ereport(ERROR,
7094  (errcode(ERRCODE_COLLATION_MISMATCH),
7095  errmsg("child table \"%s\" has different collation for column \"%s\"",
7096  RelationGetRelationName(rel), colDef->colname),
7097  errdetail("\"%s\" versus \"%s\"",
7098  get_collation_name(ccollid),
7099  get_collation_name(childatt->attcollation))));
7100 
7101  /* Bump the existing child att's inhcount */
7102  childatt->attinhcount++;
7103  if (childatt->attinhcount < 0)
7104  ereport(ERROR,
7105  errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
7106  errmsg("too many inheritance parents"));
7107  CatalogTupleUpdate(attrdesc, &tuple->t_self, tuple);
7108 
7109  heap_freetuple(tuple);
7110 
7111  /* Inform the user about the merge */
7112  ereport(NOTICE,
7113  (errmsg("merging definition of column \"%s\" for child \"%s\"",
7114  colDef->colname, RelationGetRelationName(rel))));
7115 
7116  table_close(attrdesc, RowExclusiveLock);
7117 
7118  /* Make the child column change visible */
7120 
7121  return InvalidObjectAddress;
7122  }
7123  }
7124 
7125  /* skip if the name already exists and if_not_exists is true */
7126  if (!check_for_column_name_collision(rel, colDef->colname, if_not_exists))
7127  {
7128  table_close(attrdesc, RowExclusiveLock);
7129  return InvalidObjectAddress;
7130  }
7131 
7132  /*
7133  * Okay, we need to add the column, so go ahead and do parse
7134  * transformation. This can result in queueing up, or even immediately
7135  * executing, subsidiary operations (such as creation of unique indexes);
7136  * so we mustn't do it until we have made the if_not_exists check.
7137  *
7138  * When recursing, the command was already transformed and we needn't do
7139  * so again. Also, if context isn't given we can't transform. (That
7140  * currently happens only for AT_AddColumnToView; we expect that view.c
7141  * passed us a ColumnDef that doesn't need work.)
7142  */
7143  if (context != NULL && !recursing)
7144  {
7145  *cmd = ATParseTransformCmd(wqueue, tab, rel, *cmd, recurse, lockmode,
7146  cur_pass, context);
7147  Assert(*cmd != NULL);
7148  colDef = castNode(ColumnDef, (*cmd)->def);
7149  }
7150 
7151  /*
7152  * Regular inheritance children are independent enough not to inherit the
7153  * identity column from parent hence cannot recursively add identity
7154  * column if the table has inheritance children.
7155  *
7156  * Partitions, on the other hand, are integral part of a partitioned table
7157  * and inherit identity column. Hence propagate identity column down the
7158  * partition hierarchy.
7159  */
7160  if (colDef->identity &&
7161  recurse &&
7162  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE &&
7163  find_inheritance_children(myrelid, NoLock) != NIL)
7164  ereport(ERROR,
7165  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7166  errmsg("cannot recursively add identity column to table that has child tables")));
7167 
7168  pgclass = table_open(RelationRelationId, RowExclusiveLock);
7169 
7170  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
7171  if (!HeapTupleIsValid(reltup))
7172  elog(ERROR, "cache lookup failed for relation %u", myrelid);
7173  relkind = ((Form_pg_class) GETSTRUCT(reltup))->relkind;
7174 
7175  /* Determine the new attribute's number */
7176  newattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts + 1;
7177  if (newattnum > MaxHeapAttributeNumber)
7178  ereport(ERROR,
7179  (errcode(ERRCODE_TOO_MANY_COLUMNS),
7180  errmsg("tables can have at most %d columns",
7182 
7183  /*
7184  * Construct new attribute's pg_attribute entry.
7185  */
7186  tupdesc = BuildDescForRelation(list_make1(colDef));
7187 
7188  attribute = TupleDescAttr(tupdesc, 0);
7189 
7190  /* Fix up attribute number */
7191  attribute->attnum = newattnum;
7192 
7193  /* make sure datatype is legal for a column */
7194  CheckAttributeType(NameStr(attribute->attname), attribute->atttypid, attribute->attcollation,
7195  list_make1_oid(rel->rd_rel->reltype),
7196  0);
7197 
7198  InsertPgAttributeTuples(attrdesc, tupdesc, myrelid, NULL, NULL);
7199 
7200  table_close(attrdesc, RowExclusiveLock);
7201 
7202  /*
7203  * Update pg_class tuple as appropriate
7204  */
7205  ((Form_pg_class) GETSTRUCT(reltup))->relnatts = newattnum;
7206 
7207  CatalogTupleUpdate(pgclass, &reltup->t_self, reltup);
7208 
7209  heap_freetuple(reltup);
7210 
7211  /* Post creation hook for new attribute */
7212  InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
7213 
7214  table_close(pgclass, RowExclusiveLock);
7215 
7216  /* Make the attribute's catalog entry visible */
7218 
7219  /*
7220  * Store the DEFAULT, if any, in the catalogs
7221  */
7222  if (colDef->raw_default)
7223  {
7224  RawColumnDefault *rawEnt;
7225 
7226  rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
7227  rawEnt->attnum = attribute->attnum;
7228  rawEnt->raw_default = copyObject(colDef->raw_default);
7229 
7230  /*
7231  * Attempt to skip a complete table rewrite by storing the specified
7232  * DEFAULT value outside of the heap. This may be disabled inside
7233  * AddRelationNewConstraints if the optimization cannot be applied.
7234  */
7235  rawEnt->missingMode = (!colDef->generated);
7236 
7237  rawEnt->generated = colDef->generated;
7238 
7239  /*
7240  * This function is intended for CREATE TABLE, so it processes a
7241  * _list_ of defaults, but we just do one.
7242  */
7244  false, true, false, NULL);
7245 
7246  /* Make the additional catalog changes visible */
7248 
7249  /*
7250  * Did the request for a missing value work? If not we'll have to do a
7251  * rewrite
7252  */
7253  if (!rawEnt->missingMode)
7255  }
7256 
7257  /*
7258  * Tell Phase 3 to fill in the default expression, if there is one.
7259  *
7260  * If there is no default, Phase 3 doesn't have to do anything, because
7261  * that effectively means that the default is NULL. The heap tuple access
7262  * routines always check for attnum > # of attributes in tuple, and return
7263  * NULL if so, so without any modification of the tuple data we will get
7264  * the effect of NULL values in the new column.
7265  *
7266  * An exception occurs when the new column is of a domain type: the domain
7267  * might have a not-null constraint, or a check constraint that indirectly
7268  * rejects nulls. If there are any domain constraints then we construct
7269  * an explicit NULL default value that will be passed through
7270  * CoerceToDomain processing. (This is a tad inefficient, since it causes
7271  * rewriting the table which we really don't have to do, but the present
7272  * design of domain processing doesn't offer any simple way of checking
7273  * the constraints more directly.)
7274  *
7275  * Note: we use build_column_default, and not just the cooked default
7276  * returned by AddRelationNewConstraints, so that the right thing happens
7277  * when a datatype's default applies.
7278  *
7279  * Note: it might seem that this should happen at the end of Phase 2, so
7280  * that the effects of subsequent subcommands can be taken into account.
7281  * It's intentional that we do it now, though. The new column should be
7282  * filled according to what is said in the ADD COLUMN subcommand, so that
7283  * the effects are the same as if this subcommand had been run by itself
7284  * and the later subcommands had been issued in new ALTER TABLE commands.
7285  *
7286  * We can skip this entirely for relations without storage, since Phase 3
7287  * is certainly not going to touch them. System attributes don't have
7288  * interesting defaults, either.
7289  */
7290  if (RELKIND_HAS_STORAGE(relkind))
7291  {
7292  /*
7293  * For an identity column, we can't use build_column_default(),
7294  * because the sequence ownership isn't set yet. So do it manually.
7295  */
7296  if (colDef->identity)
7297  {
7299 
7300  nve->seqid = RangeVarGetRelid(colDef->identitySequence, NoLock, false);
7301  nve->typeId = attribute->atttypid;
7302 
7303  defval = (Expr *) nve;
7304 
7305  /* must do a rewrite for identity columns */
7307  }
7308  else
7309  defval = (Expr *) build_column_default(rel, attribute->attnum);
7310 
7311  if (!defval && DomainHasConstraints(attribute->atttypid))
7312  {
7313  Oid baseTypeId;
7314  int32 baseTypeMod;
7315  Oid baseTypeColl;
7316 
7317  baseTypeMod = attribute->atttypmod;
7318  baseTypeId = getBaseTypeAndTypmod(attribute->atttypid, &baseTypeMod);
7319  baseTypeColl = get_typcollation(baseTypeId);
7320  defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
7321  defval = (Expr *) coerce_to_target_type(NULL,
7322  (Node *) defval,
7323  baseTypeId,
7324  attribute->atttypid,
7325  attribute->atttypmod,
7328  -1);
7329  if (defval == NULL) /* should not happen */
7330  elog(ERROR, "failed to coerce base type to domain");
7331  }
7332 
7333  if (defval)
7334  {
7336 
7338  newval->attnum = attribute->attnum;
7339  newval->expr = expression_planner(defval);
7340  newval->is_generated = (colDef->generated != '\0');
7341 
7342  tab->newvals = lappend(tab->newvals, newval);
7343  }
7344 
7345  if (DomainHasConstraints(attribute->atttypid))
7347 
7348  if (!TupleDescAttr(rel->rd_att, attribute->attnum - 1)->atthasmissing)
7349  {
7350  /*
7351  * If the new column is NOT NULL, and there is no missing value,
7352  * tell Phase 3 it needs to check for NULLs.
7353  */
7354  tab->verify_new_notnull |= colDef->is_not_null;
7355  }
7356  }
7357 
7358  /*
7359  * Add needed dependency entries for the new column.
7360  */
7361  add_column_datatype_dependency(myrelid, newattnum, attribute->atttypid);
7362  add_column_collation_dependency(myrelid, newattnum, attribute->attcollation);
7363 
7364  /*
7365  * Propagate to children as appropriate. Unlike most other ALTER
7366  * routines, we have to do this one level of recursion at a time; we can't
7367  * use find_all_inheritors to do it in one pass.
7368  */
7369  children =
7371 
7372  /*
7373  * If we are told not to recurse, there had better not be any child
7374  * tables; else the addition would put them out of step.
7375  */
7376  if (children && !recurse)
7377  ereport(ERROR,
7378  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7379  errmsg("column must be added to child tables too")));
7380 
7381  /* Children should see column as singly inherited */
7382  if (!recursing)
7383  {
7384  childcmd = copyObject(*cmd);
7385  colDef = castNode(ColumnDef, childcmd->def);
7386  colDef->inhcount = 1;
7387  colDef->is_local = false;
7388  }
7389  else
7390  childcmd = *cmd; /* no need to copy again */
7391 
7392  foreach(child, children)
7393  {
7394  Oid childrelid = lfirst_oid(child);
7395  Relation childrel;
7396  AlteredTableInfo *childtab;
7397 
7398  /* find_inheritance_children already got lock */
7399  childrel = table_open(childrelid, NoLock);
7400  CheckTableNotInUse(childrel, "ALTER TABLE");
7401 
7402  /* Find or create work queue entry for this table */
7403  childtab = ATGetQueueEntry(wqueue, childrel);
7404 
7405  /* Recurse to child; return value is ignored */
7406  ATExecAddColumn(wqueue, childtab, childrel,
7407  &childcmd, recurse, true,
7408  lockmode, cur_pass, context);
7409 
7410  table_close(childrel, NoLock);
7411  }
7412 
7413  ObjectAddressSubSet(address, RelationRelationId, myrelid, newattnum);
7414  return address;
7415 }
#define AT_REWRITE_DEFAULT_VAL
Definition: event_trigger.h:35
#define newval
void InsertPgAttributeTuples(Relation pg_attribute_rel, TupleDesc tupdesc, Oid new_rel_oid, const Datum *attoptions, CatalogIndexState indstate)
Definition: heap.c:701
void CheckAttributeType(const char *attname, Oid atttypid, Oid attcollation, List *containing_rowtypes, int flags)
Definition: heap.c:548
#define MaxHeapAttributeNumber
Definition: htup_details.h:48
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:3011
char * get_collation_name(Oid colloid)
Definition: lsyscache.c:1034
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2493
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:340
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:79
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:173
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
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
void typenameTypeIdAndMod(ParseState *pstate, const TypeName *typeName, Oid *typeid_p, int32 *typmod_p)
Definition: parse_type.c:310
Oid GetColumnDefCollation(ParseState *pstate, const ColumnDef *coldef, Oid typeOid)
Definition: parse_type.c:540
#define list_make1_oid(x1)
Definition: pg_list.h:242
Expr * expression_planner(Expr *expr)
Definition: planner.c:6407
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:671
@ COERCION_ASSIGNMENT
Definition: primnodes.h:650
Node * build_column_default(Relation rel, int attrno)
bool verify_new_notnull
Definition: tablecmds.c:187
bool is_not_null
Definition: parsenodes.h:718
char identity
Definition: parsenodes.h:724
RangeVar * identitySequence
Definition: parsenodes.h:725
int inhcount
Definition: parsenodes.h:716
char * colname
Definition: parsenodes.h:713
TypeName * typeName
Definition: parsenodes.h:714
char generated
Definition: parsenodes.h:727
Node * raw_default
Definition: parsenodes.h:722
bool is_local
Definition: parsenodes.h:717
Node * raw_default
Definition: heap.h:30
AttrNumber attnum
Definition: heap.h:29
char generated
Definition: heap.h:32
bool missingMode
Definition: heap.h:31
TupleDesc rd_att
Definition: rel.h:112
HeapTuple SearchSysCacheCopyAttName(Oid relid, const char *attname)
Definition: syscache.c:383
static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
Definition: tablecmds.c:7475
static void add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
Definition: tablecmds.c:7493
TupleDesc BuildDescForRelation(const List *columns)
Definition: tablecmds.c:1296
static AlterTableCmd * ATParseTransformCmd(List **wqueue, AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode, AlterTablePass cur_pass, AlterTableUtilityContext *context)
Definition: tablecmds.c:5584
static bool check_for_column_name_collision(Relation rel, const char *colname, bool if_not_exists)
Definition: tablecmds.c:7422
static ObjectAddress ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel, AlterTableCmd **cmd, bool recurse, bool recursing, LOCKMODE lockmode, AlterTablePass cur_pass, AlterTableUtilityContext *context)
Definition: tablecmds.c:7029

References add_column_collation_dependency(), add_column_datatype_dependency(), AddRelationNewConstraints(), Assert(), AT_REWRITE_DEFAULT_VAL, ATGetQueueEntry(), ATParseTransformCmd(), ATSimplePermissions(), ATT_FOREIGN_TABLE, ATT_TABLE, RawColumnDefault::attnum, build_column_default(), BuildDescForRelation(), castNode, CatalogTupleUpdate(), check_for_column_name_collision(), check_stack_depth(), CheckAttributeType(), CheckTableNotInUse(), COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, ColumnDef::colname, CommandCounterIncrement(), copyObject, AlterTableCmd::def, DomainHasConstraints(), elog(), ereport, errcode(), errdetail(), errmsg(), ERROR, expression_planner(), find_inheritance_children(), RawColumnDefault::generated, ColumnDef::generated, get_collation_name(), get_typcollation(), getBaseTypeAndTypmod(), GetColumnDefCollation(), GETSTRUCT, heap_freetuple(), HeapTupleIsValid, ColumnDef::identity, ColumnDef::identitySequence, ColumnDef::inhcount, InsertPgAttributeTuples(), InvalidObjectAddress, InvokeObjectPostCreateHook, ColumnDef::is_local, ColumnDef::is_not_null, lappend(), lfirst_oid, list_make1, list_make1_oid, makeNode, makeNullConst(), MaxHeapAttributeNumber, RawColumnDefault::missingMode, NameStr, newval, AlteredTableInfo::newvals, NIL, NoLock, NOTICE, ObjectAddressSubSet, ObjectIdGetDatum(), palloc(), palloc0(), RangeVarGetRelid, RawColumnDefault::raw_default, ColumnDef::raw_default, RelationData::rd_att, RelationData::rd_rel, RelationGetRelationName, RelationGetRelid, AlteredTableInfo::rewrite, RowExclusiveLock, SearchSysCacheCopy1, SearchSysCacheCopyAttName(), NextValueExpr::seqid, HeapTupleData::t_self, table_close(), table_open(), TupleDescAttr, NextValueExpr::typeId, ColumnDef::typeName, typenameTypeIdAndMod(), and AlteredTableInfo::verify_new_notnull.

Referenced by ATExecCmd().

◆ ATExecAddConstraint()

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

Definition at line 9530 of file tablecmds.c.

9533 {
9535 
9536  Assert(IsA(newConstraint, Constraint));
9537 
9538  /*
9539  * Currently, we only expect to see CONSTR_CHECK, CONSTR_NOTNULL and
9540  * CONSTR_FOREIGN nodes arriving here (see the preprocessing done in
9541  * parse_utilcmd.c).
9542  */
9543  switch (newConstraint->contype)
9544  {
9545  case CONSTR_CHECK:
9546  case CONSTR_NOTNULL:
9547  address =
9548  ATAddCheckNNConstraint(wqueue, tab, rel,
9549  newConstraint, recurse, false, is_readd,
9550  lockmode);
9551  break;
9552 
9553  case CONSTR_FOREIGN:
9554 
9555  /*
9556  * Assign or validate constraint name
9557  */
9558  if (newConstraint->conname)
9559  {
9561  RelationGetRelid(rel),
9562  newConstraint->conname))
9563  ereport(ERROR,
9565  errmsg("constraint \"%s\" for relation \"%s\" already exists",
9566  newConstraint->conname,
9567  RelationGetRelationName(rel))));
9568  }
9569  else
9570  newConstraint->conname =
9573  "fkey",
9574  RelationGetNamespace(rel),
9575  NIL);
9576 
9577  address = ATAddForeignKeyConstraint(wqueue, tab, rel,
9578  newConstraint,
9579  recurse, false,
9580  lockmode);
9581  break;
9582 
9583  default:
9584  elog(ERROR, "unrecognized constraint type: %d",
9585  (int) newConstraint->contype);
9586  }
9587 
9588  return address;
9589 }
@ CONSTR_CHECK
Definition: parsenodes.h:2544
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
static ObjectAddress ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *fkconstraint, bool recurse, bool recursing, LOCKMODE lockmode)
Definition: tablecmds.c:9804

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

Referenced by ATExecCmd().

◆ ATExecAddIdentity()

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

Definition at line 8128 of file tablecmds.c.

8130 {
8131  Relation attrelation;
8132  HeapTuple tuple;
8133  Form_pg_attribute attTup;
8135  ObjectAddress address;
8136  ColumnDef *cdef = castNode(ColumnDef, def);
8137  bool ispartitioned;
8138 
8139  ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
8140  if (ispartitioned && !recurse)
8141  ereport(ERROR,
8142  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8143  errmsg("cannot add identity to a column of only the partitioned table"),
8144  errhint("Do not specify the ONLY keyword.")));
8145 
8146  if (rel->rd_rel->relispartition && !recursing)
8147  ereport(ERROR,
8148  errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8149  errmsg("cannot add identity to a column of a partition"));
8150 
8151  attrelation = table_open(AttributeRelationId, RowExclusiveLock);
8152 
8153  tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8154  if (!HeapTupleIsValid(tuple))
8155  ereport(ERROR,
8156  (errcode(ERRCODE_UNDEFINED_COLUMN),
8157  errmsg("column \"%s\" of relation \"%s\" does not exist",
8158  colName, RelationGetRelationName(rel))));
8159  attTup = (Form_pg_attribute) GETSTRUCT(tuple);
8160  attnum = attTup->attnum;
8161 
8162  /* Can't alter a system attribute */
8163  if (attnum <= 0)
8164  ereport(ERROR,
8165  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8166  errmsg("cannot alter system column \"%s\"",
8167  colName)));
8168 
8169  /*
8170  * Creating a column as identity implies NOT NULL, so adding the identity
8171  * to an existing column that is not NOT NULL would create a state that
8172  * cannot be reproduced without contortions.
8173  */
8174  if (!attTup->attnotnull)
8175  ereport(ERROR,
8176  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8177  errmsg("column \"%s\" of relation \"%s\" must be declared NOT NULL before identity can be added",
8178  colName, RelationGetRelationName(rel))));
8179 
8180  if (attTup->attidentity)
8181  ereport(ERROR,
8182  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8183  errmsg("column \"%s\" of relation \"%s\" is already an identity column",
8184  colName, RelationGetRelationName(rel))));
8185 
8186  if (attTup->atthasdef)
8187  ereport(ERROR,
8188  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8189  errmsg("column \"%s\" of relation \"%s\" already has a default value",
8190  colName, RelationGetRelationName(rel))));
8191 
8192  attTup->attidentity = cdef->identity;
8193  CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
8194 
8195  InvokeObjectPostAlterHook(RelationRelationId,
8196  RelationGetRelid(rel),
8197  attTup->attnum);
8198  ObjectAddressSubSet(address, RelationRelationId,
8199  RelationGetRelid(rel), attnum);
8200  heap_freetuple(tuple);
8201 
8202  table_close(attrelation, RowExclusiveLock);
8203 
8204  /*
8205  * Recurse to propagate the identity column to partitions. Identity is
8206  * not inherited in regular inheritance children.
8207  */
8208  if (recurse && ispartitioned)
8209  {
8210  List *children;
8211  ListCell *lc;
8212 
8213  children = find_inheritance_children(RelationGetRelid(rel), lockmode);
8214 
8215  foreach(lc, children)
8216  {
8217  Relation childrel;
8218 
8219  childrel = table_open(lfirst_oid(lc), NoLock);
8220  ATExecAddIdentity(childrel, colName, def, lockmode, recurse, true);
8221  table_close(childrel, NoLock);
8222  }
8223  }
8224 
8225  return address;
8226 }
int errhint(const char *fmt,...)
Definition: elog.c:1322
static ObjectAddress ATExecAddIdentity(Relation rel, const char *colName, Node *def, LOCKMODE lockmode, bool recurse, bool recursing)
Definition: tablecmds.c:8128

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

Referenced by ATExecCmd().

◆ ATExecAddIndex()

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

Definition at line 9354 of file tablecmds.c.

9356 {
9357  bool check_rights;
9358  bool skip_build;
9359  bool quiet;
9360  ObjectAddress address;
9361 
9362  Assert(IsA(stmt, IndexStmt));
9363  Assert(!stmt->concurrent);
9364 
9365  /* The IndexStmt has already been through transformIndexStmt */
9366  Assert(stmt->transformed);
9367 
9368  /* suppress schema rights check when rebuilding existing index */
9369  check_rights = !is_rebuild;
9370  /* skip index build if phase 3 will do it or we're reusing an old one */
9371  skip_build = tab->rewrite > 0 || RelFileNumberIsValid(stmt->oldNumber);
9372  /* suppress notices when rebuilding existing index */
9373  quiet = is_rebuild;
9374 
9375  address = DefineIndex(RelationGetRelid(rel),
9376  stmt,
9377  InvalidOid, /* no predefined OID */
9378  InvalidOid, /* no parent index */
9379  InvalidOid, /* no parent constraint */
9380  -1, /* total_parts unknown */
9381  true, /* is_alter_table */
9382  check_rights,
9383  false, /* check_not_in_use - we did it already */
9384  skip_build,
9385  quiet);
9386 
9387  /*
9388  * If TryReuseIndex() stashed a relfilenumber for us, we used it for the
9389  * new index instead of building from scratch. Restore associated fields.
9390  * This may store InvalidSubTransactionId in both fields, in which case
9391  * relcache.c will assume it can rebuild the relcache entry. Hence, do
9392  * this after the CCI that made catalog rows visible to any rebuild. The
9393  * DROP of the old edition of this index will have scheduled the storage
9394  * for deletion at commit, so cancel that pending deletion.
9395  */
9396  if (RelFileNumberIsValid(stmt->oldNumber))
9397  {
9398  Relation irel = index_open(address.objectId, NoLock);
9399 
9400  irel->rd_createSubid = stmt->oldCreateSubid;
9401  irel->rd_firstRelfilelocatorSubid = stmt->oldFirstRelfilelocatorSubid;
9402  RelationPreserveStorage(irel->rd_locator, true);
9403  index_close(irel, NoLock);
9404  }
9405 
9406  return address;
9407 }
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:182
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:138
ObjectAddress DefineIndex(Oid tableId, IndexStmt *stmt, Oid indexRelationId, Oid parentIndexId, Oid parentConstraintId, int total_parts, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
Definition: indexcmds.c:534
#define RelFileNumberIsValid(relnumber)
Definition: relpath.h:27
void RelationPreserveStorage(RelFileLocator rlocator, bool atCommit)
Definition: storage.c:251
SubTransactionId rd_firstRelfilelocatorSubid
Definition: rel.h:106
SubTransactionId rd_createSubid
Definition: rel.h:103
RelFileLocator rd_locator
Definition: rel.h:57

References Assert(), DefineIndex(), index_close(), index_open(), InvalidOid, IsA, NoLock, ObjectAddress::objectId, RelationData::rd_createSubid, RelationData::rd_firstRelfilelocatorSubid, RelationData::rd_locator, RelationGetRelid, RelationPreserveStorage(), RelFileNumberIsValid, AlteredTableInfo::rewrite, and stmt.

Referenced by ATExecCmd().

◆ ATExecAddIndexConstraint()

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

Definition at line 9438 of file tablecmds.c.

9440 {
9441  Oid index_oid = stmt->indexOid;
9442  Relation indexRel;
9443  char *indexName;
9444  IndexInfo *indexInfo;
9445  char *constraintName;
9446  char constraintType;
9447  ObjectAddress address;
9448  bits16 flags;
9449 
9450  Assert(IsA(stmt, IndexStmt));
9451  Assert(OidIsValid(index_oid));
9452  Assert(stmt->isconstraint);
9453 
9454  /*
9455  * Doing this on partitioned tables is not a simple feature to implement,
9456  * so let's punt for now.
9457  */
9458  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
9459  ereport(ERROR,
9460  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9461  errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX is not supported on partitioned tables")));
9462 
9463  indexRel = index_open(index_oid, AccessShareLock);
9464 
9465  indexName = pstrdup(RelationGetRelationName(indexRel));
9466 
9467  indexInfo = BuildIndexInfo(indexRel);
9468 
9469  /* this should have been checked at parse time */
9470  if (!indexInfo->ii_Unique)
9471  elog(ERROR, "index \"%s\" is not unique", indexName);
9472 
9473  /*
9474  * Determine name to assign to constraint. We require a constraint to
9475  * have the same name as the underlying index; therefore, use the index's
9476  * existing name as the default constraint name, and if the user
9477  * explicitly gives some other name for the constraint, rename the index
9478  * to match.
9479  */
9480  constraintName = stmt->idxname;
9481  if (constraintName == NULL)
9482  constraintName = indexName;
9483  else if (strcmp(constraintName, indexName) != 0)
9484  {
9485  ereport(NOTICE,
9486  (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
9487  indexName, constraintName)));
9488  RenameRelationInternal(index_oid, constraintName, false, true);
9489  }
9490 
9491  /* Extra checks needed if making primary key */
9492  if (stmt->primary)
9493  index_check_primary_key(rel, indexInfo, true, stmt);
9494 
9495  /* Note we currently don't support EXCLUSION constraints here */
9496  if (stmt->primary)
9497  constraintType = CONSTRAINT_PRIMARY;
9498  else
9499  constraintType = CONSTRAINT_UNIQUE;
9500 
9501  /* Create the catalog entries for the constraint */
9504  (stmt->initdeferred ? INDEX_CONSTR_CREATE_INIT_DEFERRED : 0) |
9505  (stmt->deferrable ? INDEX_CONSTR_CREATE_DEFERRABLE : 0) |
9506  (stmt->primary ? INDEX_CONSTR_CREATE_MARK_AS_PRIMARY : 0);
9507 
9508  address = index_constraint_create(rel,
9509  index_oid,
9510  InvalidOid,
9511  indexInfo,
9512  constraintName,
9513  constraintType,
9514  flags,
9516  false); /* is_internal */
9517 
9518  index_close(indexRel, NoLock);
9519 
9520  return address;
9521 }
uint16 bits16
Definition: c.h:503
void index_check_primary_key(Relation heapRel, const IndexInfo *indexInfo, bool is_alter_table, const IndexStmt *stmt)
Definition: index.c:206
ObjectAddress index_constraint_create(Relation heapRelation, Oid indexRelationId, Oid parentConstraintId, const IndexInfo *indexInfo, const char *constraintName, char constraintType, bits16 constr_flags, bool allow_system_table_mods, bool is_internal)
Definition: index.c:1912
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2438
#define INDEX_CONSTR_CREATE_UPDATE_INDEX
Definition: index.h:93
#define INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS
Definition: index.h:94
#define INDEX_CONSTR_CREATE_DEFERRABLE
Definition: index.h:91
#define INDEX_CONSTR_CREATE_MARK_AS_PRIMARY
Definition: index.h:90
#define INDEX_CONSTR_CREATE_INIT_DEFERRED
Definition: index.h:92
char * pstrdup(const char *in)
Definition: mcxt.c:1619
bool ii_Unique
Definition: execnodes.h:197
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
Definition: tablecmds.c:4192

References AccessShareLock, allowSystemTableMods, Assert(), BuildIndexInfo(), elog(), ereport, errcode(), errmsg(), ERROR, 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(), InvalidOid, IsA, NoLock, NOTICE, OidIsValid, pstrdup(), RelationData::rd_rel, RelationGetRelationName, RenameRelationInternal(), and stmt.

Referenced by ATExecCmd().

◆ ATExecAddInherit()

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

Definition at line 15870 of file tablecmds.c.

15871 {
15872  Relation parent_rel;
15873  List *children;
15874  ObjectAddress address;
15875  const char *trigger_name;
15876 
15877  /*
15878  * A self-exclusive lock is needed here. See the similar case in
15879  * MergeAttributes() for a full explanation.
15880  */
15881  parent_rel = table_openrv(parent, ShareUpdateExclusiveLock);
15882 
15883  /*
15884  * Must be owner of both parent and child -- child was checked by
15885  * ATSimplePermissions call in ATPrepCmd
15886  */
15888 
15889  /* Permanent rels cannot inherit from temporary ones */
15890  if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
15891  child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
15892  ereport(ERROR,
15893  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
15894  errmsg("cannot inherit from temporary relation \"%s\"",
15895  RelationGetRelationName(parent_rel))));
15896 
15897  /* If parent rel is temp, it must belong to this session */
15898  if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
15899  !parent_rel->rd_islocaltemp)
15900  ereport(ERROR,
15901  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
15902  errmsg("cannot inherit from temporary relation of another session")));
15903 
15904  /* Ditto for the child */
15905  if (child_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
15906  !child_rel->rd_islocaltemp)
15907  ereport(ERROR,
15908  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
15909  errmsg("cannot inherit to temporary relation of another session")));
15910 
15911  /* Prevent partitioned tables from becoming inheritance parents */
15912  if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
15913  ereport(ERROR,
15914  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
15915  errmsg("cannot inherit from partitioned table \"%s\"",
15916  parent->relname)));
15917 
15918  /* Likewise for partitions */
15919  if (parent_rel->rd_rel->relispartition)
15920  ereport(ERROR,
15921  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
15922  errmsg("cannot inherit from a partition")));
15923 
15924  /*
15925  * Prevent circularity by seeing if proposed parent inherits from child.
15926  * (In particular, this disallows making a rel inherit from itself.)
15927  *
15928  * This is not completely bulletproof because of race conditions: in
15929  * multi-level inheritance trees, someone else could concurrently be
15930  * making another inheritance link that closes the loop but does not join
15931  * either of the rels we have locked. Preventing that seems to require
15932  * exclusive locks on the entire inheritance tree, which is a cure worse
15933  * than the disease. find_all_inheritors() will cope with circularity
15934  * anyway, so don't sweat it too much.
15935  *
15936  * We use weakest lock we can on child's children, namely AccessShareLock.
15937  */
15938  children = find_all_inheritors(RelationGetRelid(child_rel),
15939  AccessShareLock, NULL);
15940 
15941  if (list_member_oid(children, RelationGetRelid(parent_rel)))
15942  ereport(ERROR,
15943  (errcode(ERRCODE_DUPLICATE_TABLE),
15944  errmsg("circular inheritance not allowed"),
15945  errdetail("\"%s\" is already a child of \"%s\".",
15946  parent->relname,
15947  RelationGetRelationName(child_rel))));
15948 
15949  /*
15950  * If child_rel has row-level triggers with transition tables, we
15951  * currently don't allow it to become an inheritance child. See also
15952  * prohibitions in ATExecAttachPartition() and CreateTrigger().
15953  */
15954  trigger_name = FindTriggerIncompatibleWithInheritance(child_rel->trigdesc);
15955  if (trigger_name != NULL)
15956  ereport(ERROR,
15957  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
15958  errmsg("trigger \"%s\" prevents table \"%s\" from becoming an inheritance child",
15959  trigger_name, RelationGetRelationName(child_rel)),
15960  errdetail("ROW triggers with transition tables are not supported in inheritance hierarchies.")));
15961 
15962  /* OK to create inheritance */
15963  CreateInheritance(child_rel, parent_rel, false);
15964 
15965  /*
15966  * If parent_rel has a primary key, then child_rel has not-null
15967  * constraints that make these columns as non nullable. Make those
15968  * constraints as inherited.
15969  */
15970  ATInheritAdjustNotNulls(parent_rel, child_rel, 1);
15971 
15972  ObjectAddressSet(address, RelationRelationId,
15973  RelationGetRelid(parent_rel));
15974 
15975  /* keep our lock on the parent relation until commit */
15976  table_close(parent_rel, NoLock);
15977 
15978  return address;
15979 }
char * relname
Definition: primnodes.h:82
TriggerDesc * trigdesc
Definition: rel.h:117
static void ATInheritAdjustNotNulls(Relation parent_rel, Relation child_rel, int inhcount)
Definition: tablecmds.c:16744
static void CreateInheritance(Relation child_rel, Relation parent_rel, bool ispartition)
Definition: tablecmds.c:15989
const char * FindTriggerIncompatibleWithInheritance(TriggerDesc *trigdesc)
Definition: trigger.c:2279

References AccessShareLock, AT_AddInherit, ATInheritAdjustNotNulls(), 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().

◆ ATExecAddOf()

static ObjectAddress ATExecAddOf ( Relation  rel,
const TypeName ofTypename,
LOCKMODE  lockmode 
)
static

Definition at line 16841 of file tablecmds.c.

16842 {
16843  Oid relid = RelationGetRelid(rel);
16844  Type typetuple;
16845  Form_pg_type typeform;
16846  Oid typeid;
16847  Relation inheritsRelation,
16848  relationRelation;
16849  SysScanDesc scan;
16850  ScanKeyData key;
16851  AttrNumber table_attno,
16852  type_attno;
16853  TupleDesc typeTupleDesc,
16854  tableTupleDesc;
16855  ObjectAddress tableobj,
16856  typeobj;
16857  HeapTuple classtuple;
16858 
16859  /* Validate the type. */
16860  typetuple = typenameType(NULL, ofTypename, NULL);
16861  check_of_type(typetuple);
16862  typeform = (Form_pg_type) GETSTRUCT(typetuple);
16863  typeid = typeform->oid;
16864 
16865  /* Fail if the table has any inheritance parents. */
16866  inheritsRelation = table_open(InheritsRelationId, AccessShareLock);
16867  ScanKeyInit(&key,
16868  Anum_pg_inherits_inhrelid,
16869  BTEqualStrategyNumber, F_OIDEQ,
16870  ObjectIdGetDatum(relid));
16871  scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
16872  true, NULL, 1, &key);
16874  ereport(ERROR,
16875  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
16876  errmsg("typed tables cannot inherit")));
16877  systable_endscan(scan);
16878  table_close(inheritsRelation, AccessShareLock);
16879 
16880  /*
16881  * Check the tuple descriptors for compatibility. Unlike inheritance, we
16882  * require that the order also match. However, attnotnull need not match.
16883  */
16884  typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
16885  tableTupleDesc = RelationGetDescr(rel);
16886  table_attno = 1;
16887  for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
16888  {
16889  Form_pg_attribute type_attr,
16890  table_attr;
16891  const char *type_attname,
16892  *table_attname;
16893 
16894  /* Get the next non-dropped type attribute. */
16895  type_attr = TupleDescAttr(typeTupleDesc, type_attno - 1);
16896  if (type_attr->attisdropped)
16897  continue;
16898  type_attname = NameStr(type_attr->attname);
16899 
16900  /* Get the next non-dropped table attribute. */
16901  do
16902  {
16903  if (table_attno > tableTupleDesc->natts)
16904  ereport(ERROR,
16905  (errcode(ERRCODE_DATATYPE_MISMATCH),
16906  errmsg("table is missing column \"%s\"",
16907  type_attname)));
16908  table_attr = TupleDescAttr(tableTupleDesc, table_attno - 1);
16909  table_attno++;
16910  } while (table_attr->attisdropped);
16911  table_attname = NameStr(table_attr->attname);
16912 
16913  /* Compare name. */
16914  if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
16915  ereport(ERROR,
16916  (errcode(ERRCODE_DATATYPE_MISMATCH),
16917  errmsg("table has column \"%s\" where type requires \"%s\"",
16918  table_attname, type_attname)));
16919 
16920  /* Compare type. */
16921  if (table_attr->atttypid != type_attr->atttypid ||
16922  table_attr->atttypmod != type_attr->atttypmod ||
16923  table_attr->attcollation != type_attr->attcollation)
16924  ereport(ERROR,
16925  (errcode(ERRCODE_DATATYPE_MISMATCH),
16926  errmsg("table \"%s\" has different type for column \"%s\"",
16927  RelationGetRelationName(rel), type_attname)));
16928  }
16929  ReleaseTupleDesc(typeTupleDesc);
16930 
16931  /* Any remaining columns at the end of the table had better be dropped. */
16932  for (; table_attno <= tableTupleDesc->natts; table_attno++)
16933  {
16934  Form_pg_attribute table_attr = TupleDescAttr(tableTupleDesc,
16935  table_attno - 1);
16936 
16937  if (!table_attr->attisdropped)
16938  ereport(ERROR,
16939  (errcode(ERRCODE_DATATYPE_MISMATCH),
16940  errmsg("table has extra column \"%s\"",
16941  NameStr(table_attr->attname))));
16942  }
16943 
16944  /* If the table was already typed, drop the existing dependency. */
16945  if (rel->rd_rel->reloftype)
16946  drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
16948 
16949  /* Record a dependency on the new type. */
16950  tableobj.classId = RelationRelationId;
16951  tableobj.objectId = relid;
16952  tableobj.objectSubId = 0;
16953  typeobj.classId = TypeRelationId;
16954  typeobj.objectId = typeid;
16955  typeobj.objectSubId = 0;
16956  recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
16957 
16958  /* Update pg_class.reloftype */
16959  relationRelation = table_open(RelationRelationId, RowExclusiveLock);
16960  classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
16961  if (!HeapTupleIsValid(classtuple))
16962  elog(ERROR, "cache lookup failed for relation %u", relid);
16963  ((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
16964  CatalogTupleUpdate(relationRelation, &classtuple->t_self, classtuple);
16965 
16966  InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
16967 
16968  heap_freetuple(classtuple);
16969  table_close(relationRelation, RowExclusiveLock);
16970 
16971  ReleaseSysCache(typetuple);
16972 
16973  return typeobj;
16974 }
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:264
#define NAMEDATALEN
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
static void drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid, DependencyType deptype)
Definition: tablecmds.c:16789
void check_of_type(HeapTuple typetuple)
Definition: tablecmds.c:6962
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:122
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1834

References AccessShareLock, BTEqualStrategyNumber, CatalogTupleUpdate(), check_of_type(), ObjectAddress::classId, DEPENDENCY_NORMAL, drop_parent_dependency(), elog(), ereport, errcode(), errmsg(), ERROR, GETSTRUCT, heap_freetuple(), HeapTupleIsValid, InvokeObjectPostAlterHook, sort-test::key, lookup_rowtype_tupdesc(), NAMEDATALEN, NameStr, TupleDescData::natts, ObjectAddress::objectId, ObjectIdGetDatum(), ObjectAddress::objectSubId, RelationData::rd_rel, recordDependencyOn(), RelationGetDescr, RelationGetRelationName, RelationGetRelid, ReleaseSysCache(), ReleaseTupleDesc, RowExclusiveLock, ScanKeyInit(), SearchSysCacheCopy1, systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), table_open(), TupleDescAttr, and typenameType().

Referenced by ATExecCmd().

◆ ATExecAddStatistics()

static ObjectAddress ATExecAddStatistics ( AlteredTableInfo tab,
Relation  rel,
CreateStatsStmt stmt,
bool  is_rebuild,
LOCKMODE  lockmode 
)
static

Definition at line 9417 of file tablecmds.c.

9419 {