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/xact.h"
#include "access/xlog.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/objectaccess.h"
#include "catalog/partition.h"
#include "catalog/pg_am.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_depend.h"
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_tablespace.h"
#include "catalog/pg_trigger.h"
#include "catalog/pg_type.h"
#include "catalog/storage.h"
#include "catalog/storage_xlog.h"
#include "catalog/toasting.h"
#include "commands/cluster.h"
#include "commands/comment.h"
#include "commands/defrem.h"
#include "commands/event_trigger.h"
#include "commands/policy.h"
#include "commands/sequence.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "commands/trigger.h"
#include "commands/typecmds.h"
#include "commands/user.h"
#include "executor/executor.h"
#include "foreign/foreign.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/parsenodes.h"
#include "optimizer/optimizer.h"
#include "parser/parse_clause.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_expr.h"
#include "parser/parse_oper.h"
#include "parser/parse_relation.h"
#include "parser/parse_type.h"
#include "parser/parse_utilcmd.h"
#include "parser/parser.h"
#include "partitioning/partbounds.h"
#include "partitioning/partdesc.h"
#include "pgstat.h"
#include "rewrite/rewriteDefine.h"
#include "rewrite/rewriteHandler.h"
#include "rewrite/rewriteManip.h"
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "storage/lock.h"
#include "storage/predicate.h"
#include "storage/smgr.h"
#include "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 dependency graph for tablecmds.c:

Go to the source code of this file.

Data Structures

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

Macros

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

Typedefs

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

Functions

static void truncate_check_rel (Oid relid, Form_pg_class reltuple)
 
static void truncate_check_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 *schema, List *supers, char relpersistence, bool is_partition, List **supconstr)
 
static bool MergeCheckConstraint (List *constraints, char *name, Node *expr)
 
static void MergeAttributesIntoExisting (Relation child_rel, Relation parent_rel)
 
static void MergeConstraintsIntoExisting (Relation child_rel, Relation parent_rel)
 
static void StoreCatalogInheritance (Oid relationId, List *supers, bool child_is_partition)
 
static void StoreCatalogInheritance1 (Oid relationId, Oid parentOid, int32 seqNumber, Relation inhRelation, bool child_is_partition)
 
static int findAttrByName (const char *attributeName, List *schema)
 
static void AlterIndexNamespaces (Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
 
static void AlterSeqNamespaces (Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved, LOCKMODE lockmode)
 
static ObjectAddress ATExecAlterConstraint (Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
 
static ObjectAddress ATExecValidateConstraint (Relation rel, char *constrName, bool recurse, bool recursing, LOCKMODE lockmode)
 
static int transformColumnNameList (Oid relId, List *colList, int16 *attnums, Oid *atttypids)
 
static int transformFkeyGetPrimaryKey (Relation pkrel, Oid *indexOid, List **attnamelist, int16 *attnums, Oid *atttypids, Oid *opclasses)
 
static Oid transformFkeyCheckAttrs (Relation pkrel, int numattrs, int16 *attnums, Oid *opclasses)
 
static void checkFkeyPermissions (Relation rel, int16 *attnums, int natts)
 
static CoercionPathType findFkeyCast (Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
 
static void validateCheckConstraint (Relation rel, HeapTuple constrtup)
 
static void validateForeignKeyConstraint (char *conname, Relation rel, Relation pkrel, Oid pkindOid, Oid constraintOid)
 
static void ATController (AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, 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, Relation rel, AlterTableCmd *cmd, LOCKMODE lockmode, int cur_pass, AlterTableUtilityContext *context)
 
static AlterTableCmdATParseTransformCmd (List **wqueue, AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode, int 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 (Relation rel, int allowed_targets)
 
static void ATWrongRelkindError (Relation rel, int allowed_targets)
 
static void ATSimpleRecursion (List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode, 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, int 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 void ATPrepDropNotNull (Relation rel, bool recurse, bool recursing)
 
static ObjectAddress ATExecDropNotNull (Relation rel, const char *colName, LOCKMODE lockmode)
 
static void ATPrepSetNotNull (List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
static ObjectAddress ATExecSetNotNull (AlteredTableInfo *tab, Relation rel, const char *colName, LOCKMODE lockmode)
 
static void ATExecCheckNotNull (AlteredTableInfo *tab, Relation rel, const char *colName, LOCKMODE lockmode)
 
static bool NotNullImpliedByRelConstraints (Relation rel, Form_pg_attribute attr)
 
static bool ConstraintImpliedByRelConstraint (Relation scanrel, List *testConstraint, List *provenConstraint)
 
static ObjectAddress ATExecColumnDefault (Relation rel, const char *colName, Node *newDefault, LOCKMODE lockmode)
 
static ObjectAddress ATExecAddIdentity (Relation rel, const char *colName, Node *def, LOCKMODE lockmode)
 
static ObjectAddress ATExecSetIdentity (Relation rel, const char *colName, Node *def, LOCKMODE lockmode)
 
static ObjectAddress ATExecDropIdentity (Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode)
 
static void ATPrepDropExpression (Relation rel, AlterTableCmd *cmd, bool recursing)
 
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 ObjectAddress ATExecAddIndex (AlteredTableInfo *tab, Relation rel, IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
 
static ObjectAddress ATExecAddConstraint (List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *newConstraint, bool recurse, bool is_readd, LOCKMODE lockmode)
 
static char * ChooseForeignKeyConstraintNameAddition (List *colnames)
 
static ObjectAddress ATExecAddIndexConstraint (AlteredTableInfo *tab, Relation rel, IndexStmt *stmt, LOCKMODE lockmode)
 
static ObjectAddress ATAddCheckConstraint (List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *constr, bool recurse, bool recursing, bool is_readd, LOCKMODE lockmode)
 
static ObjectAddress ATAddForeignKeyConstraint (List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *fkconstraint, Oid parentConstr, bool recurse, bool recursing, LOCKMODE lockmode)
 
static ObjectAddress addFkRecurseReferenced (List **wqueue, Constraint *fkconstraint, Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr, int numfks, int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators, bool old_check_ok)
 
static void addFkRecurseReferencing (List **wqueue, Constraint *fkconstraint, Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr, int numfks, int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators, bool old_check_ok, LOCKMODE lockmode)
 
static void CloneForeignKeyConstraints (List **wqueue, Relation parentRel, Relation partitionRel)
 
static void CloneFkReferenced (Relation parentRel, Relation partitionRel)
 
static void CloneFkReferencing (List **wqueue, Relation parentRel, Relation partRel)
 
static void createForeignKeyCheckTriggers (Oid myRelOid, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid)
 
static void createForeignKeyActionTriggers (Relation rel, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid)
 
static bool tryAttachPartitionForeignKey (ForeignKeyCacheInfo *fk, Oid partRelid, Oid parentConstrOid, int numfks, AttrNumber *mapped_conkey, AttrNumber *confkey, Oid *conpfeqop)
 
static void ATExecDropConstraint (Relation rel, const char *constrName, DropBehavior behavior, bool recurse, bool recursing, bool missing_ok, LOCKMODE lockmode)
 
static void ATPrepAlterColumnType (List **wqueue, AlteredTableInfo *tab, Relation rel, bool recurse, bool recursing, AlterTableCmd *cmd, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
static bool ATColumnChangeRequiresRewrite (Node *expr, AttrNumber varattno)
 
static ObjectAddress ATExecAlterColumnType (AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static void RememberConstraintForRebuilding (Oid conoid, AlteredTableInfo *tab)
 
static void RememberIndexForRebuilding (Oid indoid, AlteredTableInfo *tab)
 
static void ATPostAlterTypeCleanup (List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
 
static void ATPostAlterTypeParse (Oid oldId, Oid oldRelId, Oid refRelId, char *cmd, List **wqueue, LOCKMODE lockmode, bool rewrite)
 
static void RebuildConstraintComment (AlteredTableInfo *tab, int pass, Oid objid, Relation rel, List *domname, const char *conname)
 
static void TryReuseIndex (Oid oldId, IndexStmt *stmt)
 
static void TryReuseForeignKey (Oid oldId, Constraint *con)
 
static ObjectAddress ATExecAlterColumnGenericOptions (Relation rel, const char *colName, List *options, LOCKMODE lockmode)
 
static void change_owner_fix_column_acls (Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
 
static void change_owner_recurse_to_sequences (Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
 
static ObjectAddress ATExecClusterOn (Relation rel, const char *indexName, LOCKMODE lockmode)
 
static void ATExecDropCluster (Relation rel, LOCKMODE lockmode)
 
static bool ATPrepChangePersistence (Relation rel, bool toLogged)
 
static void ATPrepSetTableSpace (AlteredTableInfo *tab, Relation rel, const char *tablespacename, LOCKMODE lockmode)
 
static void ATExecSetTableSpace (Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
 
static void ATExecSetTableSpaceNoStorage (Relation rel, Oid newTableSpace)
 
static void ATExecSetRelOptions (Relation rel, List *defList, AlterTableType operation, LOCKMODE lockmode)
 
static void ATExecEnableDisableTrigger (Relation rel, const char *trigname, char fires_when, bool skip_system, LOCKMODE lockmode)
 
static void ATExecEnableDisableRule (Relation rel, const char *rulename, char fires_when, LOCKMODE lockmode)
 
static void ATPrepAddInherit (Relation child_rel)
 
static ObjectAddress ATExecAddInherit (Relation child_rel, RangeVar *parent, LOCKMODE lockmode)
 
static ObjectAddress ATExecDropInherit (Relation rel, RangeVar *parent, LOCKMODE lockmode)
 
static void drop_parent_dependency (Oid relid, Oid refclassid, Oid refobjid, DependencyType deptype)
 
static ObjectAddress ATExecAddOf (Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
 
static void ATExecDropOf (Relation rel, LOCKMODE lockmode)
 
static void ATExecReplicaIdentity (Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode)
 
static void ATExecGenericOptions (Relation rel, List *options)
 
static void ATExecEnableRowSecurity (Relation rel)
 
static void ATExecDisableRowSecurity (Relation rel)
 
static void ATExecForceNoForceRowSecurity (Relation rel, bool force_rls)
 
static void index_copy_data (Relation rel, RelFileNode newrnode)
 
static const char * storage_name (char c)
 
static void RangeVarCallbackForDropRelation (const RangeVar *rel, Oid relOid, Oid oldRelOid, void *arg)
 
static void RangeVarCallbackForAlterRelation (const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
 
static PartitionSpectransformPartitionSpec (Relation rel, PartitionSpec *partspec, char *strategy)
 
static void ComputePartitionAttrs (ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs, List **partexprs, Oid *partopclass, Oid *partcollation, char strategy)
 
static void CreateInheritance (Relation child_rel, Relation parent_rel)
 
static void RemoveInheritance (Relation child_rel, Relation parent_rel)
 
static ObjectAddress ATExecAttachPartition (List **wqueue, Relation rel, PartitionCmd *cmd)
 
static void AttachPartitionEnsureIndexes (Relation rel, Relation attachrel)
 
static void QueuePartitionConstraintValidation (List **wqueue, Relation scanrel, List *partConstraint, bool validate_default)
 
static void CloneRowTriggersToPartition (Relation parent, Relation partition)
 
static void DropClonedTriggersFromPartition (Oid partitionId)
 
static ObjectAddress ATExecDetachPartition (Relation rel, RangeVar *name)
 
static ObjectAddress ATExecAttachPartitionIdx (List **wqueue, Relation rel, RangeVar *name)
 
static void validatePartitionedIndex (Relation partedIdx, Relation partedTbl)
 
static void refuseDupeIndexAttach (Relation parentIdx, Relation partIdx, Relation partitionTbl)
 
static ListGetParentedForeignKeyRefs (Relation partition)
 
static void ATDetachCheckNoForeignKeyRefs (Relation partition)
 
ObjectAddress DefineRelation (CreateStmt *stmt, char relkind, Oid ownerId, ObjectAddress *typaddress, const char *queryString)
 
static void DropErrorMsgNonExistent (RangeVar *rel, char rightkind, bool missing_ok)
 
static void DropErrorMsgWrongType (const char *relname, char wrongkind, char rightkind)
 
void RemoveRelations (DropStmt *drop)
 
void ExecuteTruncate (TruncateStmt *stmt)
 
void ExecuteTruncateGuts (List *explicit_rels, List *relids, List *relids_logged, DropBehavior behavior, bool restart_seqs)
 
void SetRelationHasSubclass (Oid relationId, bool relhassubclass)
 
static void renameatt_check (Oid myrelid, Form_pg_class classform, bool recursing)
 
static AttrNumber renameatt_internal (Oid myrelid, const char *oldattname, const char *newattname, bool recurse, bool recursing, int expected_parents, DropBehavior behavior)
 
static void RangeVarCallbackForRenameAttribute (const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
 
ObjectAddress renameatt (RenameStmt *stmt)
 
static ObjectAddress rename_constraint_internal (Oid myrelid, Oid mytypid, const char *oldconname, const char *newconname, bool recurse, bool recursing, int expected_parents)
 
ObjectAddress RenameConstraint (RenameStmt *stmt)
 
ObjectAddress RenameRelation (RenameStmt *stmt)
 
void RenameRelationInternal (Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
 
void CheckTableNotInUse (Relation rel, const char *stmt)
 
Oid AlterTableLookupRelation (AlterTableStmt *stmt, LOCKMODE lockmode)
 
void AlterTable (AlterTableStmt *stmt, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
void AlterTableInternal (Oid relid, List *cmds, bool recurse)
 
LOCKMODE AlterTableGetLockLevel (List *cmds)
 
void find_composite_type_dependencies (Oid typeOid, Relation origRelation, const char *origTypeName)
 
void check_of_type (HeapTuple typetuple)
 
static void CreateFKCheckTrigger (Oid myRelOid, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid, bool on_insert)
 
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 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   11

Definition at line 152 of file tablecmds.c.

Referenced by ATRewriteCatalogs().

◆ AT_PASS_ADD_COL

#define AT_PASS_ADD_COL   4 /* ADD COLUMN */

Definition at line 145 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ AT_PASS_ADD_CONSTR

#define AT_PASS_ADD_CONSTR   5 /* ADD constraints (initial examination) */

Definition at line 146 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ AT_PASS_ADD_INDEX

#define AT_PASS_ADD_INDEX   8 /* ADD indexes */

Definition at line 149 of file tablecmds.c.

Referenced by ATParseTransformCmd(), and ATPrepCmd().

◆ AT_PASS_ADD_INDEXCONSTR

#define AT_PASS_ADD_INDEXCONSTR   7 /* ADD index-based constraints */

Definition at line 148 of file tablecmds.c.

Referenced by ATParseTransformCmd(), and ATPrepCmd().

◆ AT_PASS_ADD_OTHERCONSTR

#define AT_PASS_ADD_OTHERCONSTR   9 /* ADD other constraints, defaults */

Definition at line 150 of file tablecmds.c.

Referenced by ATParseTransformCmd(), and ATPrepCmd().

◆ AT_PASS_ALTER_TYPE

#define AT_PASS_ALTER_TYPE   1 /* ALTER COLUMN TYPE */

Definition at line 141 of file tablecmds.c.

Referenced by ATPrepCmd(), and ATRewriteCatalogs().

◆ AT_PASS_COL_ATTRS

#define AT_PASS_COL_ATTRS   6 /* set column attributes, eg NOT NULL */

Definition at line 147 of file tablecmds.c.

Referenced by ATParseTransformCmd(), and ATPrepCmd().

◆ AT_PASS_DROP

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

Definition at line 140 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ AT_PASS_MISC

#define AT_PASS_MISC   10 /* other stuff */

Definition at line 151 of file tablecmds.c.

Referenced by ATParseTransformCmd(), and ATPrepCmd().

◆ AT_PASS_OLD_CONSTR

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

Definition at line 143 of file tablecmds.c.

Referenced by ATPostAlterTypeCleanup(), and ATPostAlterTypeParse().

◆ AT_PASS_OLD_INDEX

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

Definition at line 142 of file tablecmds.c.

Referenced by ATPostAlterTypeParse().

◆ AT_PASS_UNSET

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

Definition at line 139 of file tablecmds.c.

Referenced by ATParseTransformCmd(), and ATPrepCmd().

◆ ATT_COMPOSITE_TYPE

#define ATT_COMPOSITE_TYPE   0x0010

Definition at line 296 of file tablecmds.c.

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

◆ ATT_FOREIGN_TABLE

◆ ATT_INDEX

#define ATT_INDEX   0x0008

Definition at line 295 of file tablecmds.c.

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

◆ ATT_MATVIEW

#define ATT_MATVIEW   0x0004

Definition at line 294 of file tablecmds.c.

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

◆ ATT_PARTITIONED_INDEX

#define ATT_PARTITIONED_INDEX   0x0040

Definition at line 298 of file tablecmds.c.

Referenced by ATPrepCmd(), and ATSimplePermissions().

◆ ATT_TABLE

◆ ATT_VIEW

#define ATT_VIEW   0x0002

Definition at line 293 of file tablecmds.c.

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

◆ child_dependency_type

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

Definition at line 305 of file tablecmds.c.

Referenced by RemoveInheritance(), and StoreCatalogInheritance1().

Typedef Documentation

◆ AlteredTableInfo

◆ NewColumnValue

◆ NewConstraint

typedef struct NewConstraint NewConstraint

◆ OnCommitItem

typedef struct OnCommitItem OnCommitItem

Function Documentation

◆ add_column_collation_dependency()

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

Definition at line 6429 of file tablecmds.c.

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

Referenced by ATExecAddColumn(), and ATExecAlterColumnType().

6430 {
6431  ObjectAddress myself,
6432  referenced;
6433 
6434  /* We know the default collation is pinned, so don't bother recording it */
6435  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
6436  {
6437  myself.classId = RelationRelationId;
6438  myself.objectId = relid;
6439  myself.objectSubId = attnum;
6440  referenced.classId = CollationRelationId;
6441  referenced.objectId = collid;
6442  referenced.objectSubId = 0;
6443  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
6444  }
6445 }
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
#define OidIsValid(objectId)
Definition: c.h:644
int16 attnum
Definition: pg_attribute.h:79

◆ add_column_datatype_dependency()

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

Definition at line 6411 of file tablecmds.c.

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

Referenced by ATExecAddColumn(), and ATExecAlterColumnType().

6412 {
6413  ObjectAddress myself,
6414  referenced;
6415 
6416  myself.classId = RelationRelationId;
6417  myself.objectId = relid;
6418  myself.objectSubId = attnum;
6419  referenced.classId = TypeRelationId;
6420  referenced.objectId = typid;
6421  referenced.objectSubId = 0;
6422  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
6423 }
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
int16 attnum
Definition: pg_attribute.h:79

◆ addFkRecurseReferenced()

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

Definition at line 8626 of file tablecmds.c.

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

8631 {
8632  ObjectAddress address;
8633  Oid constrOid;
8634  char *conname;
8635  bool conislocal;
8636  int coninhcount;
8637  bool connoinherit;
8638 
8639  /*
8640  * Verify relkind for each referenced partition. At the top level, this
8641  * is redundant with a previous check, but we need it when recursing.
8642  */
8643  if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
8644  pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
8645  ereport(ERROR,
8646  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8647  errmsg("referenced relation \"%s\" is not a table",
8648  RelationGetRelationName(pkrel))));
8649 
8650  /*
8651  * Caller supplies us with a constraint name; however, it may be used in
8652  * this partition, so come up with a different one in that case.
8653  */
8655  RelationGetRelid(rel),
8656  fkconstraint->conname))
8659  "fkey",
8660  RelationGetNamespace(rel), NIL);
8661  else
8662  conname = fkconstraint->conname;
8663 
8664  if (OidIsValid(parentConstr))
8665  {
8666  conislocal = false;
8667  coninhcount = 1;
8668  connoinherit = false;
8669  }
8670  else
8671  {
8672  conislocal = true;
8673  coninhcount = 0;
8674 
8675  /*
8676  * always inherit for partitioned tables, never for legacy inheritance
8677  */
8678  connoinherit = rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE;
8679  }
8680 
8681  /*
8682  * Record the FK constraint in pg_constraint.
8683  */
8684  constrOid = CreateConstraintEntry(conname,
8685  RelationGetNamespace(rel),
8686  CONSTRAINT_FOREIGN,
8687  fkconstraint->deferrable,
8688  fkconstraint->initdeferred,
8689  fkconstraint->initially_valid,
8690  parentConstr,
8691  RelationGetRelid(rel),
8692  fkattnum,
8693  numfks,
8694  numfks,
8695  InvalidOid, /* not a domain constraint */
8696  indexOid,
8697  RelationGetRelid(pkrel),
8698  pkattnum,
8699  pfeqoperators,
8700  ppeqoperators,
8701  ffeqoperators,
8702  numfks,
8703  fkconstraint->fk_upd_action,
8704  fkconstraint->fk_del_action,
8705  fkconstraint->fk_matchtype,
8706  NULL, /* no exclusion constraint */
8707  NULL, /* no check constraint */
8708  NULL,
8709  conislocal, /* islocal */
8710  coninhcount, /* inhcount */
8711  connoinherit, /* conNoInherit */
8712  false); /* is_internal */
8713 
8714  ObjectAddressSet(address, ConstraintRelationId, constrOid);
8715 
8716  /*
8717  * Mark the child constraint as part of the parent constraint; it must not
8718  * be dropped on its own. (This constraint is deleted when the partition
8719  * is detached, but a special check needs to occur that the partition
8720  * contains no referenced values.)
8721  */
8722  if (OidIsValid(parentConstr))
8723  {
8724  ObjectAddress referenced;
8725 
8726  ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
8727  recordDependencyOn(&address, &referenced, DEPENDENCY_INTERNAL);
8728  }
8729 
8730  /* make new constraint visible, in case we add more */
8732 
8733  /*
8734  * If the referenced table is a plain relation, create the action triggers
8735  * that enforce the constraint.
8736  */
8737  if (pkrel->rd_rel->relkind == RELKIND_RELATION)
8738  {
8740  fkconstraint,
8741  constrOid, indexOid);
8742  }
8743 
8744  /*
8745  * If the referenced table is partitioned, recurse on ourselves to handle
8746  * each partition. We need one pg_constraint row created for each
8747  * partition in addition to the pg_constraint row for the parent table.
8748  */
8749  if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
8750  {
8752 
8753  for (int i = 0; i < pd->nparts; i++)
8754  {
8755  Relation partRel;
8756  AttrMap *map;
8757  AttrNumber *mapped_pkattnum;
8758  Oid partIndexId;
8759 
8760  partRel = table_open(pd->oids[i], ShareRowExclusiveLock);
8761 
8762  /*
8763  * Map the attribute numbers in the referenced side of the FK
8764  * definition to match the partition's column layout.
8765  */
8767  RelationGetDescr(pkrel));
8768  if (map)
8769  {
8770  mapped_pkattnum = palloc(sizeof(AttrNumber) * numfks);
8771  for (int j = 0; j < numfks; j++)
8772  mapped_pkattnum[j] = map->attnums[pkattnum[j] - 1];
8773  }
8774  else
8775  mapped_pkattnum = pkattnum;
8776 
8777  /* do the deed */
8778  partIndexId = index_get_partition(partRel, indexOid);
8779  if (!OidIsValid(partIndexId))
8780  elog(ERROR, "index for %u not found in partition %s",
8781  indexOid, RelationGetRelationName(partRel));
8782  addFkRecurseReferenced(wqueue, fkconstraint, rel, partRel,
8783  partIndexId, constrOid, numfks,
8784  mapped_pkattnum, fkattnum,
8785  pfeqoperators, ppeqoperators, ffeqoperators,
8786  old_check_ok);
8787 
8788  /* Done -- clean up (but keep the lock) */
8789  table_close(partRel, NoLock);
8790  if (map)
8791  {
8792  pfree(mapped_pkattnum);
8793  free_attrmap(map);
8794  }
8795  }
8796  }
8797 
8798  return address;
8799 }
#define NIL
Definition: pg_list.h:65
Oid index_get_partition(Relation partition, Oid indexId)
Definition: partition.c:153
char * ChooseConstraintName(const char *name1, const char *name2, const char *label, Oid namespaceid, List *others)
bool ConstraintNameIsUsed(ConstraintCategory conCat, Oid objId, const char *conname)
static char * ChooseForeignKeyConstraintNameAddition(List *colnames)
Definition: tablecmds.c:8009
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
void free_attrmap(AttrMap *map)
Definition: attmap.c:57
#define RelationGetDescr(relation)
Definition: rel.h:482
char fk_matchtype
Definition: parsenodes.h:2189
Oid CreateConstraintEntry(const char *constraintName, Oid constraintNamespace, char constraintType, bool isDeferrable, bool isDeferred, bool isValidated, Oid parentConstrId, Oid relId, const int16 *constraintKey, int constraintNKeys, int constraintNTotalKeys, Oid domainId, Oid indexRelId, Oid foreignRelId, const int16 *foreignKey, const Oid *pfEqOp, const Oid *ppEqOp, const Oid *ffEqOp, int foreignNKeys, char foreignUpdateType, char foreignDeleteType, char foreignMatchType, const Oid *exclOp, Node *conExpr, const char *conBin, bool conIsLocal, int conInhCount, bool conNoInherit, bool is_internal)
Definition: pg_constraint.c:50
int errcode(int sqlerrcode)
Definition: elog.c:610
bool initdeferred
Definition: parsenodes.h:2157
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
char * conname
Definition: parsenodes.h:2155
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:644
Definition: attmap.h:34
void pfree(void *pointer)
Definition: mcxt.c:1056
static ObjectAddress addFkRecurseReferenced(List **wqueue, Constraint *fkconstraint, Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr, int numfks, int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators, bool old_check_ok)
Definition: tablecmds.c:8626
AttrMap * build_attrmap_by_name_if_req(TupleDesc indesc, TupleDesc outdesc)
Definition: attmap.c:259
#define ERROR
Definition: elog.h:43
bool deferrable
Definition: parsenodes.h:2156
#define NoLock
Definition: lockdefs.h:34
PartitionDesc RelationGetPartitionDesc(Relation rel)
Definition: partdesc.c:65
#define RelationGetRelationName(relation)
Definition: rel.h:490
static void createForeignKeyActionTriggers(Relation rel, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid)
Definition: tablecmds.c:10459
void CommandCounterIncrement(void)
Definition: xact.c:1006
#define InvalidOid
Definition: postgres_ext.h:36
bool initially_valid
Definition: parsenodes.h:2198
#define ereport(elevel,...)
Definition: elog.h:144
char fk_del_action
Definition: parsenodes.h:2191
#define ShareRowExclusiveLock
Definition: lockdefs.h:42
AttrNumber * attnums
Definition: attmap.h:36
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
int i
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:456
List * fk_attrs
Definition: parsenodes.h:2187
char fk_upd_action
Definition: parsenodes.h:2190
#define RelationGetNamespace(relation)
Definition: rel.h:497

◆ addFkRecurseReferencing()

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

Definition at line 8831 of file tablecmds.c.

References AssertArg, 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, lappend(), lfirst_node, NewConstraint::name, NIL, NoLock, PartitionDescData::nparts, ObjectAddressSet, OidIsValid, PartitionDescData::oids, palloc0(), NewConstraint::qual, RelationData::rd_rel, recordDependencyOn(), NewConstraint::refindid, NewConstraint::refrelid, RelationGetDescr, RelationGetFKeyList(), RelationGetNamespace, RelationGetPartitionDesc(), RelationGetRelationName, RelationGetRelid, Constraint::skip_validation, table_close(), table_open(), and tryAttachPartitionForeignKey().

Referenced by ATAddForeignKeyConstraint(), and CloneFkReferencing().

8836 {
8837  AssertArg(OidIsValid(parentConstr));
8838 
8839  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
8840  ereport(ERROR,
8841  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8842  errmsg("foreign key constraints are not supported on foreign tables")));
8843 
8844  /*
8845  * If the referencing relation is a plain table, add the check triggers to
8846  * it and, if necessary, schedule it to be checked in Phase 3.
8847  *
8848  * If the relation is partitioned, drill down to do it to its partitions.
8849  */
8850  if (rel->rd_rel->relkind == RELKIND_RELATION)
8851  {
8853  RelationGetRelid(pkrel),
8854  fkconstraint,
8855  parentConstr,
8856  indexOid);
8857 
8858  /*
8859  * Tell Phase 3 to check that the constraint is satisfied by existing
8860  * rows. We can skip this during table creation, when requested
8861  * explicitly by specifying NOT VALID in an ADD FOREIGN KEY command,
8862  * and when we're recreating a constraint following a SET DATA TYPE
8863  * operation that did not impugn its validity.
8864  */
8865  if (wqueue && !old_check_ok && !fkconstraint->skip_validation)
8866  {
8867  NewConstraint *newcon;
8868  AlteredTableInfo *tab;
8869 
8870  tab = ATGetQueueEntry(wqueue, rel);
8871 
8872  newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
8873  newcon->name = get_constraint_name(parentConstr);
8874  newcon->contype = CONSTR_FOREIGN;
8875  newcon->refrelid = RelationGetRelid(pkrel);
8876  newcon->refindid = indexOid;
8877  newcon->conid = parentConstr;
8878  newcon->qual = (Node *) fkconstraint;
8879 
8880  tab->constraints = lappend(tab->constraints, newcon);
8881  }
8882  }
8883  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
8884  {
8886 
8887  /*
8888  * Recurse to take appropriate action on each partition; either we
8889  * find an existing constraint to reparent to ours, or we create a new
8890  * one.
8891  */
8892  for (int i = 0; i < pd->nparts; i++)
8893  {
8894  Oid partitionId = pd->oids[i];
8895  Relation partition = table_open(partitionId, lockmode);
8896  List *partFKs;
8897  AttrMap *attmap;
8898  AttrNumber mapped_fkattnum[INDEX_MAX_KEYS];
8899  bool attached;
8900  char *conname;
8901  Oid constrOid;
8902  ObjectAddress address,
8903  referenced;
8904  ListCell *cell;
8905 
8906  CheckTableNotInUse(partition, "ALTER TABLE");
8907 
8908  attmap = build_attrmap_by_name(RelationGetDescr(partition),
8909  RelationGetDescr(rel));
8910  for (int j = 0; j < numfks; j++)
8911  mapped_fkattnum[j] = attmap->attnums[fkattnum[j] - 1];
8912 
8913  /* Check whether an existing constraint can be repurposed */
8914  partFKs = copyObject(RelationGetFKeyList(partition));
8915  attached = false;
8916  foreach(cell, partFKs)
8917  {
8918  ForeignKeyCacheInfo *fk;
8919 
8920  fk = lfirst_node(ForeignKeyCacheInfo, cell);
8922  partitionId,
8923  parentConstr,
8924  numfks,
8925  mapped_fkattnum,
8926  pkattnum,
8927  pfeqoperators))
8928  {
8929  attached = true;
8930  break;
8931  }
8932  }
8933  if (attached)
8934  {
8935  table_close(partition, NoLock);
8936  continue;
8937  }
8938 
8939  /*
8940  * No luck finding a good constraint to reuse; create our own.
8941  */
8943  RelationGetRelid(partition),
8944  fkconstraint->conname))
8945  conname = ChooseConstraintName(RelationGetRelationName(partition),
8947  "fkey",
8948  RelationGetNamespace(partition), NIL);
8949  else
8950  conname = fkconstraint->conname;
8951  constrOid =
8952  CreateConstraintEntry(conname,
8953  RelationGetNamespace(partition),
8954  CONSTRAINT_FOREIGN,
8955  fkconstraint->deferrable,
8956  fkconstraint->initdeferred,
8957  fkconstraint->initially_valid,
8958  parentConstr,
8959  partitionId,
8960  mapped_fkattnum,
8961  numfks,
8962  numfks,
8963  InvalidOid,
8964  indexOid,
8965  RelationGetRelid(pkrel),
8966  pkattnum,
8967  pfeqoperators,
8968  ppeqoperators,
8969  ffeqoperators,
8970  numfks,
8971  fkconstraint->fk_upd_action,
8972  fkconstraint->fk_del_action,
8973  fkconstraint->fk_matchtype,
8974  NULL,
8975  NULL,
8976  NULL,
8977  false,
8978  1,
8979  false,
8980  false);
8981 
8982  /*
8983  * Give this constraint partition-type dependencies on the parent
8984  * constraint as well as the table.
8985  */
8986  ObjectAddressSet(address, ConstraintRelationId, constrOid);
8987  ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
8988  recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_PRI);
8989  ObjectAddressSet(referenced, RelationRelationId, partitionId);
8990  recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_SEC);
8991 
8992  /* Make all this visible before recursing */
8994 
8995  /* call ourselves to finalize the creation and we're done */
8996  addFkRecurseReferencing(wqueue, fkconstraint, partition, pkrel,
8997  indexOid,
8998  constrOid,
8999  numfks,
9000  pkattnum,
9001  mapped_fkattnum,
9002  pfeqoperators,
9003  ppeqoperators,
9004  ffeqoperators,
9005  old_check_ok,
9006  lockmode);
9007 
9008  table_close(partition, NoLock);
9009  }
9010  }
9011 }
#define NIL
Definition: pg_list.h:65
char * ChooseConstraintName(const char *name1, const char *name2, const char *label, Oid namespaceid, List *others)
static void createForeignKeyCheckTriggers(Oid myRelOid, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid)
Definition: tablecmds.c:10580
bool ConstraintNameIsUsed(ConstraintCategory conCat, Oid objId, const char *conname)
char * name
Definition: tablecmds.c:187
static char * ChooseForeignKeyConstraintNameAddition(List *colnames)
Definition: tablecmds.c:8009
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define RelationGetDescr(relation)
Definition: rel.h:482
char * get_constraint_name(Oid conoid)
Definition: lsyscache.c:1079
static void addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint, Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr, int numfks, int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators, bool old_check_ok, LOCKMODE lockmode)
Definition: tablecmds.c:8831
char fk_matchtype
Definition: parsenodes.h:2189
Oid CreateConstraintEntry(const char *constraintName, Oid constraintNamespace, char constraintType, bool isDeferrable, bool isDeferred, bool isValidated, Oid parentConstrId, Oid relId, const int16 *constraintKey, int constraintNKeys, int constraintNTotalKeys, Oid domainId, Oid indexRelId, Oid foreignRelId, const int16 *foreignKey, const Oid *pfEqOp, const Oid *ppEqOp, const Oid *ffEqOp, int foreignNKeys, char foreignUpdateType, char foreignDeleteType, char foreignMatchType, const Oid *exclOp, Node *conExpr, const char *conBin, bool conIsLocal, int conInhCount, bool conNoInherit, bool is_internal)
Definition: pg_constraint.c:50
Node * qual
Definition: tablecmds.c:192
Definition: nodes.h:529
int errcode(int sqlerrcode)
Definition: elog.c:610
bool initdeferred
Definition: parsenodes.h:2157
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
char * conname
Definition: parsenodes.h:2155
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:644
List * constraints
Definition: tablecmds.c:163
Definition: attmap.h:34
static bool tryAttachPartitionForeignKey(ForeignKeyCacheInfo *fk, Oid partRelid, Oid parentConstrOid, int numfks, AttrNumber *mapped_conkey, AttrNumber *confkey, Oid *conpfeqop)
Definition: tablecmds.c:9428
#define ERROR
Definition: elog.h:43
bool deferrable
Definition: parsenodes.h:2156
#define lfirst_node(type, lc)
Definition: pg_list.h:193
#define NoLock
Definition: lockdefs.h:34
PartitionDesc RelationGetPartitionDesc(Relation rel)
Definition: partdesc.c:65
#define RelationGetRelationName(relation)
Definition: rel.h:490
static AlteredTableInfo * ATGetQueueEntry(List **wqueue, Relation rel)
Definition: tablecmds.c:5439
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3533
#define AssertArg(condition)
Definition: c.h:740
List * lappend(List *list, void *datum)
Definition: list.c:321
ConstrType contype
Definition: tablecmds.c:188
void * palloc0(Size size)
Definition: mcxt.c:980
void CommandCounterIncrement(void)
Definition: xact.c:1006
#define InvalidOid
Definition: postgres_ext.h:36
bool initially_valid
Definition: parsenodes.h:2198
#define ereport(elevel,...)
Definition: elog.h:144
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc)
Definition: attmap.c:174
char fk_del_action
Definition: parsenodes.h:2191
AttrNumber * attnums
Definition: attmap.h:36
#define INDEX_MAX_KEYS
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
List * RelationGetFKeyList(Relation relation)
Definition: relcache.c:4398
int errmsg(const char *fmt,...)
Definition: elog.c:824
int i
#define copyObject(obj)
Definition: nodes.h:645
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
bool skip_validation
Definition: parsenodes.h:2197
#define RelationGetRelid(relation)
Definition: rel.h:456
List * fk_attrs
Definition: parsenodes.h:2187
char fk_upd_action
Definition: parsenodes.h:2190
#define RelationGetNamespace(relation)
Definition: rel.h:497

◆ AlterIndexNamespaces()

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

Definition at line 15107 of file tablecmds.c.

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

Referenced by AlterTableNamespaceInternal().

15109 {
15110  List *indexList;
15111  ListCell *l;
15112 
15113  indexList = RelationGetIndexList(rel);
15114 
15115  foreach(l, indexList)
15116  {
15117  Oid indexOid = lfirst_oid(l);
15118  ObjectAddress thisobj;
15119 
15120  thisobj.classId = RelationRelationId;
15121  thisobj.objectId = indexOid;
15122  thisobj.objectSubId = 0;
15123 
15124  /*
15125  * Note: currently, the index will not have its own dependency on the
15126  * namespace, so we don't need to do changeDependencyFor(). There's no
15127  * row type in pg_type, either.
15128  *
15129  * XXX this objsMoved test may be pointless -- surely we have a single
15130  * dependency link from a relation to each index?
15131  */
15132  if (!object_address_present(&thisobj, objsMoved))
15133  {
15134  AlterRelationNamespaceInternal(classRel, indexOid,
15135  oldNspOid, newNspOid,
15136  false, objsMoved);
15137  add_exact_object_address(&thisobj, objsMoved);
15138  }
15139  }
15140 
15141  list_free(indexList);
15142 }
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2525
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2465
unsigned int Oid
Definition: postgres_ext.h:31
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:15037
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4507
void list_free(List *list)
Definition: list.c:1376
Definition: pg_list.h:50
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ AlterRelationNamespaceInternal()

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

Definition at line 15037 of file tablecmds.c.

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

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

15041 {
15042  HeapTuple classTup;
15043  Form_pg_class classForm;
15044  ObjectAddress thisobj;
15045  bool already_done = false;
15046 
15047  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
15048  if (!HeapTupleIsValid(classTup))
15049  elog(ERROR, "cache lookup failed for relation %u", relOid);
15050  classForm = (Form_pg_class) GETSTRUCT(classTup);
15051 
15052  Assert(classForm->relnamespace == oldNspOid);
15053 
15054  thisobj.classId = RelationRelationId;
15055  thisobj.objectId = relOid;
15056  thisobj.objectSubId = 0;
15057 
15058  /*
15059  * If the object has already been moved, don't move it again. If it's
15060  * already in the right place, don't move it, but still fire the object
15061  * access hook.
15062  */
15063  already_done = object_address_present(&thisobj, objsMoved);
15064  if (!already_done && oldNspOid != newNspOid)
15065  {
15066  /* check for duplicate name (more friendly than unique-index failure) */
15067  if (get_relname_relid(NameStr(classForm->relname),
15068  newNspOid) != InvalidOid)
15069  ereport(ERROR,
15070  (errcode(ERRCODE_DUPLICATE_TABLE),
15071  errmsg("relation \"%s\" already exists in schema \"%s\"",
15072  NameStr(classForm->relname),
15073  get_namespace_name(newNspOid))));
15074 
15075  /* classTup is a copy, so OK to scribble on */
15076  classForm->relnamespace = newNspOid;
15077 
15078  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
15079 
15080  /* Update dependency on schema if caller said so */
15081  if (hasDependEntry &&
15082  changeDependencyFor(RelationRelationId,
15083  relOid,
15084  NamespaceRelationId,
15085  oldNspOid,
15086  newNspOid) != 1)
15087  elog(ERROR, "failed to change schema dependency for relation \"%s\"",
15088  NameStr(classForm->relname));
15089  }
15090  if (!already_done)
15091  {
15092  add_exact_object_address(&thisobj, objsMoved);
15093 
15094  InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
15095  }
15096 
15097  heap_freetuple(classTup);
15098 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2525
int errcode(int sqlerrcode)
Definition: elog.c:610
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2465
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1797
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:738
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
int errmsg(const char *fmt,...)
Definition: elog.c:824
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:346
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:615

◆ AlterSeqNamespaces()

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

Definition at line 15152 of file tablecmds.c.

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

Referenced by AlterTableNamespaceInternal().

15155 {
15156  Relation depRel;
15157  SysScanDesc scan;
15158  ScanKeyData key[2];
15159  HeapTuple tup;
15160 
15161  /*
15162  * SERIAL sequences are those having an auto dependency on one of the
15163  * table's columns (we don't care *which* column, exactly).
15164  */
15165  depRel = table_open(DependRelationId, AccessShareLock);
15166 
15167  ScanKeyInit(&key[0],
15168  Anum_pg_depend_refclassid,
15169  BTEqualStrategyNumber, F_OIDEQ,
15170  ObjectIdGetDatum(RelationRelationId));
15171  ScanKeyInit(&key[1],
15172  Anum_pg_depend_refobjid,
15173  BTEqualStrategyNumber, F_OIDEQ,
15175  /* we leave refobjsubid unspecified */
15176 
15177  scan = systable_beginscan(depRel, DependReferenceIndexId, true,
15178  NULL, 2, key);
15179 
15180  while (HeapTupleIsValid(tup = systable_getnext(scan)))
15181  {
15182  Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
15183  Relation seqRel;
15184 
15185  /* skip dependencies other than auto dependencies on columns */
15186  if (depForm->refobjsubid == 0 ||
15187  depForm->classid != RelationRelationId ||
15188  depForm->objsubid != 0 ||
15189  !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
15190  continue;
15191 
15192  /* Use relation_open just in case it's an index */
15193  seqRel = relation_open(depForm->objid, lockmode);
15194 
15195  /* skip non-sequence relations */
15196  if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
15197  {
15198  /* No need to keep the lock */
15199  relation_close(seqRel, lockmode);
15200  continue;
15201  }
15202 
15203  /* Fix the pg_class and pg_depend entries */
15204  AlterRelationNamespaceInternal(classRel, depForm->objid,
15205  oldNspOid, newNspOid,
15206  true, objsMoved);
15207 
15208  /*
15209  * Sequences used to have entries in pg_type, but no longer do. If we
15210  * ever re-instate that, we'll need to move the pg_type entry to the
15211  * new namespace, too (using AlterTypeNamespaceInternal).
15212  */
15213  Assert(RelationGetForm(seqRel)->reltype == InvalidOid);
15214 
15215  /* Now we can close it. Keep the lock till end of transaction. */
15216  relation_close(seqRel, NoLock);
15217  }
15218 
15219  systable_endscan(scan);
15220 
15222 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:529
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define RelationGetForm(relation)
Definition: rel.h:450
#define DependReferenceIndexId
Definition: indexing.h:151
#define AccessShareLock
Definition: lockdefs.h:36
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:356
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:448
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:71
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define Assert(condition)
Definition: c.h:738
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:15037
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:456
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ AlterTable()

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

Definition at line 3617 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3619 {
3620  Relation rel;
3621 
3622  /* Caller is required to provide an adequate lock. */
3623  rel = relation_open(context->relid, NoLock);
3624 
3625  CheckTableNotInUse(rel, "ALTER TABLE");
3626 
3627  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
3628 }
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:3952
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3533
bool inh
Definition: primnodes.h:69
RangeVar * relation
Definition: parsenodes.h:1777

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)

Definition at line 3691 of file tablecmds.c.

References AccessExclusiveLock, AccessShareLock, AlterTableGetRelOptionsLockLevel(), AT_AddColumn, AT_AddColumnToView, AT_AddConstraint, AT_AddConstraintRecurse, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AddInherit, AT_AddOf, AT_AlterColumnGenericOptions, AT_AlterColumnType, AT_AlterConstraint, AT_AttachPartition, AT_ChangeOwner, AT_CheckNotNull, AT_ClusterOn, AT_ColumnDefault, AT_DetachPartition, AT_DisableRowSecurity, AT_DisableRule, AT_DisableTrig, AT_DisableTrigAll, AT_DisableTrigUser, AT_DropCluster, AT_DropColumn, AT_DropConstraint, AT_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_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().

3692 {
3693  /*
3694  * This only works if we read catalog tables using MVCC snapshots.
3695  */
3696  ListCell *lcmd;
3698 
3699  foreach(lcmd, cmds)
3700  {
3701  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3702  LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
3703 
3704  switch (cmd->subtype)
3705  {
3706  /*
3707  * These subcommands rewrite the heap, so require full locks.
3708  */
3709  case AT_AddColumn: /* may rewrite heap, in some cases and visible
3710  * to SELECT */
3711  case AT_SetTableSpace: /* must rewrite heap */
3712  case AT_AlterColumnType: /* must rewrite heap */
3713  cmd_lockmode = AccessExclusiveLock;
3714  break;
3715 
3716  /*
3717  * These subcommands may require addition of toast tables. If
3718  * we add a toast table to a table currently being scanned, we
3719  * might miss data added to the new toast table by concurrent
3720  * insert transactions.
3721  */
3722  case AT_SetStorage: /* may add toast tables, see
3723  * ATRewriteCatalogs() */
3724  cmd_lockmode = AccessExclusiveLock;
3725  break;
3726 
3727  /*
3728  * Removing constraints can affect SELECTs that have been
3729  * optimized assuming the constraint holds true. See also
3730  * CloneFkReferenced.
3731  */
3732  case AT_DropConstraint: /* as DROP INDEX */
3733  case AT_DropNotNull: /* may change some SQL plans */
3734  cmd_lockmode = AccessExclusiveLock;
3735  break;
3736 
3737  /*
3738  * Subcommands that may be visible to concurrent SELECTs
3739  */
3740  case AT_DropColumn: /* change visible to SELECT */
3741  case AT_AddColumnToView: /* CREATE VIEW */
3742  case AT_DropOids: /* used to equiv to DropColumn */
3743  case AT_EnableAlwaysRule: /* may change SELECT rules */
3744  case AT_EnableReplicaRule: /* may change SELECT rules */
3745  case AT_EnableRule: /* may change SELECT rules */
3746  case AT_DisableRule: /* may change SELECT rules */
3747  cmd_lockmode = AccessExclusiveLock;
3748  break;
3749 
3750  /*
3751  * Changing owner may remove implicit SELECT privileges
3752  */
3753  case AT_ChangeOwner: /* change visible to SELECT */
3754  cmd_lockmode = AccessExclusiveLock;
3755  break;
3756 
3757  /*
3758  * Changing foreign table options may affect optimization.
3759  */
3760  case AT_GenericOptions:
3762  cmd_lockmode = AccessExclusiveLock;
3763  break;
3764 
3765  /*
3766  * These subcommands affect write operations only.
3767  */
3768  case AT_EnableTrig:
3769  case AT_EnableAlwaysTrig:
3770  case AT_EnableReplicaTrig:
3771  case AT_EnableTrigAll:
3772  case AT_EnableTrigUser:
3773  case AT_DisableTrig:
3774  case AT_DisableTrigAll:
3775  case AT_DisableTrigUser:
3776  cmd_lockmode = ShareRowExclusiveLock;
3777  break;
3778 
3779  /*
3780  * These subcommands affect write operations only. XXX
3781  * Theoretically, these could be ShareRowExclusiveLock.
3782  */
3783  case AT_ColumnDefault:
3784  case AT_AlterConstraint:
3785  case AT_AddIndex: /* from ADD CONSTRAINT */
3786  case AT_AddIndexConstraint:
3787  case AT_ReplicaIdentity:
3788  case AT_SetNotNull:
3789  case AT_EnableRowSecurity:
3790  case AT_DisableRowSecurity:
3791  case AT_ForceRowSecurity:
3792  case AT_NoForceRowSecurity:
3793  case AT_AddIdentity:
3794  case AT_DropIdentity:
3795  case AT_SetIdentity:
3796  case AT_DropExpression:
3797  cmd_lockmode = AccessExclusiveLock;
3798  break;
3799 
3800  case AT_AddConstraint:
3801  case AT_AddConstraintRecurse: /* becomes AT_AddConstraint */
3802  case AT_ReAddConstraint: /* becomes AT_AddConstraint */
3803  case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
3804  if (IsA(cmd->def, Constraint))
3805  {
3806  Constraint *con = (Constraint *) cmd->def;
3807 
3808  switch (con->contype)
3809  {
3810  case CONSTR_EXCLUSION:
3811  case CONSTR_PRIMARY:
3812  case CONSTR_UNIQUE:
3813 
3814  /*
3815  * Cases essentially the same as CREATE INDEX. We
3816  * could reduce the lock strength to ShareLock if
3817  * we can work out how to allow concurrent catalog
3818  * updates. XXX Might be set down to
3819  * ShareRowExclusiveLock but requires further
3820  * analysis.
3821  */
3822  cmd_lockmode = AccessExclusiveLock;
3823  break;
3824  case CONSTR_FOREIGN:
3825 
3826  /*
3827  * We add triggers to both tables when we add a
3828  * Foreign Key, so the lock level must be at least
3829  * as strong as CREATE TRIGGER.
3830  */
3831  cmd_lockmode = ShareRowExclusiveLock;
3832  break;
3833 
3834  default:
3835  cmd_lockmode = AccessExclusiveLock;
3836  }
3837  }
3838  break;
3839 
3840  /*
3841  * These subcommands affect inheritance behaviour. Queries
3842  * started before us will continue to see the old inheritance
3843  * behaviour, while queries started after we commit will see
3844  * new behaviour. No need to prevent reads or writes to the
3845  * subtable while we hook it up though. Changing the TupDesc
3846  * may be a problem, so keep highest lock.
3847  */
3848  case AT_AddInherit:
3849  case AT_DropInherit:
3850  cmd_lockmode = AccessExclusiveLock;
3851  break;
3852 
3853  /*
3854  * These subcommands affect implicit row type conversion. They
3855  * have affects similar to CREATE/DROP CAST on queries. don't
3856  * provide for invalidating parse trees as a result of such
3857  * changes, so we keep these at AccessExclusiveLock.
3858  */
3859  case AT_AddOf:
3860  case AT_DropOf:
3861  cmd_lockmode = AccessExclusiveLock;
3862  break;
3863 
3864  /*
3865  * Only used by CREATE OR REPLACE VIEW which must conflict
3866  * with an SELECTs currently using the view.
3867  */
3868  case AT_ReplaceRelOptions:
3869  cmd_lockmode = AccessExclusiveLock;
3870  break;
3871 
3872  /*
3873  * These subcommands affect general strategies for performance
3874  * and maintenance, though don't change the semantic results
3875  * from normal data reads and writes. Delaying an ALTER TABLE
3876  * behind currently active writes only delays the point where
3877  * the new strategy begins to take effect, so there is no
3878  * benefit in waiting. In this case the minimum restriction
3879  * applies: we don't currently allow concurrent catalog
3880  * updates.
3881  */
3882  case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
3883  case AT_ClusterOn: /* Uses MVCC in getIndexes() */
3884  case AT_DropCluster: /* Uses MVCC in getIndexes() */
3885  case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
3886  case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
3887  cmd_lockmode = ShareUpdateExclusiveLock;
3888  break;
3889 
3890  case AT_SetLogged:
3891  case AT_SetUnLogged:
3892  cmd_lockmode = AccessExclusiveLock;
3893  break;
3894 
3895  case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
3896  cmd_lockmode = ShareUpdateExclusiveLock;
3897  break;
3898 
3899  /*
3900  * Rel options are more complex than first appears. Options
3901  * are set here for tables, views and indexes; for historical
3902  * reasons these can all be used with ALTER TABLE, so we can't
3903  * decide between them using the basic grammar.
3904  */
3905  case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
3906  * getTables() */
3907  case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
3908  * getTables() */
3909  cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
3910  break;
3911 
3912  case AT_AttachPartition:
3913  cmd_lockmode = ShareUpdateExclusiveLock;
3914  break;
3915 
3916  case AT_DetachPartition:
3917  cmd_lockmode = AccessExclusiveLock;
3918  break;
3919 
3920  case AT_CheckNotNull:
3921 
3922  /*
3923  * This only examines the table's schema; but lock must be
3924  * strong enough to prevent concurrent DROP NOT NULL.
3925  */
3926  cmd_lockmode = AccessShareLock;
3927  break;
3928 
3929  default: /* oops */
3930  elog(ERROR, "unrecognized alter table type: %d",
3931  (int) cmd->subtype);
3932  break;
3933  }
3934 
3935  /*
3936  * Take the greatest lockmode from any subcommand
3937  */
3938  if (cmd_lockmode > lockmode)
3939  lockmode = cmd_lockmode;
3940  }
3941 
3942  return lockmode;
3943 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
int LOCKMODE
Definition: lockdefs.h:26
#define AccessShareLock
Definition: lockdefs.h:36
AlterTableType subtype
Definition: parsenodes.h:1863
#define ERROR
Definition: elog.h:43
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define lfirst(lc)
Definition: pg_list.h:190
#define ShareRowExclusiveLock
Definition: lockdefs.h:42
LOCKMODE AlterTableGetRelOptionsLockLevel(List *defList)
Definition: reloptions.c:2085
#define AccessExclusiveLock
Definition: lockdefs.h:45
#define elog(elevel,...)
Definition: elog.h:214
ConstrType contype
Definition: parsenodes.h:2152
Definition: pg_list.h:50

◆ AlterTableInternal()

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

Definition at line 3646 of file tablecmds.c.

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

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

3647 {
3648  Relation rel;
3649  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
3650 
3651  rel = relation_open(relid, lockmode);
3652 
3654 
3655  ATController(NULL, rel, cmds, recurse, lockmode, NULL);
3656 }
int LOCKMODE
Definition: lockdefs.h:26
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:3952
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:3691
void EventTriggerAlterTableRelid(Oid objectId)

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 3561 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3562 {
3563  return RangeVarGetRelidExtended(stmt->relation, lockmode,
3564  stmt->missing_ok ? RVR_MISSING_OK : 0,
3566  (void *) stmt);
3567 }
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:15551
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:236
RangeVar * relation
Definition: parsenodes.h:1777

◆ AlterTableMoveAll()

Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

Definition at line 13231 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

13232 {
13233  List *relations = NIL;
13234  ListCell *l;
13235  ScanKeyData key[1];
13236  Relation rel;
13237  TableScanDesc scan;
13238  HeapTuple tuple;
13239  Oid orig_tablespaceoid;
13240  Oid new_tablespaceoid;
13241  List *role_oids = roleSpecsToIds(stmt->roles);
13242 
13243  /* Ensure we were not asked to move something we can't */
13244  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
13245  stmt->objtype != OBJECT_MATVIEW)
13246  ereport(ERROR,
13247  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
13248  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
13249 
13250  /* Get the orig and new tablespace OIDs */
13251  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
13252  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
13253 
13254  /* Can't move shared relations in to or out of pg_global */
13255  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
13256  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
13257  new_tablespaceoid == GLOBALTABLESPACE_OID)
13258  ereport(ERROR,
13259  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
13260  errmsg("cannot move relations in to or out of pg_global tablespace")));
13261 
13262  /*
13263  * Must have CREATE rights on the new tablespace, unless it is the
13264  * database default tablespace (which all users implicitly have CREATE
13265  * rights on).
13266  */
13267  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
13268  {
13269  AclResult aclresult;
13270 
13271  aclresult = pg_tablespace_aclcheck(new_tablespaceoid, GetUserId(),
13272  ACL_CREATE);
13273  if (aclresult != ACLCHECK_OK)
13274  aclcheck_error(aclresult, OBJECT_TABLESPACE,
13275  get_tablespace_name(new_tablespaceoid));
13276  }
13277 
13278  /*
13279  * Now that the checks are done, check if we should set either to
13280  * InvalidOid because it is our database's default tablespace.
13281  */
13282  if (orig_tablespaceoid == MyDatabaseTableSpace)
13283  orig_tablespaceoid = InvalidOid;
13284 
13285  if (new_tablespaceoid == MyDatabaseTableSpace)
13286  new_tablespaceoid = InvalidOid;
13287 
13288  /* no-op */
13289  if (orig_tablespaceoid == new_tablespaceoid)
13290  return new_tablespaceoid;
13291 
13292  /*
13293  * Walk the list of objects in the tablespace and move them. This will
13294  * only find objects in our database, of course.
13295  */
13296  ScanKeyInit(&key[0],
13297  Anum_pg_class_reltablespace,
13298  BTEqualStrategyNumber, F_OIDEQ,
13299  ObjectIdGetDatum(orig_tablespaceoid));
13300 
13301  rel = table_open(RelationRelationId, AccessShareLock);
13302  scan = table_beginscan_catalog(rel, 1, key);
13303  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
13304  {
13305  Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
13306  Oid relOid = relForm->oid;
13307 
13308  /*
13309  * Do not move objects in pg_catalog as part of this, if an admin
13310  * really wishes to do so, they can issue the individual ALTER
13311  * commands directly.
13312  *
13313  * Also, explicitly avoid any shared tables, temp tables, or TOAST
13314  * (TOAST will be moved with the main table).
13315  */
13316  if (IsCatalogNamespace(relForm->relnamespace) ||
13317  relForm->relisshared ||
13318  isAnyTempNamespace(relForm->relnamespace) ||
13319  IsToastNamespace(relForm->relnamespace))
13320  continue;
13321 
13322  /* Only move the object type requested */
13323  if ((stmt->objtype == OBJECT_TABLE &&
13324  relForm->relkind != RELKIND_RELATION &&
13325  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
13326  (stmt->objtype == OBJECT_INDEX &&
13327  relForm->relkind != RELKIND_INDEX &&
13328  relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
13329  (stmt->objtype == OBJECT_MATVIEW &&
13330  relForm->relkind != RELKIND_MATVIEW))
13331  continue;
13332 
13333  /* Check if we are only moving objects owned by certain roles */
13334  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
13335  continue;
13336 
13337  /*
13338  * Handle permissions-checking here since we are locking the tables
13339  * and also to avoid doing a bunch of work only to fail part-way. Note
13340  * that permissions will also be checked by AlterTableInternal().
13341  *
13342  * Caller must be considered an owner on the table to move it.
13343  */
13344  if (!pg_class_ownercheck(relOid, GetUserId()))
13346  NameStr(relForm->relname));
13347 
13348  if (stmt->nowait &&
13350  ereport(ERROR,
13351  (errcode(ERRCODE_OBJECT_IN_USE),
13352  errmsg("aborting because lock on relation \"%s.%s\" is not available",
13353  get_namespace_name(relForm->relnamespace),
13354  NameStr(relForm->relname))));
13355  else
13357 
13358  /* Add to our list of objects to move */
13359  relations = lappend_oid(relations, relOid);
13360  }
13361 
13362  table_endscan(scan);
13364 
13365  if (relations == NIL)
13366  ereport(NOTICE,
13367  (errcode(ERRCODE_NO_DATA_FOUND),
13368  errmsg("no matching relations in tablespace \"%s\" found",
13369  orig_tablespaceoid == InvalidOid ? "(database default)" :
13370  get_tablespace_name(orig_tablespaceoid))));
13371 
13372  /* Everything is locked, loop through and move all of the relations. */
13373  foreach(l, relations)
13374  {
13375  List *cmds = NIL;
13377 
13378  cmd->subtype = AT_SetTableSpace;
13379  cmd->name = stmt->new_tablespacename;
13380 
13381  cmds = lappend(cmds, cmd);
13382 
13384  /* OID is set by AlterTableInternal */
13385  AlterTableInternal(lfirst_oid(l), cmds, false);
13387  }
13388 
13389  return new_tablespaceoid;
13390 }
#define NIL
Definition: pg_list.h:65
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:151
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1421
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4637
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:98
Oid GetUserId(void)
Definition: miscinit.c:448
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1915
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:529
int errcode(int sqlerrcode)
Definition: elog.c:610
AlterTableType subtype
Definition: parsenodes.h:1863
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:195
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
#define OidIsValid(objectId)
Definition: c.h:644
Oid MyDatabaseTableSpace
Definition: globals.c:87
void EventTriggerAlterTableStart(Node *parsetree)
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:84
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1275
List * lappend(List *list, void *datum)
Definition: list.c:321
AclResult
Definition: acl.h:177
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define NOTICE
Definition: elog.h:37
#define makeNode(_type_)
Definition: nodes.h:577
List * roleSpecsToIds(List *memberNames)
Definition: user.c:1434
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:674
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4687
bool IsCatalogNamespace(Oid namespaceId)
Definition: catalog.c:177
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:862
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:3646
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:824
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1467
ObjectType get_relkind_objtype(char relkind)
#define NameStr(name)
Definition: c.h:615
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
bool isAnyTempNamespace(Oid namespaceId)
Definition: namespace.c:3195
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:108
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define lfirst_oid(lc)
Definition: pg_list.h:192
void EventTriggerAlterTableEnd(void)

◆ AlterTableNamespace()

ObjectAddress AlterTableNamespace ( AlterObjectSchemaStmt stmt,
Oid oldschema 
)

Definition at line 14927 of file tablecmds.c.

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

Referenced by ExecAlterObjectSchemaStmt().

14928 {
14929  Relation rel;
14930  Oid relid;
14931  Oid oldNspOid;
14932  Oid nspOid;
14933  RangeVar *newrv;
14934  ObjectAddresses *objsMoved;
14935  ObjectAddress myself;
14936 
14938  stmt->missing_ok ? RVR_MISSING_OK : 0,
14940  (void *) stmt);
14941 
14942  if (!OidIsValid(relid))
14943  {
14944  ereport(NOTICE,
14945  (errmsg("relation \"%s\" does not exist, skipping",
14946  stmt->relation->relname)));
14947  return InvalidObjectAddress;
14948  }
14949 
14950  rel = relation_open(relid, NoLock);
14951 
14952  oldNspOid = RelationGetNamespace(rel);
14953 
14954  /* If it's an owned sequence, disallow moving it by itself. */
14955  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
14956  {
14957  Oid tableId;
14958  int32 colId;
14959 
14960  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
14961  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
14962  ereport(ERROR,
14963  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14964  errmsg("cannot move an owned sequence into another schema"),
14965  errdetail("Sequence \"%s\" is linked to table \"%s\".",
14967  get_rel_name(tableId))));
14968  }
14969 
14970  /* Get and lock schema OID and check its permissions. */
14971  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
14972  nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
14973 
14974  /* common checks on switching namespaces */
14975  CheckSetNamespace(oldNspOid, nspOid);
14976 
14977  objsMoved = new_object_addresses();
14978  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
14979  free_object_addresses(objsMoved);
14980 
14981  ObjectAddressSet(myself, RelationRelationId, relid);
14982 
14983  if (oldschema)
14984  *oldschema = oldNspOid;
14985 
14986  /* close rel, but keep lock until commit */
14987  relation_close(rel, NoLock);
14988 
14989  return myself;
14990 }
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition: pg_depend.c:755
int errcode(int sqlerrcode)
Definition: elog.c:610
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2410
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2705
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:644
signed int int32
Definition: c.h:355
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
void AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:14998
#define NoLock
Definition: lockdefs.h:34
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:15551
int errdetail(const char *fmt,...)
Definition: elog.c:957
#define RelationGetRelationName(relation)
Definition: rel.h:490
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:236
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition: namespace.c:2967
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:534
#define ereport(elevel,...)
Definition: elog.h:144
#define NOTICE
Definition: elog.h:37
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define AccessExclusiveLock
Definition: lockdefs.h:45
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:824
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1840
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
#define RelationGetNamespace(relation)
Definition: rel.h:497

◆ AlterTableNamespaceInternal()

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

Definition at line 14998 of file tablecmds.c.

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

15000 {
15001  Relation classRel;
15002 
15003  Assert(objsMoved != NULL);
15004 
15005  /* OK, modify the pg_class row and pg_depend entry */
15006  classRel = table_open(RelationRelationId, RowExclusiveLock);
15007 
15008  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
15009  nspOid, true, objsMoved);
15010 
15011  /* Fix the table's row type too, if it has one */
15012  if (OidIsValid(rel->rd_rel->reltype))
15013  AlterTypeNamespaceInternal(rel->rd_rel->reltype,
15014  nspOid, false, false, objsMoved);
15015 
15016  /* Fix other dependent stuff */
15017  if (rel->rd_rel->relkind == RELKIND_RELATION ||
15018  rel->rd_rel->relkind == RELKIND_MATVIEW ||
15019  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
15020  {
15021  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
15022  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
15023  objsMoved, AccessExclusiveLock);
15024  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
15025  false, objsMoved);
15026  }
15027 
15028  table_close(classRel, RowExclusiveLock);
15029 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:3510
Form_pg_class rd_rel
Definition: rel.h:109
#define OidIsValid(objectId)
Definition: c.h:644
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:15107
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:15152
#define RowExclusiveLock
Definition: lockdefs.h:38
#define Assert(condition)
Definition: c.h:738
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:15037
#define AccessExclusiveLock
Definition: lockdefs.h:45
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:456

◆ ATAddCheckConstraint()

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

Definition at line 8051 of file tablecmds.c.

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

Referenced by ATExecAddConstraint().

8054 {
8055  List *newcons;
8056  ListCell *lcon;
8057  List *children;
8058  ListCell *child;
8060 
8061  /* At top level, permission check was done in ATPrepCmd, else do it */
8062  if (recursing)
8064 
8065  /*
8066  * Call AddRelationNewConstraints to do the work, making sure it works on
8067  * a copy of the Constraint so transformExpr can't modify the original. It
8068  * returns a list of cooked constraints.
8069  *
8070  * If the constraint ends up getting merged with a pre-existing one, it's
8071  * omitted from the returned list, which is what we want: we do not need
8072  * to do any validation work. That can only happen at child tables,
8073  * though, since we disallow merging at the top level.
8074  */
8075  newcons = AddRelationNewConstraints(rel, NIL,
8076  list_make1(copyObject(constr)),
8077  recursing | is_readd, /* allow_merge */
8078  !recursing, /* is_local */
8079  is_readd, /* is_internal */
8080  NULL); /* queryString not available
8081  * here */
8082 
8083  /* we don't expect more than one constraint here */
8084  Assert(list_length(newcons) <= 1);
8085 
8086  /* Add each to-be-validated constraint to Phase 3's queue */
8087  foreach(lcon, newcons)
8088  {
8089  CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
8090 
8091  if (!ccon->skip_validation)
8092  {
8093  NewConstraint *newcon;
8094 
8095  newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
8096  newcon->name = ccon->name;
8097  newcon->contype = ccon->contype;
8098  newcon->qual = ccon->expr;
8099 
8100  tab->constraints = lappend(tab->constraints, newcon);
8101  }
8102 
8103  /* Save the actually assigned name if it was defaulted */
8104  if (constr->conname == NULL)
8105  constr->conname = ccon->name;
8106 
8107  ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
8108  }
8109 
8110  /* At this point we must have a locked-down name to use */
8111  Assert(constr->conname != NULL);
8112 
8113  /* Advance command counter in case same table is visited multiple times */
8115 
8116  /*
8117  * If the constraint got merged with an existing constraint, we're done.
8118  * We mustn't recurse to child tables in this case, because they've
8119  * already got the constraint, and visiting them again would lead to an
8120  * incorrect value for coninhcount.
8121  */
8122  if (newcons == NIL)
8123  return address;
8124 
8125  /*
8126  * If adding a NO INHERIT constraint, no need to find our children.
8127  */
8128  if (constr->is_no_inherit)
8129  return address;
8130 
8131  /*
8132  * Propagate to children as appropriate. Unlike most other ALTER
8133  * routines, we have to do this one level of recursion at a time; we can't
8134  * use find_all_inheritors to do it in one pass.
8135  */
8136  children = find_inheritance_children(RelationGetRelid(rel), lockmode);
8137 
8138  /*
8139  * Check if ONLY was specified with ALTER TABLE. If so, allow the
8140  * constraint creation only if there are no children currently. Error out
8141  * otherwise.
8142  */
8143  if (!recurse && children != NIL)
8144  ereport(ERROR,
8145  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8146  errmsg("constraint must be added to child tables too")));
8147 
8148  foreach(child, children)
8149  {
8150  Oid childrelid = lfirst_oid(child);
8151  Relation childrel;
8152  AlteredTableInfo *childtab;
8153 
8154  /* find_inheritance_children already got lock */
8155  childrel = table_open(childrelid, NoLock);
8156  CheckTableNotInUse(childrel, "ALTER TABLE");
8157 
8158  /* Find or create work queue entry for this table */
8159  childtab = ATGetQueueEntry(wqueue, childrel);
8160 
8161  /* Recurse to child */
8162  ATAddCheckConstraint(wqueue, childtab, childrel,
8163  constr, recurse, true, is_readd, lockmode);
8164 
8165  table_close(childrel, NoLock);
8166  }
8167 
8168  return address;
8169 }
#define NIL
Definition: pg_list.h:65
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal, const char *queryString)
Definition: heap.c:2520
char * name
Definition: tablecmds.c:187
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Node * qual
Definition: tablecmds.c:192
int errcode(int sqlerrcode)
Definition: elog.c:610
static ObjectAddress ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *constr, bool recurse, bool recursing, bool is_readd, LOCKMODE lockmode)
Definition: tablecmds.c:8051
char * conname
Definition: parsenodes.h:2155
unsigned int Oid
Definition: postgres_ext.h:31
#define ATT_TABLE
Definition: tablecmds.c:292
List * constraints
Definition: tablecmds.c:163
#define list_make1(x1)
Definition: pg_list.h:227
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
static AlteredTableInfo * ATGetQueueEntry(List **wqueue, Relation rel)
Definition: tablecmds.c:5439
bool skip_validation
Definition: heap.h:42
ConstrType contype
Definition: heap.h:37
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3533
List * lappend(List *list, void *datum)
Definition: list.c:321
ConstrType contype
Definition: tablecmds.c:188
void * palloc0(Size size)
Definition: mcxt.c:980
void CommandCounterIncrement(void)
Definition: xact.c:1006
bool is_no_inherit
Definition: parsenodes.h:2161
List * find_inheritance_children(Oid parentrelId, LOCKMODE lockmode)
Definition: pg_inherits.c:55
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:738
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:824
Oid conoid
Definition: heap.h:38
Node * expr
Definition: heap.h:41
static void ATSimplePermissions(Relation rel, int allowed_targets)
Definition: tablecmds.c:5476
#define copyObject(obj)
Definition: nodes.h:645
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define ATT_FOREIGN_TABLE
Definition: tablecmds.c:297
char * name
Definition: heap.h:39
#define RelationGetRelid(relation)
Definition: rel.h:456
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ ATAddForeignKeyConstraint()

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

Definition at line 8187 of file tablecmds.c.

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

Referenced by ATExecAddConstraint().

8190 {
8191  Relation pkrel;
8192  int16 pkattnum[INDEX_MAX_KEYS];
8193  int16 fkattnum[INDEX_MAX_KEYS];
8194  Oid pktypoid[INDEX_MAX_KEYS];
8195  Oid fktypoid[INDEX_MAX_KEYS];
8196  Oid opclasses[INDEX_MAX_KEYS];
8197  Oid pfeqoperators[INDEX_MAX_KEYS];
8198  Oid ppeqoperators[INDEX_MAX_KEYS];
8199  Oid ffeqoperators[INDEX_MAX_KEYS];
8200  int i;
8201  int numfks,
8202  numpks;
8203  Oid indexOid;
8204  bool old_check_ok;
8205  ObjectAddress address;
8206  ListCell *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
8207 
8208  /*
8209  * Grab ShareRowExclusiveLock on the pk table, so that someone doesn't
8210  * delete rows out from under us.
8211  */
8212  if (OidIsValid(fkconstraint->old_pktable_oid))
8213  pkrel = table_open(fkconstraint->old_pktable_oid, ShareRowExclusiveLock);
8214  else
8215  pkrel = table_openrv(fkconstraint->pktable, ShareRowExclusiveLock);
8216 
8217  /*
8218  * Validity checks (permission checks wait till we have the column
8219  * numbers)
8220  */
8221  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
8222  {
8223  if (!recurse)
8224  ereport(ERROR,
8225  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8226  errmsg("cannot use ONLY for foreign key on partitioned table \"%s\" referencing relation \"%s\"",
8228  RelationGetRelationName(pkrel))));
8229  if (fkconstraint->skip_validation && !fkconstraint->initially_valid)
8230  ereport(ERROR,
8231  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8232  errmsg("cannot add NOT VALID foreign key on partitioned table \"%s\" referencing relation \"%s\"",
8234  RelationGetRelationName(pkrel)),
8235  errdetail("This feature is not yet supported on partitioned tables.")));
8236  }
8237 
8238  if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
8239  pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
8240  ereport(ERROR,
8241  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8242  errmsg("referenced relation \"%s\" is not a table",
8243  RelationGetRelationName(pkrel))));
8244 
8245  if (!allowSystemTableMods && IsSystemRelation(pkrel))
8246  ereport(ERROR,
8247  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
8248  errmsg("permission denied: \"%s\" is a system catalog",
8249  RelationGetRelationName(pkrel))));
8250 
8251  /*
8252  * References from permanent or unlogged tables to temp tables, and from
8253  * permanent tables to unlogged tables, are disallowed because the
8254  * referenced data can vanish out from under us. References from temp
8255  * tables to any other table type are also disallowed, because other
8256  * backends might need to run the RI triggers on the perm table, but they
8257  * can't reliably see tuples in the local buffers of other backends.
8258  */
8259  switch (rel->rd_rel->relpersistence)
8260  {
8261  case RELPERSISTENCE_PERMANENT:
8262  if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT)
8263  ereport(ERROR,
8264  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8265  errmsg("constraints on permanent tables may reference only permanent tables")));
8266  break;
8267  case RELPERSISTENCE_UNLOGGED:
8268  if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT
8269  && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
8270  ereport(ERROR,
8271  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8272  errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
8273  break;
8274  case RELPERSISTENCE_TEMP:
8275  if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
8276  ereport(ERROR,
8277  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8278  errmsg("constraints on temporary tables may reference only temporary tables")));
8279  if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
8280  ereport(ERROR,
8281  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8282  errmsg("constraints on temporary tables must involve temporary tables of this session")));
8283  break;
8284  }
8285 
8286  /*
8287  * Look up the referencing attributes to make sure they exist, and record
8288  * their attnums and type OIDs.
8289  */
8290  MemSet(pkattnum, 0, sizeof(pkattnum));
8291  MemSet(fkattnum, 0, sizeof(fkattnum));
8292  MemSet(pktypoid, 0, sizeof(pktypoid));
8293  MemSet(fktypoid, 0, sizeof(fktypoid));
8294  MemSet(opclasses, 0, sizeof(opclasses));
8295  MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
8296  MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
8297  MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
8298 
8300  fkconstraint->fk_attrs,
8301  fkattnum, fktypoid);
8302 
8303  /*
8304  * If the attribute list for the referenced table was omitted, lookup the
8305  * definition of the primary key and use it. Otherwise, validate the
8306  * supplied attribute list. In either case, discover the index OID and
8307  * index opclasses, and the attnums and type OIDs of the attributes.
8308  */
8309  if (fkconstraint->pk_attrs == NIL)
8310  {
8311  numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
8312  &fkconstraint->pk_attrs,
8313  pkattnum, pktypoid,
8314  opclasses);
8315  }
8316  else
8317  {
8318  numpks = transformColumnNameList(RelationGetRelid(pkrel),
8319  fkconstraint->pk_attrs,
8320  pkattnum, pktypoid);
8321  /* Look for an index matching the column list */
8322  indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
8323  opclasses);
8324  }
8325 
8326  /*
8327  * Now we can check permissions.
8328  */
8329  checkFkeyPermissions(pkrel, pkattnum, numpks);
8330 
8331  /*
8332  * Check some things for generated columns.
8333  */
8334  for (i = 0; i < numfks; i++)
8335  {
8336  char attgenerated = TupleDescAttr(RelationGetDescr(rel), fkattnum[i] - 1)->attgenerated;
8337 
8338  if (attgenerated)
8339  {
8340  /*
8341  * Check restrictions on UPDATE/DELETE actions, per SQL standard
8342  */
8343  if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
8344  fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT ||
8345  fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE)
8346  ereport(ERROR,
8347  (errcode(ERRCODE_SYNTAX_ERROR),
8348  errmsg("invalid %s action for foreign key constraint containing generated column",
8349  "ON UPDATE")));
8350  if (fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
8351  fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
8352  ereport(ERROR,
8353  (errcode(ERRCODE_SYNTAX_ERROR),
8354  errmsg("invalid %s action for foreign key constraint containing generated column",
8355  "ON DELETE")));
8356  }
8357  }
8358 
8359  /*
8360  * Look up the equality operators to use in the constraint.
8361  *
8362  * Note that we have to be careful about the difference between the actual
8363  * PK column type and the opclass' declared input type, which might be
8364  * only binary-compatible with it. The declared opcintype is the right
8365  * thing to probe pg_amop with.
8366  */
8367  if (numfks != numpks)
8368  ereport(ERROR,
8369  (errcode(ERRCODE_INVALID_FOREIGN_KEY),
8370  errmsg("number of referencing and referenced columns for foreign key disagree")));
8371 
8372  /*
8373  * On the strength of a previous constraint, we might avoid scanning
8374  * tables to validate this one. See below.
8375  */
8376  old_check_ok = (fkconstraint->old_conpfeqop != NIL);
8377  Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
8378 
8379  for (i = 0; i < numpks; i++)
8380  {
8381  Oid pktype = pktypoid[i];
8382  Oid fktype = fktypoid[i];
8383  Oid fktyped;
8384  HeapTuple cla_ht;
8385  Form_pg_opclass cla_tup;
8386  Oid amid;
8387  Oid opfamily;
8388  Oid opcintype;
8389  Oid pfeqop;
8390  Oid ppeqop;
8391  Oid ffeqop;
8392  int16 eqstrategy;
8393  Oid pfeqop_right;
8394 
8395  /* We need several fields out of the pg_opclass entry */
8396  cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
8397  if (!HeapTupleIsValid(cla_ht))
8398  elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
8399  cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
8400  amid = cla_tup->opcmethod;
8401  opfamily = cla_tup->opcfamily;
8402  opcintype = cla_tup->opcintype;
8403  ReleaseSysCache(cla_ht);
8404 
8405  /*
8406  * Check it's a btree; currently this can never fail since no other
8407  * index AMs support unique indexes. If we ever did have other types
8408  * of unique indexes, we'd need a way to determine which operator
8409  * strategy number is equality. (Is it reasonable to insist that
8410  * every such index AM use btree's number for equality?)
8411  */
8412  if (amid != BTREE_AM_OID)
8413  elog(ERROR, "only b-tree indexes are supported for foreign keys");
8414  eqstrategy = BTEqualStrategyNumber;
8415 
8416  /*
8417  * There had better be a primary equality operator for the index.
8418  * We'll use it for PK = PK comparisons.
8419  */
8420  ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
8421  eqstrategy);
8422 
8423  if (!OidIsValid(ppeqop))
8424  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
8425  eqstrategy, opcintype, opcintype, opfamily);
8426 
8427  /*
8428  * Are there equality operators that take exactly the FK type? Assume
8429  * we should look through any domain here.
8430  */
8431  fktyped = getBaseType(fktype);
8432 
8433  pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
8434  eqstrategy);
8435  if (OidIsValid(pfeqop))
8436  {
8437  pfeqop_right = fktyped;
8438  ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
8439  eqstrategy);
8440  }
8441  else
8442  {
8443  /* keep compiler quiet */
8444  pfeqop_right = InvalidOid;
8445  ffeqop = InvalidOid;
8446  }
8447 
8448  if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
8449  {
8450  /*
8451  * Otherwise, look for an implicit cast from the FK type to the
8452  * opcintype, and if found, use the primary equality operator.
8453  * This is a bit tricky because opcintype might be a polymorphic
8454  * type such as ANYARRAY or ANYENUM; so what we have to test is
8455  * whether the two actual column types can be concurrently cast to
8456  * that type. (Otherwise, we'd fail to reject combinations such
8457  * as int[] and point[].)
8458  */
8459  Oid input_typeids[2];
8460  Oid target_typeids[2];
8461 
8462  input_typeids[0] = pktype;
8463  input_typeids[1] = fktype;
8464  target_typeids[0] = opcintype;
8465  target_typeids[1] = opcintype;
8466  if (can_coerce_type(2, input_typeids, target_typeids,
8468  {
8469  pfeqop = ffeqop = ppeqop;
8470  pfeqop_right = opcintype;
8471  }
8472  }
8473 
8474  if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
8475  ereport(ERROR,
8476  (errcode(ERRCODE_DATATYPE_MISMATCH),
8477  errmsg("foreign key constraint \"%s\" cannot be implemented",
8478  fkconstraint->conname),
8479  errdetail("Key columns \"%s\" and \"%s\" "
8480  "are of incompatible types: %s and %s.",
8481  strVal(list_nth(fkconstraint->fk_attrs, i)),
8482  strVal(list_nth(fkconstraint->pk_attrs, i)),
8483  format_type_be(fktype),
8484  format_type_be(pktype))));
8485 
8486  if (old_check_ok)
8487  {
8488  /*
8489  * When a pfeqop changes, revalidate the constraint. We could
8490  * permit intra-opfamily changes, but that adds subtle complexity
8491  * without any concrete benefit for core types. We need not
8492  * assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
8493  */
8494  old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
8495  old_pfeqop_item = lnext(fkconstraint->old_conpfeqop,
8496  old_pfeqop_item);
8497  }
8498  if (old_check_ok)
8499  {
8500  Oid old_fktype;
8501  Oid new_fktype;
8502  CoercionPathType old_pathtype;
8503  CoercionPathType new_pathtype;
8504  Oid old_castfunc;
8505  Oid new_castfunc;
8507  fkattnum[i] - 1);
8508 
8509  /*
8510  * Identify coercion pathways from each of the old and new FK-side
8511  * column types to the right (foreign) operand type of the pfeqop.
8512  * We may assume that pg_constraint.conkey is not changing.
8513  */
8514  old_fktype = attr->atttypid;
8515  new_fktype = fktype;
8516  old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
8517  &old_castfunc);
8518  new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
8519  &new_castfunc);
8520 
8521  /*
8522  * Upon a change to the cast from the FK column to its pfeqop
8523  * operand, revalidate the constraint. For this evaluation, a
8524  * binary coercion cast is equivalent to no cast at all. While
8525  * type implementors should design implicit casts with an eye
8526  * toward consistency of operations like equality, we cannot
8527  * assume here that they have done so.
8528  *
8529  * A function with a polymorphic argument could change behavior
8530  * arbitrarily in response to get_fn_expr_argtype(). Therefore,
8531  * when the cast destination is polymorphic, we only avoid
8532  * revalidation if the input type has not changed at all. Given
8533  * just the core data types and operator classes, this requirement
8534  * prevents no would-be optimizations.
8535  *
8536  * If the cast converts from a base type to a domain thereon, then
8537  * that domain type must be the opcintype of the unique index.
8538  * Necessarily, the primary key column must then be of the domain
8539  * type. Since the constraint was previously valid, all values on
8540  * the foreign side necessarily exist on the primary side and in
8541  * turn conform to the domain. Consequently, we need not treat
8542  * domains specially here.
8543  *
8544  * Since we require that all collations share the same notion of
8545  * equality (which they do, because texteq reduces to bitwise
8546  * equality), we don't compare collation here.
8547  *
8548  * We need not directly consider the PK type. It's necessarily
8549  * binary coercible to the opcintype of the unique index column,
8550  * and ri_triggers.c will only deal with PK datums in terms of
8551  * that opcintype. Changing the opcintype also changes pfeqop.
8552  */
8553  old_check_ok = (new_pathtype == old_pathtype &&
8554  new_castfunc == old_castfunc &&
8555  (!IsPolymorphicType(pfeqop_right) ||
8556  new_fktype == old_fktype));
8557  }
8558 
8559  pfeqoperators[i] = pfeqop;
8560  ppeqoperators[i] = ppeqop;
8561  ffeqoperators[i] = ffeqop;
8562  }
8563 
8564  /*
8565  * Create all the constraint and trigger objects, recursing to partitions
8566  * as necessary. First handle the referenced side.
8567  */
8568  address = addFkRecurseReferenced(wqueue, fkconstraint, rel, pkrel,
8569  indexOid,
8570  InvalidOid, /* no parent constraint */
8571  numfks,
8572  pkattnum,
8573  fkattnum,
8574  pfeqoperators,
8575  ppeqoperators,
8576  ffeqoperators,
8577  old_check_ok);
8578 
8579  /* Now handle the referencing side. */
8580  addFkRecurseReferencing(wqueue, fkconstraint, rel, pkrel,
8581  indexOid,
8582  address.objectId,
8583  numfks,
8584  pkattnum,
8585  fkattnum,
8586  pfeqoperators,
8587  ppeqoperators,
8588  ffeqoperators,
8589  old_check_ok,
8590  lockmode);
8591 
8592  /*
8593  * Done. Close pk table, but keep lock until we've committed.
8594  */
8595  table_close(pkrel, NoLock);
8596 
8597  return address;
8598 }
signed short int16
Definition: c.h:354
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
List * old_conpfeqop
Definition: parsenodes.h:2192
bool IsSystemRelation(Relation relation)
Definition: catalog.c:68
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
#define RelationGetDescr(relation)
Definition: rel.h:482
static void addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint, Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr, int numfks, int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators, bool old_check_ok, LOCKMODE lockmode)
Definition: tablecmds.c:8831
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:546
#define FKCONSTR_ACTION_SETDEFAULT
Definition: parsenodes.h:2142
static int transformColumnNameList(Oid relId, List *colList, int16 *attnums, Oid *atttypids)
Definition: tablecmds.c:9892
bool rd_islocaltemp
Definition: rel.h:60
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:610
#define MemSet(start, val, len)
Definition: c.h:971
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
List * pk_attrs
Definition: parsenodes.h:2188
char * conname
Definition: parsenodes.h:2155
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
Definition: tablecmds.c:10204
#define OidIsValid(objectId)
Definition: c.h:644
CoercionPathType
Definition: parse_coerce.h:24
static ObjectAddress addFkRecurseReferenced(List **wqueue, Constraint *fkconstraint, Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr, int numfks, int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators, bool old_check_ok)
Definition: tablecmds.c:8626
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
static void * list_nth(const List *list, int n)
Definition: pg_list.h:277
TupleDesc oldDesc
Definition: tablecmds.c:159
#define NoLock
Definition: lockdefs.h:34
int errdetail(const char *fmt,...)
Definition: elog.c:957
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
#define RelationGetRelationName(relation)
Definition: rel.h:490
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
Oid old_pktable_oid
Definition: parsenodes.h:2193
#define FKCONSTR_ACTION_CASCADE
Definition: parsenodes.h:2140
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:68
bool allowSystemTableMods
Definition: globals.c:120
#define InvalidOid
Definition: postgres_ext.h:36
bool initially_valid
Definition: parsenodes.h:2198
#define ereport(elevel,...)
Definition: elog.h:144
static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid, List **attnamelist, int16 *attnums, Oid *atttypids, Oid *opclasses)
Definition: tablecmds.c:9937
char fk_del_action
Definition: parsenodes.h:2191
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:738
#define ShareRowExclusiveLock
Definition: lockdefs.h:42
static CoercionPathType findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
Definition: tablecmds.c:10175
#define INDEX_MAX_KEYS
static int list_length(const List *l)
Definition: pg_list.h:169
static Oid transformFkeyCheckAttrs(Relation pkrel, int numattrs, int16 *attnums, Oid *opclasses)
Definition: tablecmds.c:10034
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
int i
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
RangeVar * pktable
Definition: parsenodes.h:2186
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2409
#define FKCONSTR_ACTION_SETNULL
Definition: parsenodes.h:2141
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
bool skip_validation
Definition: parsenodes.h:2197
#define RelationGetRelid(relation)
Definition: rel.h:456
List * fk_attrs
Definition: parsenodes.h:2187
#define BTEqualStrategyNumber
Definition: stratnum.h:31
char fk_upd_action
Definition: parsenodes.h:2190
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ ATCheckPartitionsNotInUse()

static void ATCheckPartitionsNotInUse ( Relation  rel,
LOCKMODE  lockmode 
)
static

Definition at line 5643 of file tablecmds.c.

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

Referenced by ATPrepCmd().

5644 {
5645  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
5646  {
5647  List *inh;
5648  ListCell *cell;
5649 
5650  inh = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
5651  /* first element is the parent rel; must ignore it */
5652  for_each_cell(cell, inh, list_second_cell(inh))
5653  {
5654  Relation childrel;
5655 
5656  /* find_all_inheritors already got lock */
5657  childrel = table_open(lfirst_oid(cell), NoLock);
5658  CheckTableNotInUse(childrel, "ALTER TABLE");
5659  table_close(childrel, NoLock);
5660  }
5661  list_free(inh);
5662  }
5663 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:390
Form_pg_class rd_rel
Definition: rel.h:109
#define NoLock
Definition: lockdefs.h:34
static ListCell * list_second_cell(const List *l)
Definition: pg_list.h:139
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3533
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:165
void list_free(List *list)
Definition: list.c:1376
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:456
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ ATColumnChangeRequiresRewrite()

static bool ATColumnChangeRequiresRewrite ( Node expr,
AttrNumber  varattno 
)
static

Definition at line 11130 of file tablecmds.c.

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

Referenced by ATPrepAlterColumnType().

11131 {
11132  Assert(expr != NULL);
11133 
11134  for (;;)
11135  {
11136  /* only one varno, so no need to check that */
11137  if (IsA(expr, Var) && ((Var *) expr)->varattno == varattno)
11138  return false;
11139  else if (IsA(expr, RelabelType))
11140  expr = (Node *) ((RelabelType *) expr)->arg;
11141  else if (IsA(expr, CoerceToDomain))
11142  {
11143  CoerceToDomain *d = (CoerceToDomain *) expr;
11144 
11146  return true;
11147  expr = (Node *) d->arg;
11148  }
11149  else if (IsA(expr, FuncExpr))
11150  {
11151  FuncExpr *f = (FuncExpr *) expr;
11152 
11153  switch (f->funcid)
11154  {
11155  case F_TIMESTAMPTZ_TIMESTAMP:
11156  case F_TIMESTAMP_TIMESTAMPTZ:
11158  return true;
11159  else
11160  expr = linitial(f->args);
11161  break;
11162  default:
11163  return true;
11164  }
11165  }
11166  else
11167  return true;
11168  }
11169 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
List * args
Definition: primnodes.h:477
Definition: nodes.h:529
Definition: primnodes.h:181
bool DomainHasConstraints(Oid type_id)
Definition: typcache.c:1347
#define linitial(l)
Definition: pg_list.h:195
Oid funcid
Definition: primnodes.h:469
#define Assert(condition)
Definition: c.h:738
void * arg
bool TimestampTimestampTzRequiresRewrite(void)
Definition: timestamp.c:5154

◆ ATController()

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

Definition at line 3952 of file tablecmds.c.

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

Referenced by AlterTable(), and AlterTableInternal().

3955 {
3956  List *wqueue = NIL;
3957  ListCell *lcmd;
3958 
3959  /* Phase 1: preliminary examination of commands, create work queue */
3960  foreach(lcmd, cmds)
3961  {
3962  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3963 
3964  ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode, context);
3965  }
3966 
3967  /* Close the relation, but keep lock until commit */
3968  relation_close(rel, NoLock);
3969 
3970  /* Phase 2: update system catalogs */
3971  ATRewriteCatalogs(&wqueue, lockmode, context);
3972 
3973  /* Phase 3: scan/rewrite tables as needed, and run afterStmts */
3974  ATRewriteTables(parsetree, &wqueue, lockmode, context);
3975 }
#define NIL
Definition: pg_list.h:65
static void ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:4817
#define NoLock
Definition: lockdefs.h:34
static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:3987
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define lfirst(lc)
Definition: pg_list.h:190
static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:4309
Definition: pg_list.h:50

◆ ATDetachCheckNoForeignKeyRefs()

static void ATDetachCheckNoForeignKeyRefs ( Relation  partition)
static

Definition at line 17435 of file tablecmds.c.

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

Referenced by ATExecDetachPartition().

17436 {
17437  List *constraints;
17438  ListCell *cell;
17439 
17440  constraints = GetParentedForeignKeyRefs(partition);
17441 
17442  foreach(cell, constraints)
17443  {
17444  Oid constrOid = lfirst_oid(cell);
17445  HeapTuple tuple;
17446  Form_pg_constraint constrForm;
17447  Relation rel;
17448  Trigger trig;
17449 
17450  tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
17451  if (!HeapTupleIsValid(tuple))
17452  elog(ERROR, "cache lookup failed for constraint %u", constrOid);
17453  constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
17454 
17455  Assert(OidIsValid(constrForm->conparentid));
17456  Assert(constrForm->confrelid == RelationGetRelid(partition));
17457 
17458  /* prevent data changes into the referencing table until commit */
17459  rel = table_open(constrForm->conrelid, ShareLock);
17460 
17461  MemSet(&trig, 0, sizeof(trig));
17462  trig.tgoid = InvalidOid;
17463  trig.tgname = NameStr(constrForm->conname);
17465  trig.tgisinternal = true;
17466  trig.tgconstrrelid = RelationGetRelid(partition);
17467  trig.tgconstrindid = constrForm->conindid;
17468  trig.tgconstraint = constrForm->oid;
17469  trig.tgdeferrable = false;
17470  trig.tginitdeferred = false;
17471  /* we needn't fill in remaining fields */
17472 
17473  RI_PartitionRemove_Check(&trig, rel, partition);
17474 
17475  ReleaseSysCache(tuple);
17476 
17477  table_close(rel, NoLock);
17478  }
17479 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
static List * GetParentedForeignKeyRefs(Relation partition)
Definition: tablecmds.c:17382
Oid tgoid
Definition: reltrigger.h:25
bool tgisinternal
Definition: reltrigger.h:31
#define MemSet(start, val, len)
Definition: c.h:971
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:644
#define TRIGGER_FIRES_ON_ORIGIN
Definition: trigger.h:156
char tgenabled
Definition: reltrigger.h:30
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Oid tgconstraint
Definition: reltrigger.h:35
char * tgname
Definition: reltrigger.h:27
void RI_PartitionRemove_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
Definition: ri_triggers.c:1570
bool tgdeferrable
Definition: reltrigger.h:36
bool tginitdeferred
Definition: reltrigger.h:37
#define NoLock
Definition: lockdefs.h:34
Oid tgconstrrelid
Definition: reltrigger.h:33
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define InvalidOid
Definition: postgres_ext.h:36
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:738
Oid tgconstrindid
Definition: reltrigger.h:34
#define elog(elevel,...)
Definition: elog.h:214
#define ShareLock
Definition: lockdefs.h:41
#define NameStr(name)
Definition: c.h:615
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:456
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ AtEOSubXact_on_commit_actions()

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

Definition at line 15428 of file tablecmds.c.

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

15430 {
15431  ListCell *cur_item;
15432 
15433  foreach(cur_item, on_commits)
15434  {
15435  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
15436 
15437  if (!isCommit && oc->creating_subid == mySubid)
15438  {
15439  /* cur_item must be removed */
15441  pfree(oc);
15442  }
15443  else
15444  {
15445  /* cur_item must be preserved */
15446  if (oc->creating_subid == mySubid)
15447  oc->creating_subid = parentSubid;
15448  if (oc->deleting_subid == mySubid)
15449  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
15450  }
15451  }
15452 }
SubTransactionId creating_subid
Definition: tablecmds.c:118
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:368
void pfree(void *pointer)
Definition: mcxt.c:1056
static List * on_commits
Definition: tablecmds.c:122
SubTransactionId deleting_subid
Definition: tablecmds.c:119
#define lfirst(lc)
Definition: pg_list.h:190
#define InvalidSubTransactionId
Definition: c.h:519

◆ AtEOXact_on_commit_actions()

void AtEOXact_on_commit_actions ( bool  isCommit)

Definition at line 15396 of file tablecmds.c.

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

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

15397 {
15398  ListCell *cur_item;
15399 
15400  foreach(cur_item, on_commits)
15401  {
15402  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
15403 
15404  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
15406  {
15407  /* cur_item must be removed */
15409  pfree(oc);
15410  }
15411  else
15412  {
15413  /* cur_item must be preserved */
15416  }
15417  }
15418 }
SubTransactionId creating_subid
Definition: tablecmds.c:118
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:368
void pfree(void *pointer)
Definition: mcxt.c:1056
static List * on_commits
Definition: tablecmds.c:122
SubTransactionId deleting_subid
Definition: tablecmds.c:119
#define lfirst(lc)
Definition: pg_list.h:190
#define InvalidSubTransactionId
Definition: c.h:519

◆ ATExecAddColumn()

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

Definition at line 5952 of file tablecmds.c.

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

Referenced by ATExecCmd().

5957 {
5958  Oid myrelid = RelationGetRelid(rel);
5959  ColumnDef *colDef = castNode(ColumnDef, (*cmd)->def);
5960  bool if_not_exists = (*cmd)->missing_ok;
5961  Relation pgclass,
5962  attrdesc;
5963  HeapTuple reltup;
5964  FormData_pg_attribute attribute;
5965  int newattnum;
5966  char relkind;
5967  HeapTuple typeTuple;
5968  Oid typeOid;
5969  int32 typmod;
5970  Oid collOid;
5971  Form_pg_type tform;
5972  Expr *defval;
5973  List *children;
5974  ListCell *child;
5975  AlterTableCmd *childcmd;
5976  AclResult aclresult;
5977  ObjectAddress address;
5978 
5979  /* At top level, permission check was done in ATPrepCmd, else do it */
5980  if (recursing)
5982 
5983  if (rel->rd_rel->relispartition && !recursing)
5984  ereport(ERROR,
5985  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5986  errmsg("cannot add column to a partition")));
5987 
5988  attrdesc = table_open(AttributeRelationId, RowExclusiveLock);
5989 
5990  /*
5991  * Are we adding the column to a recursion child? If so, check whether to
5992  * merge with an existing definition for the column. If we do merge, we
5993  * must not recurse. Children will already have the column, and recursing
5994  * into them would mess up attinhcount.
5995  */
5996  if (colDef->inhcount > 0)
5997  {
5998  HeapTuple tuple;
5999 
6000  /* Does child already have a column by this name? */
6001  tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
6002  if (HeapTupleIsValid(tuple))
6003  {
6004  Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
6005  Oid ctypeId;
6006  int32 ctypmod;
6007  Oid ccollid;
6008 
6009  /* Child column must match on type, typmod, and collation */
6010  typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
6011  if (ctypeId != childatt->atttypid ||
6012  ctypmod != childatt->atttypmod)
6013  ereport(ERROR,
6014  (errcode(ERRCODE_DATATYPE_MISMATCH),
6015  errmsg("child table \"%s\" has different type for column \"%s\"",
6016  RelationGetRelationName(rel), colDef->colname)));
6017  ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
6018  if (ccollid != childatt->attcollation)
6019  ereport(ERROR,
6020  (errcode(ERRCODE_COLLATION_MISMATCH),
6021  errmsg("child table \"%s\" has different collation for column \"%s\"",
6022  RelationGetRelationName(rel), colDef->colname),
6023  errdetail("\"%s\" versus \"%s\"",
6024  get_collation_name(ccollid),
6025  get_collation_name(childatt->attcollation))));
6026 
6027  /* Bump the existing child att's inhcount */
6028  childatt->attinhcount++;
6029  CatalogTupleUpdate(attrdesc, &tuple->t_self, tuple);
6030 
6031  heap_freetuple(tuple);
6032 
6033  /* Inform the user about the merge */
6034  ereport(NOTICE,
6035  (errmsg("merging definition of column \"%s\" for child \"%s\"",
6036  colDef->colname, RelationGetRelationName(rel))));
6037 
6038  table_close(attrdesc, RowExclusiveLock);
6039  return InvalidObjectAddress;
6040  }
6041  }
6042 
6043  /* skip if the name already exists and if_not_exists is true */
6044  if (!check_for_column_name_collision(rel, colDef->colname, if_not_exists))
6045  {
6046  table_close(attrdesc, RowExclusiveLock);
6047  return InvalidObjectAddress;
6048  }
6049 
6050  /*
6051  * Okay, we need to add the column, so go ahead and do parse
6052  * transformation. This can result in queueing up, or even immediately
6053  * executing, subsidiary operations (such as creation of unique indexes);
6054  * so we mustn't do it until we have made the if_not_exists check.
6055  *
6056  * When recursing, the command was already transformed and we needn't do
6057  * so again. Also, if context isn't given we can't transform. (That
6058  * currently happens only for AT_AddColumnToView; we expect that view.c
6059  * passed us a ColumnDef that doesn't need work.)
6060  */
6061  if (context != NULL && !recursing)
6062  {
6063  *cmd = ATParseTransformCmd(wqueue, tab, rel, *cmd, recurse, lockmode,
6064  cur_pass, context);
6065  Assert(*cmd != NULL);
6066  colDef = castNode(ColumnDef, (*cmd)->def);
6067  }
6068 
6069  /*
6070  * Cannot add identity column if table has children, because identity does
6071  * not inherit. (Adding column and identity separately will work.)
6072  */
6073  if (colDef->identity &&
6074  recurse &&
6075  find_inheritance_children(myrelid, NoLock) != NIL)
6076  ereport(ERROR,
6077  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6078  errmsg("cannot recursively add identity column to table that has child tables")));
6079 
6080  pgclass = table_open(RelationRelationId, RowExclusiveLock);
6081 
6082  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
6083  if (!HeapTupleIsValid(reltup))
6084  elog(ERROR, "cache lookup failed for relation %u", myrelid);
6085  relkind = ((Form_pg_class) GETSTRUCT(reltup))->relkind;
6086 
6087  /* Determine the new attribute's number */
6088  newattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts + 1;
6089  if (newattnum > MaxHeapAttributeNumber)
6090  ereport(ERROR,
6091  (errcode(ERRCODE_TOO_MANY_COLUMNS),
6092  errmsg("tables can have at most %d columns",
6094 
6095  typeTuple = typenameType(NULL, colDef->typeName, &typmod);
6096  tform = (Form_pg_type) GETSTRUCT(typeTuple);
6097  typeOid = tform->oid;
6098 
6099  aclresult = pg_type_aclcheck(typeOid, GetUserId(), ACL_USAGE);
6100  if (aclresult != ACLCHECK_OK)
6101  aclcheck_error_type(aclresult, typeOid);
6102 
6103  collOid = GetColumnDefCollation(NULL, colDef, typeOid);
6104 
6105  /* make sure datatype is legal for a column */
6106  CheckAttributeType(colDef->colname, typeOid, collOid,
6107  list_make1_oid(rel->rd_rel->reltype),
6108  0);
6109 
6110  /* construct new attribute's pg_attribute entry */
6111  attribute.attrelid = myrelid;
6112  namestrcpy(&(attribute.attname), colDef->colname);
6113  attribute.atttypid = typeOid;
6114  attribute.attstattarget = (newattnum > 0) ? -1 : 0;
6115  attribute.attlen = tform->typlen;
6116  attribute.atttypmod = typmod;
6117  attribute.attnum = newattnum;
6118  attribute.attbyval = tform->typbyval;
6119  attribute.attndims = list_length(colDef->typeName->arrayBounds);
6120  attribute.attstorage = tform->typstorage;
6121  attribute.attalign = tform->typalign;
6122  attribute.attnotnull = colDef->is_not_null;
6123  attribute.atthasdef = false;
6124  attribute.atthasmissing = false;
6125  attribute.attidentity = colDef->identity;
6126  attribute.attgenerated = colDef->generated;
6127  attribute.attisdropped = false;
6128  attribute.attislocal = colDef->is_local;
6129  attribute.attinhcount = colDef->inhcount;
6130  attribute.attcollation = collOid;
6131  /* attribute.attacl is handled by InsertPgAttributeTuple */
6132 
6133  ReleaseSysCache(typeTuple);
6134 
6135  InsertPgAttributeTuple(attrdesc, &attribute, (Datum) 0, NULL);
6136 
6137  table_close(attrdesc, RowExclusiveLock);
6138 
6139  /*
6140  * Update pg_class tuple as appropriate
6141  */
6142  ((Form_pg_class) GETSTRUCT(reltup))->relnatts = newattnum;
6143 
6144  CatalogTupleUpdate(pgclass, &reltup->t_self, reltup);
6145 
6146  heap_freetuple(reltup);
6147 
6148  /* Post creation hook for new attribute */
6149  InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
6150 
6151  table_close(pgclass, RowExclusiveLock);
6152 
6153  /* Make the attribute's catalog entry visible */
6155 
6156  /*
6157  * Store the DEFAULT, if any, in the catalogs
6158  */
6159  if (colDef->raw_default)
6160  {
6161  RawColumnDefault *rawEnt;
6162 
6163  rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
6164  rawEnt->attnum = attribute.attnum;
6165  rawEnt->raw_default = copyObject(colDef->raw_default);
6166 
6167  /*
6168  * Attempt to skip a complete table rewrite by storing the specified
6169  * DEFAULT value outside of the heap. This may be disabled inside
6170  * AddRelationNewConstraints if the optimization cannot be applied.
6171  */
6172  rawEnt->missingMode = (!colDef->generated);
6173 
6174  rawEnt->generated = colDef->generated;
6175 
6176  /*
6177  * This function is intended for CREATE TABLE, so it processes a
6178  * _list_ of defaults, but we just do one.
6179  */
6181  false, true, false, NULL);
6182 
6183  /* Make the additional catalog changes visible */
6185 
6186  /*
6187  * Did the request for a missing value work? If not we'll have to do a
6188  * rewrite
6189  */
6190  if (!rawEnt->missingMode)
6192  }
6193 
6194  /*
6195  * Tell Phase 3 to fill in the default expression, if there is one.
6196  *
6197  * If there is no default, Phase 3 doesn't have to do anything, because
6198  * that effectively means that the default is NULL. The heap tuple access
6199  * routines always check for attnum > # of attributes in tuple, and return
6200  * NULL if so, so without any modification of the tuple data we will get
6201  * the effect of NULL values in the new column.
6202  *
6203  * An exception occurs when the new column is of a domain type: the domain
6204  * might have a NOT NULL constraint, or a check constraint that indirectly
6205  * rejects nulls. If there are any domain constraints then we construct
6206  * an explicit NULL default value that will be passed through
6207  * CoerceToDomain processing. (This is a tad inefficient, since it causes
6208  * rewriting the table which we really don't have to do, but the present
6209  * design of domain processing doesn't offer any simple way of checking
6210  * the constraints more directly.)
6211  *
6212  * Note: we use build_column_default, and not just the cooked default
6213  * returned by AddRelationNewConstraints, so that the right thing happens
6214  * when a datatype's default applies.
6215  *
6216  * Note: it might seem that this should happen at the end of Phase 2, so
6217  * that the effects of subsequent subcommands can be taken into account.
6218  * It's intentional that we do it now, though. The new column should be
6219  * filled according to what is said in the ADD COLUMN subcommand, so that
6220  * the effects are the same as if this subcommand had been run by itself
6221  * and the later subcommands had been issued in new ALTER TABLE commands.
6222  *
6223  * We can skip this entirely for relations without storage, since Phase 3
6224  * is certainly not going to touch them. System attributes don't have
6225  * interesting defaults, either.
6226  */
6227  if (RELKIND_HAS_STORAGE(relkind) && attribute.attnum > 0)
6228  {
6229  /*
6230  * For an identity column, we can't use build_column_default(),
6231  * because the sequence ownership isn't set yet. So do it manually.
6232  */
6233  if (colDef->identity)
6234  {
6236 
6237  nve->seqid = RangeVarGetRelid(colDef->identitySequence, NoLock, false);
6238  nve->typeId = typeOid;
6239 
6240  defval = (Expr *) nve;
6241 
6242  /* must do a rewrite for identity columns */
6244  }
6245  else
6246  defval = (Expr *) build_column_default(rel, attribute.attnum);
6247 
6248  if (!defval && DomainHasConstraints(typeOid))
6249  {
6250  Oid baseTypeId;
6251  int32 baseTypeMod;
6252  Oid baseTypeColl;
6253 
6254  baseTypeMod = typmod;
6255  baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
6256  baseTypeColl = get_typcollation(baseTypeId);
6257  defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
6258  defval = (Expr *) coerce_to_target_type(NULL,
6259  (Node *) defval,
6260  baseTypeId,
6261  typeOid,
6262  typmod,
6265  -1);
6266  if (defval == NULL) /* should not happen */
6267  elog(ERROR, "failed to coerce base type to domain");
6268  }
6269 
6270  if (defval)
6271  {
6273 
6274  newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
6275  newval->attnum = attribute.attnum;
6276  newval->expr = expression_planner(defval);
6277  newval->is_generated = (colDef->generated != '\0');
6278 
6279  tab->newvals = lappend(tab->newvals, newval);
6280  }
6281 
6282  if (DomainHasConstraints(typeOid))
6284 
6285  if (!TupleDescAttr(rel->rd_att, attribute.attnum - 1)->atthasmissing)
6286  {
6287  /*
6288  * If the new column is NOT NULL, and there is no missing value,
6289  * tell Phase 3 it needs to check for NULLs.
6290  */
6291  tab->verify_new_notnull |= colDef->is_not_null;
6292  }
6293  }
6294 
6295  /*
6296  * Add needed dependency entries for the new column.
6297  */
6298  add_column_datatype_dependency(myrelid, newattnum, attribute.atttypid);
6299  add_column_collation_dependency(myrelid, newattnum, attribute.attcollation);
6300 
6301  /*
6302  * Propagate to children as appropriate. Unlike most other ALTER
6303  * routines, we have to do this one level of recursion at a time; we can't
6304  * use find_all_inheritors to do it in one pass.
6305  */
6306  children = find_inheritance_children(RelationGetRelid(rel), lockmode);
6307 
6308  /*
6309  * If we are told not to recurse, there had better not be any child
6310  * tables; else the addition would put them out of step.
6311  */
6312  if (children && !recurse)
6313  ereport(ERROR,
6314  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6315  errmsg("column must be added to child tables too")));
6316 
6317  /* Children should see column as singly inherited */
6318  if (!recursing)
6319  {
6320  childcmd = copyObject(*cmd);
6321  colDef = castNode(ColumnDef, childcmd->def);
6322  colDef->inhcount = 1;
6323  colDef->is_local = false;
6324  }
6325  else
6326  childcmd = *cmd; /* no need to copy again */
6327 
6328  foreach(child, children)
6329  {
6330  Oid childrelid = lfirst_oid(child);
6331  Relation childrel;
6332  AlteredTableInfo *childtab;
6333 
6334  /* find_inheritance_children already got lock */
6335  childrel = table_open(childrelid, NoLock);
6336  CheckTableNotInUse(childrel, "ALTER TABLE");
6337 
6338  /* Find or create work queue entry for this table */
6339  childtab = ATGetQueueEntry(wqueue, childrel);
6340 
6341  /* Recurse to child; return value is ignored */
6342  ATExecAddColumn(wqueue, childtab, childrel,
6343  &childcmd, recurse, true,
6344  lockmode, cur_pass, context);
6345 
6346  table_close(childrel, NoLock);
6347  }
6348 
6349  ObjectAddressSubSet(address, RelationRelationId, myrelid, newattnum);
6350  return address;
6351 }
#define NIL
Definition: pg_list.h:65
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal, const char *queryString)
Definition: heap.c:2520
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2426
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:264
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:151
AttrNumber attnum
Definition: heap.h:29
bool is_local
Definition: parsenodes.h:650
Oid GetUserId(void)
Definition: miscinit.c:448
#define castNode(_type_, nodeptr)
Definition: nodes.h:598
char identity
Definition: parsenodes.h:656
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:78
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
char * get_collation_name(Oid colloid)
Definition: lsyscache.c:1033
Expr * expression_planner(Expr *expr)
Definition: planner.c:6156
Definition: nodes.h:529
int errcode(int sqlerrcode)
Definition: elog.c:610
char generated
Definition: parsenodes.h:659
bool is_not_null
Definition: parsenodes.h:651
Form_pg_class rd_rel
Definition: rel.h:109
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define ATT_TABLE
Definition: tablecmds.c:292
int namestrcpy(Name name, const char *str)
Definition: name.c:250
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3607
signed int int32
Definition: c.h:355
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:337
bool DomainHasConstraints(Oid type_id)
Definition: typcache.c:1347
#define list_make1(x1)
Definition: pg_list.h:227
RangeVar * identitySequence
Definition: parsenodes.h:657
#define AT_REWRITE_DEFAULT_VAL
Definition: event_trigger.h:33
static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
Definition: tablecmds.c:6411
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:77
HeapTuple SearchSysCacheCopyAttName(Oid relid, const char *attname)
Definition: syscache.c:1280
ItemPointerData t_self
Definition: htup.h:65
static void add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
Definition: tablecmds.c:6429
bool missingMode
Definition: heap.h:31
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:957
char generated
Definition: heap.h:32
#define RelationGetRelationName(relation)
Definition: rel.h:490
static AlteredTableInfo * ATGetQueueEntry(List **wqueue, Relation rel)
Definition: tablecmds.c:5439
Node * raw_default
Definition: heap.h:30
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
#define ACL_USAGE
Definition: parsenodes.h:82
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3533
bool verify_new_notnull
Definition: tablecmds.c:166
Node * raw_default
Definition: parsenodes.h:654
List * lappend(List *list, void *datum)
Definition: list.c:321
Oid GetColumnDefCollation(ParseState *pstate, ColumnDef *coldef, Oid typeOid)
Definition: parse_type.c:538
Node * build_column_default(Relation rel, int attrno)
void * palloc0(Size size)
Definition: mcxt.c:980
AclResult
Definition: acl.h:177
uintptr_t Datum
Definition: postgres.h:367
void CommandCounterIncrement(void)
Definition: xact.c:1006
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define list_make1_oid(x1)
Definition: pg_list.h:249
static ObjectAddress ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel, AlterTableCmd **cmd, bool recurse, bool recursing, LOCKMODE lockmode, int cur_pass, AlterTableUtilityContext *context)
Definition: tablecmds.c:5952
TupleDesc rd_att
Definition: rel.h:110
void typenameTypeIdAndMod(ParseState *pstate, const TypeName *typeName, Oid *typeid_p, int32 *typmod_p)
Definition: parse_type.c:310
FormData_pg_attribute
Definition: pg_attribute.h:177
List * find_inheritance_children(Oid parentrelId, LOCKMODE lockmode)
Definition: pg_inherits.c:55
#define ereport(elevel,...)
Definition: elog.h:144
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2933
#define NOTICE
Definition: elog.h:37
#define MaxHeapAttributeNumber
Definition: htup_details.h:47
#define makeNode(_type_)
Definition: nodes.h:577
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:738
static AlterTableCmd * ATParseTransformCmd(List **wqueue, AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode, int cur_pass, AlterTableUtilityContext *context)
Definition: tablecmds.c:4695
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
FormData_pg_type * Form_pg_type
Definition: pg_type.h:255
static int list_length(const List *l)
Definition: pg_list.h:169
bool is_generated
Definition: tablecmds.c:209
#define newval
void InsertPgAttributeTuple(Relation pg_attribute_rel, Form_pg_attribute new_attribute, Datum attoptions, CatalogIndexState indstate)
Definition: heap.c:726
TypeName * typeName
Definition: parsenodes.h:648
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
List * arrayBounds
Definition: parsenodes.h:216
const ObjectAddress InvalidObjectAddress
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:824
static bool check_for_column_name_collision(Relation rel, const char *colname, bool if_not_exists)
Definition: tablecmds.c:6358
#define elog(elevel,...)
Definition: elog.h:214
int inhcount
Definition: parsenodes.h:649
static void ATSimplePermissions(Relation rel, int allowed_targets)
Definition: tablecmds.c:5476
char * colname
Definition: parsenodes.h:647
#define copyObject(obj)
Definition: nodes.h:645
void CheckAttributeType(const char *attname, Oid atttypid, Oid attcollation, List *containing_rowtypes, int flags)
Definition: heap.c:581
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4675
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define ATT_FOREIGN_TABLE
Definition: tablecmds.c:297
#define RelationGetRelid(relation)
Definition: rel.h:456
#define lfirst_oid(lc)
Definition: pg_list.h:192
AttrNumber attnum
Definition: tablecmds.c:206

◆ ATExecAddConstraint()

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

Definition at line 7936 of file tablecmds.c.

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

Referenced by ATExecCmd().

7939 {
7941 
7942  Assert(IsA(newConstraint, Constraint));
7943 
7944  /*
7945  * Currently, we only expect to see CONSTR_CHECK and CONSTR_FOREIGN nodes
7946  * arriving here (see the preprocessing done in parse_utilcmd.c). Use a
7947  * switch anyway to make it easier to add more code later.
7948  */
7949  switch (newConstraint->contype)
7950  {
7951  case CONSTR_CHECK:
7952  address =
7953  ATAddCheckConstraint(wqueue, tab, rel,
7954  newConstraint, recurse, false, is_readd,
7955  lockmode);
7956  break;
7957 
7958  case CONSTR_FOREIGN:
7959 
7960  /*
7961  * Assign or validate constraint name
7962  */
7963  if (newConstraint->conname)
7964  {
7966  RelationGetRelid(rel),
7967  newConstraint->conname))
7968  ereport(ERROR,
7970  errmsg("constraint \"%s\" for relation \"%s\" already exists",
7971  newConstraint->conname,
7972  RelationGetRelationName(rel))));
7973  }
7974  else
7975  newConstraint->conname =
7978  "fkey",
7979  RelationGetNamespace(rel),
7980  NIL);
7981 
7982  address = ATAddForeignKeyConstraint(wqueue, tab, rel,
7983  newConstraint, InvalidOid,
7984  recurse, false,
7985  lockmode);
7986  break;
7987 
7988  default:
7989  elog(ERROR, "unrecognized constraint type: %d",
7990  (int) newConstraint->contype);
7991  }
7992 
7993  return address;
7994 }
#define NIL
Definition: pg_list.h:65
char * ChooseConstraintName(const char *name1, const char *name2, const char *label, Oid namespaceid, List *others)
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
bool ConstraintNameIsUsed(ConstraintCategory conCat, Oid objId, const char *conname)
static char * ChooseForeignKeyConstraintNameAddition(List *colnames)
Definition: tablecmds.c:8009
int errcode(int sqlerrcode)
Definition: elog.c:610
static ObjectAddress ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *constr, bool recurse, bool recursing, bool is_readd, LOCKMODE lockmode)
Definition: tablecmds.c:8051
char * conname
Definition: parsenodes.h:2155
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:490
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:738
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
static ObjectAddress ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *fkconstraint, Oid parentConstr, bool recurse, bool recursing, LOCKMODE lockmode)
Definition: tablecmds.c:8187
ConstrType contype
Definition: parsenodes.h:2152
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:31
#define RelationGetRelid(relation)
Definition: rel.h:456
List * fk_attrs
Definition: parsenodes.h:2187
#define RelationGetNamespace(relation)
Definition: rel.h:497

◆ ATExecAddIdentity()

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

Definition at line 6864 of file tablecmds.c.

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

Referenced by ATExecCmd().

6866 {
6867  Relation attrelation;
6868  HeapTuple tuple;
6869  Form_pg_attribute attTup;
6871  ObjectAddress address;
6872  ColumnDef *cdef = castNode(ColumnDef, def);
6873 
6874  attrelation = table_open(AttributeRelationId, RowExclusiveLock);
6875 
6876  tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
6877  if (!HeapTupleIsValid(tuple))
6878  ereport(ERROR,
6879  (errcode(ERRCODE_UNDEFINED_COLUMN),
6880  errmsg("column \"%s\" of relation \"%s\" does not exist",
6881  colName, RelationGetRelationName(rel))));
6882  attTup = (Form_pg_attribute) GETSTRUCT(tuple);
6883  attnum = attTup->attnum;
6884 
6885  /* Can't alter a system attribute */
6886  if (attnum <= 0)
6887  ereport(ERROR,
6888  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6889  errmsg("cannot alter system column \"%s\"",
6890  colName)));
6891 
6892  /*
6893  * Creating a column as identity implies NOT NULL, so adding the identity
6894  * to an existing column that is not NOT NULL would create a state that
6895  * cannot be reproduced without contortions.
6896  */
6897  if (!attTup->attnotnull)
6898  ereport(ERROR,
6899  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6900  errmsg("column \"%s\" of relation \"%s\" must be declared NOT NULL before identity can be added",
6901  colName, RelationGetRelationName(rel))));
6902 
6903  if (attTup->attidentity)
6904  ereport(ERROR,
6905  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6906  errmsg("column \"%s\" of relation \"%s\" is already an identity column",
6907  colName, RelationGetRelationName(rel))));
6908 
6909  if (attTup->atthasdef)
6910  ereport(ERROR,
6911  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6912  errmsg("column \"%s\" of relation \"%s\" already has a default value",
6913  colName, RelationGetRelationName(rel))));
6914 
6915  attTup->attidentity = cdef->identity;
6916  CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
6917 
6918  InvokeObjectPostAlterHook(RelationRelationId,
6919  RelationGetRelid(rel),
6920  attTup->attnum);
6921  ObjectAddressSubSet(address, RelationRelationId,
6922  RelationGetRelid(rel), attnum);
6923  heap_freetuple(tuple);
6924 
6925  table_close(attrelation, RowExclusiveLock);
6926 
6927  return address;
6928 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define castNode(_type_, nodeptr)
Definition: nodes.h:598
char identity
Definition: parsenodes.h:656
int errcode(int sqlerrcode)
Definition: elog.c:610
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCacheCopyAttName(Oid relid, const char *attname)
Definition: syscache.c:1280
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:490
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
int16 attnum
Definition: pg_attribute.h:79
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
int errmsg(const char *fmt,...)
Definition: elog.c:824
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:456

◆ ATExecAddIndex()

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

Definition at line 7784 of file tablecmds.c.

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

Referenced by ATExecCmd().

7786 {
7787  bool check_rights;
7788  bool skip_build;
7789  bool quiet;
7790  ObjectAddress address;
7791 
7792  Assert(IsA(stmt, IndexStmt));
7793  Assert(!stmt->concurrent);
7794 
7795  /* The IndexStmt has already been through transformIndexStmt */
7796  Assert(stmt->transformed);
7797 
7798  /* suppress schema rights check when rebuilding existing index */
7799  check_rights = !is_rebuild;
7800  /* skip index build if phase 3 will do it or we're reusing an old one */
7801  skip_build = tab->rewrite > 0 || OidIsValid(stmt->oldNode);
7802  /* suppress notices when rebuilding existing index */
7803  quiet = is_rebuild;
7804 
7805  address = DefineIndex(RelationGetRelid(rel),
7806  stmt,
7807  InvalidOid, /* no predefined OID */
7808  InvalidOid, /* no parent index */
7809  InvalidOid, /* no parent constraint */
7810  true, /* is_alter_table */
7811  check_rights,
7812  false, /* check_not_in_use - we did it already */
7813  skip_build,
7814  quiet);
7815 
7816  /*
7817  * If TryReuseIndex() stashed a relfilenode for us, we used it for the new
7818  * index instead of building from scratch. Restore associated fields.
7819  * This may store InvalidSubTransactionId in both fields, in which case
7820  * relcache.c will assume it can rebuild the relcache entry. Hence, do
7821  * this after the CCI that made catalog rows visible to any rebuild. The
7822  * DROP of the old edition of this index will have scheduled the storage
7823  * for deletion at commit, so cancel that pending deletion.
7824  */
7825  if (OidIsValid(stmt->oldNode))
7826  {
7827  Relation irel = index_open(address.objectId, NoLock);
7828 
7829  irel->rd_createSubid = stmt->oldCreateSubid;
7831  RelationPreserveStorage(irel->rd_node, true);
7832  index_close(irel, NoLock);
7833  }
7834 
7835  return address;
7836 }
void RelationPreserveStorage(RelFileNode rnode, bool atCommit)
Definition: storage.c:240
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
ObjectAddress DefineIndex(Oid relationId, IndexStmt *stmt, Oid indexRelationId, Oid parentIndexId, Oid parentConstraintId, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
Definition: indexcmds.c:479
SubTransactionId oldCreateSubid
Definition: parsenodes.h:2788
#define OidIsValid(objectId)
Definition: c.h:644
#define NoLock
Definition: lockdefs.h:34
bool transformed
Definition: parsenodes.h:2796
SubTransactionId oldFirstRelfilenodeSubid
Definition: parsenodes.h:2789
SubTransactionId rd_createSubid
Definition: rel.h:102
SubTransactionId rd_firstRelfilenodeSubid
Definition: rel.h:105
#define InvalidOid
Definition: postgres_ext.h:36
RelFileNode rd_node
Definition: rel.h:55
#define Assert(condition)
Definition: c.h:738
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
bool concurrent
Definition: parsenodes.h:2797
#define RelationGetRelid(relation)
Definition: rel.h:456
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132

◆ ATExecAddIndexConstraint()

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

Definition at line 7844 of file tablecmds.c.

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

Referenced by ATExecCmd().

7846 {
7847  Oid index_oid = stmt->indexOid;
7848  Relation indexRel;
7849  char *indexName;
7850  IndexInfo *indexInfo;
7851  char *constraintName;
7852  char constraintType;
7853  ObjectAddress address;
7854  bits16 flags;
7855 
7856  Assert(IsA(stmt, IndexStmt));
7857  Assert(OidIsValid(index_oid));
7858  Assert(stmt->isconstraint);
7859 
7860  /*
7861  * Doing this on partitioned tables is not a simple feature to implement,
7862  * so let's punt for now.
7863  */
7864  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
7865  ereport(ERROR,
7866  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7867  errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX is not supported on partitioned tables")));
7868 
7869  indexRel = index_open(index_oid, AccessShareLock);
7870 
7871  indexName = pstrdup(RelationGetRelationName(indexRel));
7872 
7873  indexInfo = BuildIndexInfo(indexRel);
7874 
7875  /* this should have been checked at parse time */
7876  if (!indexInfo->ii_Unique)
7877  elog(ERROR, "index \"%s\" is not unique", indexName);
7878 
7879  /*
7880  * Determine name to assign to constraint. We require a constraint to
7881  * have the same name as the underlying index; therefore, use the index's
7882  * existing name as the default constraint name, and if the user
7883  * explicitly gives some other name for the constraint, rename the index
7884  * to match.
7885  */
7886  constraintName = stmt->idxname;
7887  if (constraintName == NULL)
7888  constraintName = indexName;
7889  else if (strcmp(constraintName, indexName) != 0)
7890  {
7891  ereport(NOTICE,
7892  (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
7893  indexName, constraintName)));
7894  RenameRelationInternal(index_oid, constraintName, false, true);
7895  }
7896 
7897  /* Extra checks needed if making primary key */
7898  if (stmt->primary)
7899  index_check_primary_key(rel, indexInfo, true, stmt);
7900 
7901  /* Note we currently don't support EXCLUSION constraints here */
7902  if (stmt->primary)
7903  constraintType = CONSTRAINT_PRIMARY;
7904  else
7905  constraintType = CONSTRAINT_UNIQUE;
7906 
7907  /* Create the catalog entries for the constraint */
7913 
7914  address = index_constraint_create(rel,
7915  index_oid,
7916  InvalidOid,
7917  indexInfo,
7918  constraintName,
7919  constraintType,
7920  flags,
7922  false); /* is_internal */
7923 
7924  index_close(indexRel, NoLock);
7925 
7926  return address;
7927 }
bool deferrable
Definition: parsenodes.h:2794
bool primary
Definition: parsenodes.h:2792
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
uint16 bits16
Definition: c.h:375
char * pstrdup(const char *in)
Definition: mcxt.c:1186
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:610
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2298
#define INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS
Definition: index.h:79
void index_check_primary_key(Relation heapRel, IndexInfo *indexInfo, bool is_alter_table, IndexStmt *stmt)
Definition: index.c:201
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:644
#define INDEX_CONSTR_CREATE_INIT_DEFERRED
Definition: index.h:77
Oid indexOid
Definition: parsenodes.h:2786
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:490
char * idxname
Definition: parsenodes.h:2775
bool allowSystemTableMods
Definition: globals.c:120
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define NOTICE
Definition: elog.h:37
bool ii_Unique
Definition: execnodes.h:172
#define Assert(condition)
Definition: c.h:738
bool initdeferred
Definition: parsenodes.h:2795
#define INDEX_CONSTR_CREATE_UPDATE_INDEX
Definition: index.h:78
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
bool isconstraint
Definition: parsenodes.h:2793
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
Definition: tablecmds.c:3431
#define INDEX_CONSTR_CREATE_DEFERRABLE
Definition: index.h:76
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
#define INDEX_CONSTR_CREATE_MARK_AS_PRIMARY
Definition: index.h:75
ObjectAddress index_constraint_create(Relation heapRelation, Oid indexRelationId, Oid parentConstraintId, IndexInfo *indexInfo, const char *constraintName, char constraintType, bits16 constr_flags, bool allow_system_table_mods, bool is_internal)
Definition: index.c:1792

◆ ATExecAddInherit()

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