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_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 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)
 
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 bool isPartitionTrigger (Oid trigger_oid)
 
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 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 294 of file tablecmds.c.

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

◆ ATT_FOREIGN_TABLE

◆ ATT_INDEX

#define ATT_INDEX   0x0008

Definition at line 293 of file tablecmds.c.

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

◆ ATT_MATVIEW

#define ATT_MATVIEW   0x0004

Definition at line 292 of file tablecmds.c.

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

◆ ATT_PARTITIONED_INDEX

#define ATT_PARTITIONED_INDEX   0x0040

Definition at line 296 of file tablecmds.c.

Referenced by ATPrepCmd(), and ATSimplePermissions().

◆ ATT_TABLE

◆ ATT_VIEW

#define ATT_VIEW   0x0002

Definition at line 291 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 303 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 6338 of file tablecmds.c.

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

Referenced by ATExecAddColumn(), and ATExecAlterColumnType().

6339 {
6340  ObjectAddress myself,
6341  referenced;
6342 
6343  /* We know the default collation is pinned, so don't bother recording it */
6344  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
6345  {
6346  myself.classId = RelationRelationId;
6347  myself.objectId = relid;
6348  myself.objectSubId = attnum;
6349  referenced.classId = CollationRelationId;
6350  referenced.objectId = collid;
6351  referenced.objectSubId = 0;
6352  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
6353  }
6354 }
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
#define OidIsValid(objectId)
Definition: c.h:645
int16 attnum
Definition: pg_attribute.h:79

◆ add_column_datatype_dependency()

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

Definition at line 6320 of file tablecmds.c.

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

Referenced by ATExecAddColumn(), and ATExecAlterColumnType().

6321 {
6322  ObjectAddress myself,
6323  referenced;
6324 
6325  myself.classId = RelationRelationId;
6326  myself.objectId = relid;
6327  myself.objectSubId = attnum;
6328  referenced.classId = TypeRelationId;
6329  referenced.objectId = typid;
6330  referenced.objectSubId = 0;
6331  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
6332 }
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 8483 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().

8488 {
8489  ObjectAddress address;
8490  Oid constrOid;
8491  char *conname;
8492  bool conislocal;
8493  int coninhcount;
8494  bool connoinherit;
8495 
8496  /*
8497  * Verify relkind for each referenced partition. At the top level, this
8498  * is redundant with a previous check, but we need it when recursing.
8499  */
8500  if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
8501  pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
8502  ereport(ERROR,
8503  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8504  errmsg("referenced relation \"%s\" is not a table",
8505  RelationGetRelationName(pkrel))));
8506 
8507  /*
8508  * Caller supplies us with a constraint name; however, it may be used in
8509  * this partition, so come up with a different one in that case.
8510  */
8512  RelationGetRelid(rel),
8513  fkconstraint->conname))
8516  "fkey",
8517  RelationGetNamespace(rel), NIL);
8518  else
8519  conname = fkconstraint->conname;
8520 
8521  if (OidIsValid(parentConstr))
8522  {
8523  conislocal = false;
8524  coninhcount = 1;
8525  connoinherit = false;
8526  }
8527  else
8528  {
8529  conislocal = true;
8530  coninhcount = 0;
8531 
8532  /*
8533  * always inherit for partitioned tables, never for legacy inheritance
8534  */
8535  connoinherit = rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE;
8536  }
8537 
8538  /*
8539  * Record the FK constraint in pg_constraint.
8540  */
8541  constrOid = CreateConstraintEntry(conname,
8542  RelationGetNamespace(rel),
8543  CONSTRAINT_FOREIGN,
8544  fkconstraint->deferrable,
8545  fkconstraint->initdeferred,
8546  fkconstraint->initially_valid,
8547  parentConstr,
8548  RelationGetRelid(rel),
8549  fkattnum,
8550  numfks,
8551  numfks,
8552  InvalidOid, /* not a domain constraint */
8553  indexOid,
8554  RelationGetRelid(pkrel),
8555  pkattnum,
8556  pfeqoperators,
8557  ppeqoperators,
8558  ffeqoperators,
8559  numfks,
8560  fkconstraint->fk_upd_action,
8561  fkconstraint->fk_del_action,
8562  fkconstraint->fk_matchtype,
8563  NULL, /* no exclusion constraint */
8564  NULL, /* no check constraint */
8565  NULL,
8566  conislocal, /* islocal */
8567  coninhcount, /* inhcount */
8568  connoinherit, /* conNoInherit */
8569  false); /* is_internal */
8570 
8571  ObjectAddressSet(address, ConstraintRelationId, constrOid);
8572 
8573  /*
8574  * Mark the child constraint as part of the parent constraint; it must not
8575  * be dropped on its own. (This constraint is deleted when the partition
8576  * is detached, but a special check needs to occur that the partition
8577  * contains no referenced values.)
8578  */
8579  if (OidIsValid(parentConstr))
8580  {
8581  ObjectAddress referenced;
8582 
8583  ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
8584  recordDependencyOn(&address, &referenced, DEPENDENCY_INTERNAL);
8585  }
8586 
8587  /* make new constraint visible, in case we add more */
8589 
8590  /*
8591  * If the referenced table is a plain relation, create the action triggers
8592  * that enforce the constraint.
8593  */
8594  if (pkrel->rd_rel->relkind == RELKIND_RELATION)
8595  {
8597  fkconstraint,
8598  constrOid, indexOid);
8599  }
8600 
8601  /*
8602  * If the referenced table is partitioned, recurse on ourselves to handle
8603  * each partition. We need one pg_constraint row created for each
8604  * partition in addition to the pg_constraint row for the parent table.
8605  */
8606  if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
8607  {
8609 
8610  for (int i = 0; i < pd->nparts; i++)
8611  {
8612  Relation partRel;
8613  AttrMap *map;
8614  AttrNumber *mapped_pkattnum;
8615  Oid partIndexId;
8616 
8617  partRel = table_open(pd->oids[i], ShareRowExclusiveLock);
8618 
8619  /*
8620  * Map the attribute numbers in the referenced side of the FK
8621  * definition to match the partition's column layout.
8622  */
8624  RelationGetDescr(pkrel));
8625  if (map)
8626  {
8627  mapped_pkattnum = palloc(sizeof(AttrNumber) * numfks);
8628  for (int j = 0; j < numfks; j++)
8629  mapped_pkattnum[j] = map->attnums[pkattnum[j] - 1];
8630  }
8631  else
8632  mapped_pkattnum = pkattnum;
8633 
8634  /* do the deed */
8635  partIndexId = index_get_partition(partRel, indexOid);
8636  if (!OidIsValid(partIndexId))
8637  elog(ERROR, "index for %u not found in partition %s",
8638  indexOid, RelationGetRelationName(partRel));
8639  addFkRecurseReferenced(wqueue, fkconstraint, rel, partRel,
8640  partIndexId, constrOid, numfks,
8641  mapped_pkattnum, fkattnum,
8642  pfeqoperators, ppeqoperators, ffeqoperators,
8643  old_check_ok);
8644 
8645  /* Done -- clean up (but keep the lock) */
8646  table_close(partRel, NoLock);
8647  if (map)
8648  {
8649  pfree(mapped_pkattnum);
8650  free_attrmap(map);
8651  }
8652  }
8653  }
8654 
8655  return address;
8656 }
#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:7866
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:454
char fk_matchtype
Definition: parsenodes.h:2186
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:608
bool initdeferred
Definition: parsenodes.h:2154
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
char * conname
Definition: parsenodes.h:2152
Form_pg_class rd_rel
Definition: rel.h:84
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
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:8483
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:2153
#define NoLock
Definition: lockdefs.h:34
PartitionDesc RelationGetPartitionDesc(Relation rel)
Definition: partdesc.c:65
#define RelationGetRelationName(relation)
Definition: rel.h:462
#define ereport(elevel, rest)
Definition: elog.h:141
static void createForeignKeyActionTriggers(Relation rel, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid)
Definition: tablecmds.c:10311
void CommandCounterIncrement(void)
Definition: xact.c:1005
#define InvalidOid
Definition: postgres_ext.h:36
bool initially_valid
Definition: parsenodes.h:2195
char fk_del_action
Definition: parsenodes.h:2188
#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:822
#define elog(elevel,...)
Definition: elog.h:228
int i
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:428
List * fk_attrs
Definition: parsenodes.h:2184
char fk_upd_action
Definition: parsenodes.h:2187
#define RelationGetNamespace(relation)
Definition: rel.h:469

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

8693 {
8694  AssertArg(OidIsValid(parentConstr));
8695 
8696  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
8697  ereport(ERROR,
8698  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8699  errmsg("foreign key constraints are not supported on foreign tables")));
8700 
8701  /*
8702  * If the referencing relation is a plain table, add the check triggers to
8703  * it and, if necessary, schedule it to be checked in Phase 3.
8704  *
8705  * If the relation is partitioned, drill down to do it to its partitions.
8706  */
8707  if (rel->rd_rel->relkind == RELKIND_RELATION)
8708  {
8710  RelationGetRelid(pkrel),
8711  fkconstraint,
8712  parentConstr,
8713  indexOid);
8714 
8715  /*
8716  * Tell Phase 3 to check that the constraint is satisfied by existing
8717  * rows. We can skip this during table creation, when requested
8718  * explicitly by specifying NOT VALID in an ADD FOREIGN KEY command,
8719  * and when we're recreating a constraint following a SET DATA TYPE
8720  * operation that did not impugn its validity.
8721  */
8722  if (wqueue && !old_check_ok && !fkconstraint->skip_validation)
8723  {
8724  NewConstraint *newcon;
8725  AlteredTableInfo *tab;
8726 
8727  tab = ATGetQueueEntry(wqueue, rel);
8728 
8729  newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
8730  newcon->name = get_constraint_name(parentConstr);
8731  newcon->contype = CONSTR_FOREIGN;
8732  newcon->refrelid = RelationGetRelid(pkrel);
8733  newcon->refindid = indexOid;
8734  newcon->conid = parentConstr;
8735  newcon->qual = (Node *) fkconstraint;
8736 
8737  tab->constraints = lappend(tab->constraints, newcon);
8738  }
8739  }
8740  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
8741  {
8743 
8744  /*
8745  * Recurse to take appropriate action on each partition; either we
8746  * find an existing constraint to reparent to ours, or we create a new
8747  * one.
8748  */
8749  for (int i = 0; i < pd->nparts; i++)
8750  {
8751  Oid partitionId = pd->oids[i];
8752  Relation partition = table_open(partitionId, lockmode);
8753  List *partFKs;
8754  AttrMap *attmap;
8755  AttrNumber mapped_fkattnum[INDEX_MAX_KEYS];
8756  bool attached;
8757  char *conname;
8758  Oid constrOid;
8759  ObjectAddress address,
8760  referenced;
8761  ListCell *cell;
8762 
8763  CheckTableNotInUse(partition, "ALTER TABLE");
8764 
8765  attmap = build_attrmap_by_name(RelationGetDescr(partition),
8766  RelationGetDescr(rel));
8767  for (int j = 0; j < numfks; j++)
8768  mapped_fkattnum[j] = attmap->attnums[fkattnum[j] - 1];
8769 
8770  /* Check whether an existing constraint can be repurposed */
8771  partFKs = copyObject(RelationGetFKeyList(partition));
8772  attached = false;
8773  foreach(cell, partFKs)
8774  {
8775  ForeignKeyCacheInfo *fk;
8776 
8777  fk = lfirst_node(ForeignKeyCacheInfo, cell);
8779  partitionId,
8780  parentConstr,
8781  numfks,
8782  mapped_fkattnum,
8783  pkattnum,
8784  pfeqoperators))
8785  {
8786  attached = true;
8787  break;
8788  }
8789  }
8790  if (attached)
8791  {
8792  table_close(partition, NoLock);
8793  continue;
8794  }
8795 
8796  /*
8797  * No luck finding a good constraint to reuse; create our own.
8798  */
8800  RelationGetRelid(partition),
8801  fkconstraint->conname))
8802  conname = ChooseConstraintName(RelationGetRelationName(partition),
8804  "fkey",
8805  RelationGetNamespace(partition), NIL);
8806  else
8807  conname = fkconstraint->conname;
8808  constrOid =
8809  CreateConstraintEntry(conname,
8810  RelationGetNamespace(partition),
8811  CONSTRAINT_FOREIGN,
8812  fkconstraint->deferrable,
8813  fkconstraint->initdeferred,
8814  fkconstraint->initially_valid,
8815  parentConstr,
8816  partitionId,
8817  mapped_fkattnum,
8818  numfks,
8819  numfks,
8820  InvalidOid,
8821  indexOid,
8822  RelationGetRelid(pkrel),
8823  pkattnum,
8824  pfeqoperators,
8825  ppeqoperators,
8826  ffeqoperators,
8827  numfks,
8828  fkconstraint->fk_upd_action,
8829  fkconstraint->fk_del_action,
8830  fkconstraint->fk_matchtype,
8831  NULL,
8832  NULL,
8833  NULL,
8834  false,
8835  1,
8836  false,
8837  false);
8838 
8839  /*
8840  * Give this constraint partition-type dependencies on the parent
8841  * constraint as well as the table.
8842  */
8843  ObjectAddressSet(address, ConstraintRelationId, constrOid);
8844  ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
8845  recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_PRI);
8846  ObjectAddressSet(referenced, RelationRelationId, partitionId);
8847  recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_SEC);
8848 
8849  /* Make all this visible before recursing */
8851 
8852  /* call ourselves to finalize the creation and we're done */
8853  addFkRecurseReferencing(wqueue, fkconstraint, partition, pkrel,
8854  indexOid,
8855  constrOid,
8856  numfks,
8857  pkattnum,
8858  mapped_fkattnum,
8859  pfeqoperators,
8860  ppeqoperators,
8861  ffeqoperators,
8862  old_check_ok,
8863  lockmode);
8864 
8865  table_close(partition, NoLock);
8866  }
8867  }
8868 }
#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:10432
bool ConstraintNameIsUsed(ConstraintCategory conCat, Oid objId, const char *conname)
char * name
Definition: tablecmds.c:185
static char * ChooseForeignKeyConstraintNameAddition(List *colnames)
Definition: tablecmds.c:7866
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define RelationGetDescr(relation)
Definition: rel.h:454
char * get_constraint_name(Oid conoid)
Definition: lsyscache.c:969
static void addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint, Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr, int numfks, int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators, bool old_check_ok, LOCKMODE lockmode)
Definition: tablecmds.c:8688
char fk_matchtype
Definition: parsenodes.h:2186
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:190
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
bool initdeferred
Definition: parsenodes.h:2154
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
char * conname
Definition: parsenodes.h:2152
Form_pg_class rd_rel
Definition: rel.h:84
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
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:9279
#define ERROR
Definition: elog.h:43
bool deferrable
Definition: parsenodes.h:2153
#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:462
static AlteredTableInfo * ATGetQueueEntry(List **wqueue, Relation rel)
Definition: tablecmds.c:5352
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3445
#define ereport(elevel, rest)
Definition: elog.h:141
#define AssertArg(condition)
Definition: c.h:741
List * lappend(List *list, void *datum)
Definition: list.c:322
ConstrType contype
Definition: tablecmds.c:186
void * palloc0(Size size)
Definition: mcxt.c:980
void CommandCounterIncrement(void)
Definition: xact.c:1005
#define InvalidOid
Definition: postgres_ext.h:36
bool initially_valid
Definition: parsenodes.h:2195
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc)
Definition: attmap.c:174
char fk_del_action
Definition: parsenodes.h:2188
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:4221
int errmsg(const char *fmt,...)
Definition: elog.c:822
int i
#define copyObject(obj)
Definition: nodes.h:641
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
bool skip_validation
Definition: parsenodes.h:2194
#define RelationGetRelid(relation)
Definition: rel.h:428
List * fk_attrs
Definition: parsenodes.h:2184
char fk_upd_action
Definition: parsenodes.h:2187
#define RelationGetNamespace(relation)
Definition: rel.h:469

◆ AlterIndexNamespaces()

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

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

14870 {
14871  List *indexList;
14872  ListCell *l;
14873 
14874  indexList = RelationGetIndexList(rel);
14875 
14876  foreach(l, indexList)
14877  {
14878  Oid indexOid = lfirst_oid(l);
14879  ObjectAddress thisobj;
14880 
14881  thisobj.classId = RelationRelationId;
14882  thisobj.objectId = indexOid;
14883  thisobj.objectSubId = 0;
14884 
14885  /*
14886  * Note: currently, the index will not have its own dependency on the
14887  * namespace, so we don't need to do changeDependencyFor(). There's no
14888  * row type in pg_type, either.
14889  *
14890  * XXX this objsMoved test may be pointless -- surely we have a single
14891  * dependency link from a relation to each index?
14892  */
14893  if (!object_address_present(&thisobj, objsMoved))
14894  {
14895  AlterRelationNamespaceInternal(classRel, indexOid,
14896  oldNspOid, newNspOid,
14897  false, objsMoved);
14898  add_exact_object_address(&thisobj, objsMoved);
14899  }
14900  }
14901 
14902  list_free(indexList);
14903 }
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2529
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2469
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:14798
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4330
void list_free(List *list)
Definition: list.c:1377
Definition: pg_list.h:50
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ AlterRelationNamespaceInternal()

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

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

14802 {
14803  HeapTuple classTup;
14804  Form_pg_class classForm;
14805  ObjectAddress thisobj;
14806  bool already_done = false;
14807 
14808  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
14809  if (!HeapTupleIsValid(classTup))
14810  elog(ERROR, "cache lookup failed for relation %u", relOid);
14811  classForm = (Form_pg_class) GETSTRUCT(classTup);
14812 
14813  Assert(classForm->relnamespace == oldNspOid);
14814 
14815  thisobj.classId = RelationRelationId;
14816  thisobj.objectId = relOid;
14817  thisobj.objectSubId = 0;
14818 
14819  /*
14820  * If the object has already been moved, don't move it again. If it's
14821  * already in the right place, don't move it, but still fire the object
14822  * access hook.
14823  */
14824  already_done = object_address_present(&thisobj, objsMoved);
14825  if (!already_done && oldNspOid != newNspOid)
14826  {
14827  /* check for duplicate name (more friendly than unique-index failure) */
14828  if (get_relname_relid(NameStr(classForm->relname),
14829  newNspOid) != InvalidOid)
14830  ereport(ERROR,
14831  (errcode(ERRCODE_DUPLICATE_TABLE),
14832  errmsg("relation \"%s\" already exists in schema \"%s\"",
14833  NameStr(classForm->relname),
14834  get_namespace_name(newNspOid))));
14835 
14836  /* classTup is a copy, so OK to scribble on */
14837  classForm->relnamespace = newNspOid;
14838 
14839  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
14840 
14841  /* Update dependency on schema if caller said so */
14842  if (hasDependEntry &&
14843  changeDependencyFor(RelationRelationId,
14844  relOid,
14845  NamespaceRelationId,
14846  oldNspOid,
14847  newNspOid) != 1)
14848  elog(ERROR, "failed to change schema dependency for relation \"%s\"",
14849  NameStr(classForm->relname));
14850  }
14851  if (!already_done)
14852  {
14853  add_exact_object_address(&thisobj, objsMoved);
14854 
14855  InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
14856  }
14857 
14858  heap_freetuple(classTup);
14859 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2529
int errcode(int sqlerrcode)
Definition: elog.c:608
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2469
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1687
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:739
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
int errmsg(const char *fmt,...)
Definition: elog.c:822
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:297
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:616

◆ AlterSeqNamespaces()

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

Definition at line 14913 of file tablecmds.c.

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

Referenced by AlterTableNamespaceInternal().

14916 {
14917  Relation depRel;
14918  SysScanDesc scan;
14919  ScanKeyData key[2];
14920  HeapTuple tup;
14921 
14922  /*
14923  * SERIAL sequences are those having an auto dependency on one of the
14924  * table's columns (we don't care *which* column, exactly).
14925  */
14926  depRel = table_open(DependRelationId, AccessShareLock);
14927 
14928  ScanKeyInit(&key[0],
14929  Anum_pg_depend_refclassid,
14930  BTEqualStrategyNumber, F_OIDEQ,
14931  ObjectIdGetDatum(RelationRelationId));
14932  ScanKeyInit(&key[1],
14933  Anum_pg_depend_refobjid,
14934  BTEqualStrategyNumber, F_OIDEQ,
14936  /* we leave refobjsubid unspecified */
14937 
14938  scan = systable_beginscan(depRel, DependReferenceIndexId, true,
14939  NULL, 2, key);
14940 
14941  while (HeapTupleIsValid(tup = systable_getnext(scan)))
14942  {
14943  Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
14944  Relation seqRel;
14945 
14946  /* skip dependencies other than auto dependencies on columns */
14947  if (depForm->refobjsubid == 0 ||
14948  depForm->classid != RelationRelationId ||
14949  depForm->objsubid != 0 ||
14950  !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
14951  continue;
14952 
14953  /* Use relation_open just in case it's an index */
14954  seqRel = relation_open(depForm->objid, lockmode);
14955 
14956  /* skip non-sequence relations */
14957  if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
14958  {
14959  /* No need to keep the lock */
14960  relation_close(seqRel, lockmode);
14961  continue;
14962  }
14963 
14964  /* Fix the pg_class and pg_depend entries */
14965  AlterRelationNamespaceInternal(classRel, depForm->objid,
14966  oldNspOid, newNspOid,
14967  true, objsMoved);
14968 
14969  /*
14970  * Sequences have entries in pg_type. We need to be careful to move
14971  * them to the new namespace, too.
14972  */
14974  newNspOid, false, false, objsMoved);
14975 
14976  /* Now we can close it. Keep the lock till end of transaction. */
14977  relation_close(seqRel, NoLock);
14978  }
14979 
14980  systable_endscan(scan);
14981 
14983 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:525
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define RelationGetForm(relation)
Definition: rel.h:422
#define DependReferenceIndexId
Definition: indexing.h:151
#define AccessShareLock
Definition: lockdefs.h:36
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:3579
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:352
char relkind
Definition: pg_class.h:81
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:444
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:71
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:14798
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:428
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ AlterTable()

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

Definition at line 3529 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3531 {
3532  Relation rel;
3533 
3534  /* Caller is required to provide an adequate lock. */
3535  rel = relation_open(context->relid, NoLock);
3536 
3537  CheckTableNotInUse(rel, "ALTER TABLE");
3538 
3539  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
3540 }
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:3864
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:3445
bool inh
Definition: primnodes.h:69
RangeVar * relation
Definition: parsenodes.h:1774

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)

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

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

◆ AlterTableInternal()

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

Definition at line 3558 of file tablecmds.c.

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

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

3559 {
3560  Relation rel;
3561  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
3562 
3563  rel = relation_open(relid, lockmode);
3564 
3566 
3567  ATController(NULL, rel, cmds, recurse, lockmode, NULL);
3568 }
int LOCKMODE
Definition: lockdefs.h:26
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:3864
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:3603
void EventTriggerAlterTableRelid(Oid objectId)

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 3473 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3474 {
3475  return RangeVarGetRelidExtended(stmt->relation, lockmode,
3476  stmt->missing_ok ? RVR_MISSING_OK : 0,
3478  (void *) stmt);
3479 }
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:15311
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:228
RangeVar * relation
Definition: parsenodes.h:1774

◆ AlterTableMoveAll()

Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

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

12994 {
12995  List *relations = NIL;
12996  ListCell *l;
12997  ScanKeyData key[1];
12998  Relation rel;
12999  TableScanDesc scan;
13000  HeapTuple tuple;
13001  Oid orig_tablespaceoid;
13002  Oid new_tablespaceoid;
13003  List *role_oids = roleSpecsToIds(stmt->roles);
13004 
13005  /* Ensure we were not asked to move something we can't */
13006  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
13007  stmt->objtype != OBJECT_MATVIEW)
13008  ereport(ERROR,
13009  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
13010  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
13011 
13012  /* Get the orig and new tablespace OIDs */
13013  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
13014  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
13015 
13016  /* Can't move shared relations in to or out of pg_global */
13017  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
13018  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
13019  new_tablespaceoid == GLOBALTABLESPACE_OID)
13020  ereport(ERROR,
13021  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
13022  errmsg("cannot move relations in to or out of pg_global tablespace")));
13023 
13024  /*
13025  * Must have CREATE rights on the new tablespace, unless it is the
13026  * database default tablespace (which all users implicitly have CREATE
13027  * rights on).
13028  */
13029  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
13030  {
13031  AclResult aclresult;
13032 
13033  aclresult = pg_tablespace_aclcheck(new_tablespaceoid, GetUserId(),
13034  ACL_CREATE);
13035  if (aclresult != ACLCHECK_OK)
13036  aclcheck_error(aclresult, OBJECT_TABLESPACE,
13037  get_tablespace_name(new_tablespaceoid));
13038  }
13039 
13040  /*
13041  * Now that the checks are done, check if we should set either to
13042  * InvalidOid because it is our database's default tablespace.
13043  */
13044  if (orig_tablespaceoid == MyDatabaseTableSpace)
13045  orig_tablespaceoid = InvalidOid;
13046 
13047  if (new_tablespaceoid == MyDatabaseTableSpace)
13048  new_tablespaceoid = InvalidOid;
13049 
13050  /* no-op */
13051  if (orig_tablespaceoid == new_tablespaceoid)
13052  return new_tablespaceoid;
13053 
13054  /*
13055  * Walk the list of objects in the tablespace and move them. This will
13056  * only find objects in our database, of course.
13057  */
13058  ScanKeyInit(&key[0],
13059  Anum_pg_class_reltablespace,
13060  BTEqualStrategyNumber, F_OIDEQ,
13061  ObjectIdGetDatum(orig_tablespaceoid));
13062 
13063  rel = table_open(RelationRelationId, AccessShareLock);
13064  scan = table_beginscan_catalog(rel, 1, key);
13065  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
13066  {
13067  Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
13068  Oid relOid = relForm->oid;
13069 
13070  /*
13071  * Do not move objects in pg_catalog as part of this, if an admin
13072  * really wishes to do so, they can issue the individual ALTER
13073  * commands directly.
13074  *
13075  * Also, explicitly avoid any shared tables, temp tables, or TOAST
13076  * (TOAST will be moved with the main table).
13077  */
13078  if (IsCatalogNamespace(relForm->relnamespace) ||
13079  relForm->relisshared ||
13080  isAnyTempNamespace(relForm->relnamespace) ||
13081  IsToastNamespace(relForm->relnamespace))
13082  continue;
13083 
13084  /* Only move the object type requested */
13085  if ((stmt->objtype == OBJECT_TABLE &&
13086  relForm->relkind != RELKIND_RELATION &&
13087  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
13088  (stmt->objtype == OBJECT_INDEX &&
13089  relForm->relkind != RELKIND_INDEX &&
13090  relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
13091  (stmt->objtype == OBJECT_MATVIEW &&
13092  relForm->relkind != RELKIND_MATVIEW))
13093  continue;
13094 
13095  /* Check if we are only moving objects owned by certain roles */
13096  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
13097  continue;
13098 
13099  /*
13100  * Handle permissions-checking here since we are locking the tables
13101  * and also to avoid doing a bunch of work only to fail part-way. Note
13102  * that permissions will also be checked by AlterTableInternal().
13103  *
13104  * Caller must be considered an owner on the table to move it.
13105  */
13106  if (!pg_class_ownercheck(relOid, GetUserId()))
13108  NameStr(relForm->relname));
13109 
13110  if (stmt->nowait &&
13112  ereport(ERROR,
13113  (errcode(ERRCODE_OBJECT_IN_USE),
13114  errmsg("aborting because lock on relation \"%s.%s\" is not available",
13115  get_namespace_name(relForm->relnamespace),
13116  NameStr(relForm->relname))));
13117  else
13119 
13120  /* Add to our list of objects to move */
13121  relations = lappend_oid(relations, relOid);
13122  }
13123 
13124  table_endscan(scan);
13126 
13127  if (relations == NIL)
13128  ereport(NOTICE,
13129  (errcode(ERRCODE_NO_DATA_FOUND),
13130  errmsg("no matching relations in tablespace \"%s\" found",
13131  orig_tablespaceoid == InvalidOid ? "(database default)" :
13132  get_tablespace_name(orig_tablespaceoid))));
13133 
13134  /* Everything is locked, loop through and move all of the relations. */
13135  foreach(l, relations)
13136  {
13137  List *cmds = NIL;
13139 
13140  cmd->subtype = AT_SetTableSpace;
13141  cmd->name = stmt->new_tablespacename;
13142 
13143  cmds = lappend(cmds, cmd);
13144 
13146  /* OID is set by AlterTableInternal */
13147  AlterTableInternal(lfirst_oid(l), cmds, false);
13149  }
13150 
13151  return new_tablespaceoid;
13152 }
#define NIL
Definition: pg_list.h:65
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:151
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1416
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4703
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:98
Oid GetUserId(void)
Definition: miscinit.c:380
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1805
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
AlterTableType subtype
Definition: parsenodes.h:1860
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:196
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:358
#define OidIsValid(objectId)
Definition: c.h:645
Oid MyDatabaseTableSpace
Definition: globals.c:87
void EventTriggerAlterTableStart(Node *parsetree)
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3352
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:84
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1290
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
AclResult
Definition: acl.h:177
#define InvalidOid
Definition: postgres_ext.h:36
#define NOTICE
Definition: elog.h:37
#define makeNode(_type_)
Definition: nodes.h:573
List * roleSpecsToIds(List *memberNames)
Definition: user.c:1423
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:675
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4753
bool IsCatalogNamespace(Oid namespaceId)
Definition: catalog.c:178
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:849
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:3558
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:822
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1462
ObjectType get_relkind_objtype(char relkind)
#define NameStr(name)
Definition: c.h:616
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
bool isAnyTempNamespace(Oid namespaceId)
Definition: namespace.c:3187
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:108
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define lfirst_oid(lc)
Definition: pg_list.h:192
void EventTriggerAlterTableEnd(void)

◆ AlterTableNamespace()

ObjectAddress AlterTableNamespace ( AlterObjectSchemaStmt stmt,
Oid oldschema 
)

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

14690 {
14691  Relation rel;
14692  Oid relid;
14693  Oid oldNspOid;
14694  Oid nspOid;
14695  RangeVar *newrv;
14696  ObjectAddresses *objsMoved;
14697  ObjectAddress myself;
14698 
14700  stmt->missing_ok ? RVR_MISSING_OK : 0,
14702  (void *) stmt);
14703 
14704  if (!OidIsValid(relid))
14705  {
14706  ereport(NOTICE,
14707  (errmsg("relation \"%s\" does not exist, skipping",
14708  stmt->relation->relname)));
14709  return InvalidObjectAddress;
14710  }
14711 
14712  rel = relation_open(relid, NoLock);
14713 
14714  oldNspOid = RelationGetNamespace(rel);
14715 
14716  /* If it's an owned sequence, disallow moving it by itself. */
14717  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
14718  {
14719  Oid tableId;
14720  int32 colId;
14721 
14722  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
14723  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
14724  ereport(ERROR,
14725  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14726  errmsg("cannot move an owned sequence into another schema"),
14727  errdetail("Sequence \"%s\" is linked to table \"%s\".",
14729  get_rel_name(tableId))));
14730  }
14731 
14732  /* Get and lock schema OID and check its permissions. */
14733  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
14734  nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
14735 
14736  /* common checks on switching namespaces */
14737  CheckSetNamespace(oldNspOid, nspOid);
14738 
14739  objsMoved = new_object_addresses();
14740  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
14741  free_object_addresses(objsMoved);
14742 
14743  ObjectAddressSet(myself, RelationRelationId, relid);
14744 
14745  if (oldschema)
14746  *oldschema = oldNspOid;
14747 
14748  /* close rel, but keep lock until commit */
14749  relation_close(rel, NoLock);
14750 
14751  return myself;
14752 }
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition: pg_depend.c:663
int errcode(int sqlerrcode)
Definition: elog.c:608
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2414
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2709
Form_pg_class rd_rel
Definition: rel.h:84
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
signed int int32
Definition: c.h:347
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
void AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:14760
#define NoLock
Definition: lockdefs.h:34
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:15311
int errdetail(const char *fmt,...)
Definition: elog.c:955
#define RelationGetRelationName(relation)
Definition: rel.h:462
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:228
#define ereport(elevel, rest)
Definition: elog.h:141
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition: namespace.c:2959
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:526
#define NOTICE
Definition: elog.h:37
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define AccessExclusiveLock
Definition: lockdefs.h:45
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:822
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1730
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:420
#define RelationGetNamespace(relation)
Definition: rel.h:469

◆ AlterTableNamespaceInternal()

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

Definition at line 14760 of file tablecmds.c.

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

Referenced by AlterObjectNamespace_oid(), and AlterTableNamespace().

14762 {
14763  Relation classRel;
14764 
14765  Assert(objsMoved != NULL);
14766 
14767  /* OK, modify the pg_class row and pg_depend entry */
14768  classRel = table_open(RelationRelationId, RowExclusiveLock);
14769 
14770  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
14771  nspOid, true, objsMoved);
14772 
14773  /* Fix the table's row type too */
14774  AlterTypeNamespaceInternal(rel->rd_rel->reltype,
14775  nspOid, false, false, objsMoved);
14776 
14777  /* Fix other dependent stuff */
14778  if (rel->rd_rel->relkind == RELKIND_RELATION ||
14779  rel->rd_rel->relkind == RELKIND_MATVIEW ||
14780  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
14781  {
14782  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
14783  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
14784  objsMoved, AccessExclusiveLock);
14785  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
14786  false, objsMoved);
14787  }
14788 
14789  table_close(classRel, RowExclusiveLock);
14790 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:3579
Form_pg_class rd_rel
Definition: rel.h:84
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:14868
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:14913
#define RowExclusiveLock
Definition: lockdefs.h:38
#define Assert(condition)
Definition: c.h:739
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:14798
#define AccessExclusiveLock
Definition: lockdefs.h:45
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:428

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

7911 {
7912  List *newcons;
7913  ListCell *lcon;
7914  List *children;
7915  ListCell *child;
7917 
7918  /* At top level, permission check was done in ATPrepCmd, else do it */
7919  if (recursing)
7921 
7922  /*
7923  * Call AddRelationNewConstraints to do the work, making sure it works on
7924  * a copy of the Constraint so transformExpr can't modify the original. It
7925  * returns a list of cooked constraints.
7926  *
7927  * If the constraint ends up getting merged with a pre-existing one, it's
7928  * omitted from the returned list, which is what we want: we do not need
7929  * to do any validation work. That can only happen at child tables,
7930  * though, since we disallow merging at the top level.
7931  */
7932  newcons = AddRelationNewConstraints(rel, NIL,
7933  list_make1(copyObject(constr)),
7934  recursing | is_readd, /* allow_merge */
7935  !recursing, /* is_local */
7936  is_readd, /* is_internal */
7937  NULL); /* queryString not available
7938  * here */
7939 
7940  /* we don't expect more than one constraint here */
7941  Assert(list_length(newcons) <= 1);
7942 
7943  /* Add each to-be-validated constraint to Phase 3's queue */
7944  foreach(lcon, newcons)
7945  {
7946  CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
7947 
7948  if (!ccon->skip_validation)
7949  {
7950  NewConstraint *newcon;
7951 
7952  newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
7953  newcon->name = ccon->name;
7954  newcon->contype = ccon->contype;
7955  newcon->qual = ccon->expr;
7956 
7957  tab->constraints = lappend(tab->constraints, newcon);
7958  }
7959 
7960  /* Save the actually assigned name if it was defaulted */
7961  if (constr->conname == NULL)
7962  constr->conname = ccon->name;
7963 
7964  ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
7965  }
7966 
7967  /* At this point we must have a locked-down name to use */
7968  Assert(constr->conname != NULL);
7969 
7970  /* Advance command counter in case same table is visited multiple times */
7972 
7973  /*
7974  * If the constraint got merged with an existing constraint, we're done.
7975  * We mustn't recurse to child tables in this case, because they've
7976  * already got the constraint, and visiting them again would lead to an
7977  * incorrect value for coninhcount.
7978  */
7979  if (newcons == NIL)
7980  return address;
7981 
7982  /*
7983  * If adding a NO INHERIT constraint, no need to find our children.
7984  */
7985  if (constr->is_no_inherit)
7986  return address;
7987 
7988  /*
7989  * Propagate to children as appropriate. Unlike most other ALTER
7990  * routines, we have to do this one level of recursion at a time; we can't
7991  * use find_all_inheritors to do it in one pass.
7992  */
7993  children = find_inheritance_children(RelationGetRelid(rel), lockmode);
7994 
7995  /*
7996  * Check if ONLY was specified with ALTER TABLE. If so, allow the
7997  * constraint creation only if there are no children currently. Error out
7998  * otherwise.
7999  */
8000  if (!recurse && children != NIL)
8001  ereport(ERROR,
8002  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8003  errmsg("constraint must be added to child tables too")));
8004 
8005  foreach(child, children)
8006  {
8007  Oid childrelid = lfirst_oid(child);
8008  Relation childrel;
8009  AlteredTableInfo *childtab;
8010 
8011  /* find_inheritance_children already got lock */
8012  childrel = table_open(childrelid, NoLock);
8013  CheckTableNotInUse(childrel, "ALTER TABLE");
8014 
8015  /* Find or create work queue entry for this table */
8016  childtab = ATGetQueueEntry(wqueue, childrel);
8017 
8018  /* Recurse to child */
8019  ATAddCheckConstraint(wqueue, childtab, childrel,
8020  constr, recurse, true, is_readd, lockmode);
8021 
8022  table_close(childrel, NoLock);
8023  }
8024 
8025  return address;
8026 }
#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:2521
char * name
Definition: tablecmds.c:185
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Node * qual
Definition: tablecmds.c:190
int errcode(int sqlerrcode)
Definition: elog.c:608
static ObjectAddress ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *constr, bool recurse, bool recursing, bool is_readd, LOCKMODE lockmode)
Definition: tablecmds.c:7908
char * conname
Definition: parsenodes.h:2152
unsigned int Oid
Definition: postgres_ext.h:31
#define ATT_TABLE
Definition: tablecmds.c:290
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:5352
bool skip_validation
Definition: heap.h:42
ConstrType contype
Definition: heap.h:37
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3445
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
ConstrType contype
Definition: tablecmds.c:186
void * palloc0(Size size)
Definition: mcxt.c:980
void CommandCounterIncrement(void)
Definition: xact.c:1005
bool is_no_inherit
Definition: parsenodes.h:2158
List * find_inheritance_children(Oid parentrelId, LOCKMODE lockmode)
Definition: pg_inherits.c:55
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:822
Oid conoid
Definition: heap.h:38
Node * expr
Definition: heap.h:41
static void ATSimplePermissions(Relation rel, int allowed_targets)
Definition: tablecmds.c:5389
#define copyObject(obj)
Definition: nodes.h:641
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define ATT_FOREIGN_TABLE
Definition: tablecmds.c:295
char * name
Definition: heap.h:39
#define RelationGetRelid(relation)
Definition: rel.h:428
#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 8044 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().

8047 {
8048  Relation pkrel;
8049  int16 pkattnum[INDEX_MAX_KEYS];
8050  int16 fkattnum[INDEX_MAX_KEYS];
8051  Oid pktypoid[INDEX_MAX_KEYS];
8052  Oid fktypoid[INDEX_MAX_KEYS];
8053  Oid opclasses[INDEX_MAX_KEYS];
8054  Oid pfeqoperators[INDEX_MAX_KEYS];
8055  Oid ppeqoperators[INDEX_MAX_KEYS];
8056  Oid ffeqoperators[INDEX_MAX_KEYS];
8057  int i;
8058  int numfks,
8059  numpks;
8060  Oid indexOid;
8061  bool old_check_ok;
8062  ObjectAddress address;
8063  ListCell *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
8064 
8065  /*
8066  * Grab ShareRowExclusiveLock on the pk table, so that someone doesn't
8067  * delete rows out from under us.
8068  */
8069  if (OidIsValid(fkconstraint->old_pktable_oid))
8070  pkrel = table_open(fkconstraint->old_pktable_oid, ShareRowExclusiveLock);
8071  else
8072  pkrel = table_openrv(fkconstraint->pktable, ShareRowExclusiveLock);
8073 
8074  /*
8075  * Validity checks (permission checks wait till we have the column
8076  * numbers)
8077  */
8078  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
8079  {
8080  if (!recurse)
8081  ereport(ERROR,
8082  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8083  errmsg("cannot use ONLY for foreign key on partitioned table \"%s\" referencing relation \"%s\"",
8085  RelationGetRelationName(pkrel))));
8086  if (fkconstraint->skip_validation && !fkconstraint->initially_valid)
8087  ereport(ERROR,
8088  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8089  errmsg("cannot add NOT VALID foreign key on partitioned table \"%s\" referencing relation \"%s\"",
8091  RelationGetRelationName(pkrel)),
8092  errdetail("This feature is not yet supported on partitioned tables.")));
8093  }
8094 
8095  if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
8096  pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
8097  ereport(ERROR,
8098  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8099  errmsg("referenced relation \"%s\" is not a table",
8100  RelationGetRelationName(pkrel))));
8101 
8102  if (!allowSystemTableMods && IsSystemRelation(pkrel))
8103  ereport(ERROR,
8104  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
8105  errmsg("permission denied: \"%s\" is a system catalog",
8106  RelationGetRelationName(pkrel))));
8107 
8108  /*
8109  * References from permanent or unlogged tables to temp tables, and from
8110  * permanent tables to unlogged tables, are disallowed because the
8111  * referenced data can vanish out from under us. References from temp
8112  * tables to any other table type are also disallowed, because other
8113  * backends might need to run the RI triggers on the perm table, but they
8114  * can't reliably see tuples in the local buffers of other backends.
8115  */
8116  switch (rel->rd_rel->relpersistence)
8117  {
8118  case RELPERSISTENCE_PERMANENT:
8119  if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT)
8120  ereport(ERROR,
8121  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8122  errmsg("constraints on permanent tables may reference only permanent tables")));
8123  break;
8124  case RELPERSISTENCE_UNLOGGED:
8125  if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT
8126  && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
8127  ereport(ERROR,
8128  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8129  errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
8130  break;
8131  case RELPERSISTENCE_TEMP:
8132  if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
8133  ereport(ERROR,
8134  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8135  errmsg("constraints on temporary tables may reference only temporary tables")));
8136  if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
8137  ereport(ERROR,
8138  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8139  errmsg("constraints on temporary tables must involve temporary tables of this session")));
8140  break;
8141  }
8142 
8143  /*
8144  * Look up the referencing attributes to make sure they exist, and record
8145  * their attnums and type OIDs.
8146  */
8147  MemSet(pkattnum, 0, sizeof(pkattnum));
8148  MemSet(fkattnum, 0, sizeof(fkattnum));
8149  MemSet(pktypoid, 0, sizeof(pktypoid));
8150  MemSet(fktypoid, 0, sizeof(fktypoid));
8151  MemSet(opclasses, 0, sizeof(opclasses));
8152  MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
8153  MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
8154  MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
8155 
8157  fkconstraint->fk_attrs,
8158  fkattnum, fktypoid);
8159 
8160  /*
8161  * If the attribute list for the referenced table was omitted, lookup the
8162  * definition of the primary key and use it. Otherwise, validate the
8163  * supplied attribute list. In either case, discover the index OID and
8164  * index opclasses, and the attnums and type OIDs of the attributes.
8165  */
8166  if (fkconstraint->pk_attrs == NIL)
8167  {
8168  numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
8169  &fkconstraint->pk_attrs,
8170  pkattnum, pktypoid,
8171  opclasses);
8172  }
8173  else
8174  {
8175  numpks = transformColumnNameList(RelationGetRelid(pkrel),
8176  fkconstraint->pk_attrs,
8177  pkattnum, pktypoid);
8178  /* Look for an index matching the column list */
8179  indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
8180  opclasses);
8181  }
8182 
8183  /*
8184  * Now we can check permissions.
8185  */
8186  checkFkeyPermissions(pkrel, pkattnum, numpks);
8187 
8188  /*
8189  * Check some things for generated columns.
8190  */
8191  for (i = 0; i < numfks; i++)
8192  {
8193  char attgenerated = TupleDescAttr(RelationGetDescr(rel), fkattnum[i] - 1)->attgenerated;
8194 
8195  if (attgenerated)
8196  {
8197  /*
8198  * Check restrictions on UPDATE/DELETE actions, per SQL standard
8199  */
8200  if (fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETNULL ||
8201  fkconstraint->fk_upd_action == FKCONSTR_ACTION_SETDEFAULT ||
8202  fkconstraint->fk_upd_action == FKCONSTR_ACTION_CASCADE)
8203  ereport(ERROR,
8204  (errcode(ERRCODE_SYNTAX_ERROR),
8205  errmsg("invalid %s action for foreign key constraint containing generated column",
8206  "ON UPDATE")));
8207  if (fkconstraint->fk_del_action == FKCONSTR_ACTION_SETNULL ||
8208  fkconstraint->fk_del_action == FKCONSTR_ACTION_SETDEFAULT)
8209  ereport(ERROR,
8210  (errcode(ERRCODE_SYNTAX_ERROR),
8211  errmsg("invalid %s action for foreign key constraint containing generated column",
8212  "ON DELETE")));
8213  }
8214  }
8215 
8216  /*
8217  * Look up the equality operators to use in the constraint.
8218  *
8219  * Note that we have to be careful about the difference between the actual
8220  * PK column type and the opclass' declared input type, which might be
8221  * only binary-compatible with it. The declared opcintype is the right
8222  * thing to probe pg_amop with.
8223  */
8224  if (numfks != numpks)
8225  ereport(ERROR,
8226  (errcode(ERRCODE_INVALID_FOREIGN_KEY),
8227  errmsg("number of referencing and referenced columns for foreign key disagree")));
8228 
8229  /*
8230  * On the strength of a previous constraint, we might avoid scanning
8231  * tables to validate this one. See below.
8232  */
8233  old_check_ok = (fkconstraint->old_conpfeqop != NIL);
8234  Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
8235 
8236  for (i = 0; i < numpks; i++)
8237  {
8238  Oid pktype = pktypoid[i];
8239  Oid fktype = fktypoid[i];
8240  Oid fktyped;
8241  HeapTuple cla_ht;
8242  Form_pg_opclass cla_tup;
8243  Oid amid;
8244  Oid opfamily;
8245  Oid opcintype;
8246  Oid pfeqop;
8247  Oid ppeqop;
8248  Oid ffeqop;
8249  int16 eqstrategy;
8250  Oid pfeqop_right;
8251 
8252  /* We need several fields out of the pg_opclass entry */
8253  cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
8254  if (!HeapTupleIsValid(cla_ht))
8255  elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
8256  cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
8257  amid = cla_tup->opcmethod;
8258  opfamily = cla_tup->opcfamily;
8259  opcintype = cla_tup->opcintype;
8260  ReleaseSysCache(cla_ht);
8261 
8262  /*
8263  * Check it's a btree; currently this can never fail since no other
8264  * index AMs support unique indexes. If we ever did have other types
8265  * of unique indexes, we'd need a way to determine which operator
8266  * strategy number is equality. (Is it reasonable to insist that
8267  * every such index AM use btree's number for equality?)
8268  */
8269  if (amid != BTREE_AM_OID)
8270  elog(ERROR, "only b-tree indexes are supported for foreign keys");
8271  eqstrategy = BTEqualStrategyNumber;
8272 
8273  /*
8274  * There had better be a primary equality operator for the index.
8275  * We'll use it for PK = PK comparisons.
8276  */
8277  ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
8278  eqstrategy);
8279 
8280  if (!OidIsValid(ppeqop))
8281  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
8282  eqstrategy, opcintype, opcintype, opfamily);
8283 
8284  /*
8285  * Are there equality operators that take exactly the FK type? Assume
8286  * we should look through any domain here.
8287  */
8288  fktyped = getBaseType(fktype);
8289 
8290  pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
8291  eqstrategy);
8292  if (OidIsValid(pfeqop))
8293  {
8294  pfeqop_right = fktyped;
8295  ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
8296  eqstrategy);
8297  }
8298  else
8299  {
8300  /* keep compiler quiet */
8301  pfeqop_right = InvalidOid;
8302  ffeqop = InvalidOid;
8303  }
8304 
8305  if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
8306  {
8307  /*
8308  * Otherwise, look for an implicit cast from the FK type to the
8309  * opcintype, and if found, use the primary equality operator.
8310  * This is a bit tricky because opcintype might be a polymorphic
8311  * type such as ANYARRAY or ANYENUM; so what we have to test is
8312  * whether the two actual column types can be concurrently cast to
8313  * that type. (Otherwise, we'd fail to reject combinations such
8314  * as int[] and point[].)
8315  */
8316  Oid input_typeids[2];
8317  Oid target_typeids[2];
8318 
8319  input_typeids[0] = pktype;
8320  input_typeids[1] = fktype;
8321  target_typeids[0] = opcintype;
8322  target_typeids[1] = opcintype;
8323  if (can_coerce_type(2, input_typeids, target_typeids,
8325  {
8326  pfeqop = ffeqop = ppeqop;
8327  pfeqop_right = opcintype;
8328  }
8329  }
8330 
8331  if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
8332  ereport(ERROR,
8333  (errcode(ERRCODE_DATATYPE_MISMATCH),
8334  errmsg("foreign key constraint \"%s\" cannot be implemented",
8335  fkconstraint->conname),
8336  errdetail("Key columns \"%s\" and \"%s\" "
8337  "are of incompatible types: %s and %s.",
8338  strVal(list_nth(fkconstraint->fk_attrs, i)),
8339  strVal(list_nth(fkconstraint->pk_attrs, i)),
8340  format_type_be(fktype),
8341  format_type_be(pktype))));
8342 
8343  if (old_check_ok)
8344  {
8345  /*
8346  * When a pfeqop changes, revalidate the constraint. We could
8347  * permit intra-opfamily changes, but that adds subtle complexity
8348  * without any concrete benefit for core types. We need not
8349  * assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
8350  */
8351  old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
8352  old_pfeqop_item = lnext(fkconstraint->old_conpfeqop,
8353  old_pfeqop_item);
8354  }
8355  if (old_check_ok)
8356  {
8357  Oid old_fktype;
8358  Oid new_fktype;
8359  CoercionPathType old_pathtype;
8360  CoercionPathType new_pathtype;
8361  Oid old_castfunc;
8362  Oid new_castfunc;
8364  fkattnum[i] - 1);
8365 
8366  /*
8367  * Identify coercion pathways from each of the old and new FK-side
8368  * column types to the right (foreign) operand type of the pfeqop.
8369  * We may assume that pg_constraint.conkey is not changing.
8370  */
8371  old_fktype = attr->atttypid;
8372  new_fktype = fktype;
8373  old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
8374  &old_castfunc);
8375  new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
8376  &new_castfunc);
8377 
8378  /*
8379  * Upon a change to the cast from the FK column to its pfeqop
8380  * operand, revalidate the constraint. For this evaluation, a
8381  * binary coercion cast is equivalent to no cast at all. While
8382  * type implementors should design implicit casts with an eye
8383  * toward consistency of operations like equality, we cannot
8384  * assume here that they have done so.
8385  *
8386  * A function with a polymorphic argument could change behavior
8387  * arbitrarily in response to get_fn_expr_argtype(). Therefore,
8388  * when the cast destination is polymorphic, we only avoid
8389  * revalidation if the input type has not changed at all. Given
8390  * just the core data types and operator classes, this requirement
8391  * prevents no would-be optimizations.
8392  *
8393  * If the cast converts from a base type to a domain thereon, then
8394  * that domain type must be the opcintype of the unique index.
8395  * Necessarily, the primary key column must then be of the domain
8396  * type. Since the constraint was previously valid, all values on
8397  * the foreign side necessarily exist on the primary side and in
8398  * turn conform to the domain. Consequently, we need not treat
8399  * domains specially here.
8400  *
8401  * Since we require that all collations share the same notion of
8402  * equality (which they do, because texteq reduces to bitwise
8403  * equality), we don't compare collation here.
8404  *
8405  * We need not directly consider the PK type. It's necessarily
8406  * binary coercible to the opcintype of the unique index column,
8407  * and ri_triggers.c will only deal with PK datums in terms of
8408  * that opcintype. Changing the opcintype also changes pfeqop.
8409  */
8410  old_check_ok = (new_pathtype == old_pathtype &&
8411  new_castfunc == old_castfunc &&
8412  (!IsPolymorphicType(pfeqop_right) ||
8413  new_fktype == old_fktype));
8414  }
8415 
8416  pfeqoperators[i] = pfeqop;
8417  ppeqoperators[i] = ppeqop;
8418  ffeqoperators[i] = ffeqop;
8419  }
8420 
8421  /*
8422  * Create all the constraint and trigger objects, recursing to partitions
8423  * as necessary. First handle the referenced side.
8424  */
8425  address = addFkRecurseReferenced(wqueue, fkconstraint, rel, pkrel,
8426  indexOid,
8427  InvalidOid, /* no parent constraint */
8428  numfks,
8429  pkattnum,
8430  fkattnum,
8431  pfeqoperators,
8432  ppeqoperators,
8433  ffeqoperators,
8434  old_check_ok);
8435 
8436  /* Now handle the referencing side. */
8437  addFkRecurseReferencing(wqueue, fkconstraint, rel, pkrel,
8438  indexOid,
8439  address.objectId,
8440  numfks,
8441  pkattnum,
8442  fkattnum,
8443  pfeqoperators,
8444  ppeqoperators,
8445  ffeqoperators,
8446  old_check_ok,
8447  lockmode);
8448 
8449  /*
8450  * Done. Close pk table, but keep lock until we've committed.
8451  */
8452  table_close(pkrel, NoLock);
8453 
8454  return address;
8455 }
signed short int16
Definition: c.h:346
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
List * old_conpfeqop
Definition: parsenodes.h:2189
bool IsSystemRelation(Relation relation)
Definition: catalog.c:69
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
#define RelationGetDescr(relation)
Definition: rel.h:454
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:8688
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:543
#define FKCONSTR_ACTION_SETDEFAULT
Definition: parsenodes.h:2139
static int transformColumnNameList(Oid relId, List *colList, int16 *attnums, Oid *atttypids)
Definition: tablecmds.c:9743
bool rd_islocaltemp
Definition: rel.h:60
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:608
#define MemSet(start, val, len)
Definition: c.h:962
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
List * pk_attrs
Definition: parsenodes.h:2185
char * conname
Definition: parsenodes.h:2152
Form_pg_class rd_rel
Definition: rel.h:84
unsigned int Oid
Definition: postgres_ext.h:31
static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
Definition: tablecmds.c:10055
#define OidIsValid(objectId)
Definition: c.h:645
CoercionPathType
Definition: parse_coerce.h:24
static ObjectAddress addFkRecurseReferenced(List **wqueue, Constraint *fkconstraint, Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr, int numfks, int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators, bool old_check_ok)
Definition: tablecmds.c:8483
#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:955
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:163
#define RelationGetRelationName(relation)
Definition: rel.h:462
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
#define ereport(elevel, rest)
Definition: elog.h:141
Oid old_pktable_oid
Definition: parsenodes.h:2190
#define FKCONSTR_ACTION_CASCADE
Definition: parsenodes.h:2137
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:2195
static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid, List **attnamelist, int16 *attnums, Oid *atttypids, Oid *opclasses)
Definition: tablecmds.c:9788
char fk_del_action
Definition: parsenodes.h:2188
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:739
#define ShareRowExclusiveLock
Definition: lockdefs.h:42
static CoercionPathType findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
Definition: tablecmds.c:10026
#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:9885
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
int i
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
RangeVar * pktable
Definition: parsenodes.h:2183
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2299
#define FKCONSTR_ACTION_SETNULL
Definition: parsenodes.h:2138
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
bool skip_validation
Definition: parsenodes.h:2194
#define RelationGetRelid(relation)
Definition: rel.h:428
List * fk_attrs
Definition: parsenodes.h:2184
#define BTEqualStrategyNumber
Definition: stratnum.h:31
char fk_upd_action
Definition: parsenodes.h:2187
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ ATCheckPartitionsNotInUse()

static void ATCheckPartitionsNotInUse ( Relation  rel,
LOCKMODE  lockmode 
)
static

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

5557 {
5558  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
5559  {
5560  List *inh;
5561  ListCell *cell;
5562 
5563  inh = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
5564  /* first element is the parent rel; must ignore it */
5565  for_each_cell(cell, inh, list_second_cell(inh))
5566  {
5567  Relation childrel;
5568 
5569  /* find_all_inheritors already got lock */
5570  childrel = table_open(lfirst_oid(cell), NoLock);
5571  CheckTableNotInUse(childrel, "ALTER TABLE");
5572  table_close(childrel, NoLock);
5573  }
5574  list_free(inh);
5575  }
5576 }
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:84
#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:3445
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:165
void list_free(List *list)
Definition: list.c:1377
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:428
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ ATColumnChangeRequiresRewrite()

static bool ATColumnChangeRequiresRewrite ( Node expr,
AttrNumber  varattno 
)
static

Definition at line 10982 of file tablecmds.c.

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

Referenced by ATPrepAlterColumnType().

10983 {
10984  Assert(expr != NULL);
10985 
10986  for (;;)
10987  {
10988  /* only one varno, so no need to check that */
10989  if (IsA(expr, Var) &&((Var *) expr)->varattno == varattno)
10990  return false;
10991  else if (IsA(expr, RelabelType))
10992  expr = (Node *) ((RelabelType *) expr)->arg;
10993  else if (IsA(expr, CoerceToDomain))
10994  {
10995  CoerceToDomain *d = (CoerceToDomain *) expr;
10996 
10998  return true;
10999  expr = (Node *) d->arg;
11000  }
11001  else if (IsA(expr, FuncExpr))
11002  {
11003  FuncExpr *f = (FuncExpr *) expr;
11004 
11005  switch (f->funcid)
11006  {
11007  case F_TIMESTAMPTZ_TIMESTAMP:
11008  case F_TIMESTAMP_TIMESTAMPTZ:
11010  return true;
11011  else
11012  expr = linitial(f->args);
11013  break;
11014  default:
11015  return true;
11016  }
11017  }
11018  else
11019  return true;
11020  }
11021 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
List * args
Definition: primnodes.h:477
Definition: nodes.h:525
Definition: primnodes.h:181
bool DomainHasConstraints(Oid type_id)
Definition: typcache.c:1289
#define linitial(l)
Definition: pg_list.h:195
Oid funcid
Definition: primnodes.h:469
#define Assert(condition)
Definition: c.h:739
void * arg
bool TimestampTimestampTzRequiresRewrite(void)
Definition: timestamp.c:5161

◆ ATController()

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

Definition at line 3864 of file tablecmds.c.

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

Referenced by AlterTable(), and AlterTableInternal().

3867 {
3868  List *wqueue = NIL;
3869  ListCell *lcmd;
3870 
3871  /* Phase 1: preliminary examination of commands, create work queue */
3872  foreach(lcmd, cmds)
3873  {
3874  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3875 
3876  ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode, context);
3877  }
3878 
3879  /* Close the relation, but keep lock until commit */
3880  relation_close(rel, NoLock);
3881 
3882  /* Phase 2: update system catalogs */
3883  ATRewriteCatalogs(&wqueue, lockmode, context);
3884 
3885  /* Phase 3: scan/rewrite tables as needed, and run afterStmts */
3886  ATRewriteTables(parsetree, &wqueue, lockmode, context);
3887 }
#define NIL
Definition: pg_list.h:65
static void ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:4729
#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:3899
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:4221
Definition: pg_list.h:50

◆ ATDetachCheckNoForeignKeyRefs()

static void ATDetachCheckNoForeignKeyRefs ( Relation  partition)
static

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

17180 {
17181  List *constraints;
17182  ListCell *cell;
17183 
17184  constraints = GetParentedForeignKeyRefs(partition);
17185 
17186  foreach(cell, constraints)
17187  {
17188  Oid constrOid = lfirst_oid(cell);
17189  HeapTuple tuple;
17190  Form_pg_constraint constrForm;
17191  Relation rel;
17192  Trigger trig;
17193 
17194  tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
17195  if (!HeapTupleIsValid(tuple))
17196  elog(ERROR, "cache lookup failed for constraint %u", constrOid);
17197  constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
17198 
17199  Assert(OidIsValid(constrForm->conparentid));
17200  Assert(constrForm->confrelid == RelationGetRelid(partition));
17201 
17202  /* prevent data changes into the referencing table until commit */
17203  rel = table_open(constrForm->conrelid, ShareLock);
17204 
17205  MemSet(&trig, 0, sizeof(trig));
17206  trig.tgoid = InvalidOid;
17207  trig.tgname = NameStr(constrForm->conname);
17209  trig.tgisinternal = true;
17210  trig.tgconstrrelid = RelationGetRelid(partition);
17211  trig.tgconstrindid = constrForm->conindid;
17212  trig.tgconstraint = constrForm->oid;
17213  trig.tgdeferrable = false;
17214  trig.tginitdeferred = false;
17215  /* we needn't fill in remaining fields */
17216 
17217  RI_PartitionRemove_Check(&trig, rel, partition);
17218 
17219  ReleaseSysCache(tuple);
17220 
17221  table_close(rel, NoLock);
17222  }
17223 }
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:17126
Oid tgoid
Definition: reltrigger.h:25
bool tgisinternal
Definition: reltrigger.h:31
#define MemSet(start, val, len)
Definition: c.h:962
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
#define TRIGGER_FIRES_ON_ORIGIN
Definition: trigger.h:155
char tgenabled
Definition: reltrigger.h:30
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Oid tgconstraint
Definition: reltrigger.h:34
char * tgname
Definition: reltrigger.h:27
void RI_PartitionRemove_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
Definition: ri_triggers.c:1570
bool tgdeferrable
Definition: reltrigger.h:35
bool tginitdeferred
Definition: reltrigger.h:36
#define NoLock
Definition: lockdefs.h:34
Oid tgconstrrelid
Definition: reltrigger.h:32
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define InvalidOid
Definition: postgres_ext.h:36
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:739
Oid tgconstrindid
Definition: reltrigger.h:33
#define elog(elevel,...)
Definition: elog.h:228
#define ShareLock
Definition: lockdefs.h:41
#define NameStr(name)
Definition: c.h:616
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:428
#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 15189 of file tablecmds.c.

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

15191 {
15192  ListCell *cur_item;
15193 
15194  foreach(cur_item, on_commits)
15195  {
15196  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
15197 
15198  if (!isCommit && oc->creating_subid == mySubid)
15199  {
15200  /* cur_item must be removed */
15202  pfree(oc);
15203  }
15204  else
15205  {
15206  /* cur_item must be preserved */
15207  if (oc->creating_subid == mySubid)
15208  oc->creating_subid = parentSubid;
15209  if (oc->deleting_subid == mySubid)
15210  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
15211  }
15212  }
15213 }
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:520

◆ AtEOXact_on_commit_actions()

void AtEOXact_on_commit_actions ( bool  isCommit)

Definition at line 15157 of file tablecmds.c.

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

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

15158 {
15159  ListCell *cur_item;
15160 
15161  foreach(cur_item, on_commits)
15162  {
15163  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
15164 
15165  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
15167  {
15168  /* cur_item must be removed */
15170  pfree(oc);
15171  }
15172  else
15173  {
15174  /* cur_item must be preserved */
15177  }
15178  }
15179 }
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:520

◆ 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 5865 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(), relkind, relnatts, RELOID, AlteredTableInfo::rewrite, RowExclusiveLock, SearchSysCacheCopy1, SearchSysCacheCopyAttName(), NextValueExpr::seqid, HeapTupleData::t_self, table_close(), table_open(), TupleDescAttr, NextValueExpr::typeId, ColumnDef::typeName, typenameType(), typenameTypeIdAndMod(), and AlteredTableInfo::verify_new_notnull.

Referenced by ATExecCmd().

5870 {
5871  Oid myrelid = RelationGetRelid(rel);
5872  ColumnDef *colDef = castNode(ColumnDef, (*cmd)->def);
5873  bool if_not_exists = (*cmd)->missing_ok;
5874  Relation pgclass,
5875  attrdesc;
5876  HeapTuple reltup;
5877  FormData_pg_attribute attribute;
5878  int newattnum;
5879  char relkind;
5880  HeapTuple typeTuple;
5881  Oid typeOid;
5882  int32 typmod;
5883  Oid collOid;
5884  Form_pg_type tform;
5885  Expr *defval;
5886  List *children;
5887  ListCell *child;
5888  AlterTableCmd *childcmd;
5889  AclResult aclresult;
5890  ObjectAddress address;
5891 
5892  /* At top level, permission check was done in ATPrepCmd, else do it */
5893  if (recursing)
5895 
5896  if (rel->rd_rel->relispartition && !recursing)
5897  ereport(ERROR,
5898  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5899  errmsg("cannot add column to a partition")));
5900 
5901  attrdesc = table_open(AttributeRelationId, RowExclusiveLock);
5902 
5903  /*
5904  * Are we adding the column to a recursion child? If so, check whether to
5905  * merge with an existing definition for the column. If we do merge, we
5906  * must not recurse. Children will already have the column, and recursing
5907  * into them would mess up attinhcount.
5908  */
5909  if (colDef->inhcount > 0)
5910  {
5911  HeapTuple tuple;
5912 
5913  /* Does child already have a column by this name? */
5914  tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
5915  if (HeapTupleIsValid(tuple))
5916  {
5917  Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
5918  Oid ctypeId;
5919  int32 ctypmod;
5920  Oid ccollid;
5921 
5922  /* Child column must match on type, typmod, and collation */
5923  typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
5924  if (ctypeId != childatt->atttypid ||
5925  ctypmod != childatt->atttypmod)
5926  ereport(ERROR,
5927  (errcode(ERRCODE_DATATYPE_MISMATCH),
5928  errmsg("child table \"%s\" has different type for column \"%s\"",
5929  RelationGetRelationName(rel), colDef->colname)));
5930  ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
5931  if (ccollid != childatt->attcollation)
5932  ereport(ERROR,
5933  (errcode(ERRCODE_COLLATION_MISMATCH),
5934  errmsg("child table \"%s\" has different collation for column \"%s\"",
5935  RelationGetRelationName(rel), colDef->colname),
5936  errdetail("\"%s\" versus \"%s\"",
5937  get_collation_name(ccollid),
5938  get_collation_name(childatt->attcollation))));
5939 
5940  /* Bump the existing child att's inhcount */
5941  childatt->attinhcount++;
5942  CatalogTupleUpdate(attrdesc, &tuple->t_self, tuple);
5943 
5944  heap_freetuple(tuple);
5945 
5946  /* Inform the user about the merge */
5947  ereport(NOTICE,
5948  (errmsg("merging definition of column \"%s\" for child \"%s\"",
5949  colDef->colname, RelationGetRelationName(rel))));
5950 
5951  table_close(attrdesc, RowExclusiveLock);
5952  return InvalidObjectAddress;
5953  }
5954  }
5955 
5956  /* skip if the name already exists and if_not_exists is true */
5957  if (!check_for_column_name_collision(rel, colDef->colname, if_not_exists))
5958  {
5959  table_close(attrdesc, RowExclusiveLock);
5960  return InvalidObjectAddress;
5961  }
5962 
5963  /*
5964  * Okay, we need to add the column, so go ahead and do parse
5965  * transformation. This can result in queueing up, or even immediately
5966  * executing, subsidiary operations (such as creation of unique indexes);
5967  * so we mustn't do it until we have made the if_not_exists check.
5968  *
5969  * When recursing, the command was already transformed and we needn't do
5970  * so again. Also, if context isn't given we can't transform. (That
5971  * currently happens only for AT_AddColumnToView; we expect that view.c
5972  * passed us a ColumnDef that doesn't need work.)
5973  */
5974  if (context != NULL && !recursing)
5975  {
5976  *cmd = ATParseTransformCmd(wqueue, tab, rel, *cmd, recurse, lockmode,
5977  cur_pass, context);
5978  Assert(*cmd != NULL);
5979  colDef = castNode(ColumnDef, (*cmd)->def);
5980  }
5981 
5982  /*
5983  * Cannot add identity column if table has children, because identity does
5984  * not inherit. (Adding column and identity separately will work.)
5985  */
5986  if (colDef->identity &&
5987  recurse &&
5988  find_inheritance_children(myrelid, NoLock) != NIL)
5989  ereport(ERROR,
5990  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5991  errmsg("cannot recursively add identity column to table that has child tables")));
5992 
5993  pgclass = table_open(RelationRelationId, RowExclusiveLock);
5994 
5995  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
5996  if (!HeapTupleIsValid(reltup))
5997  elog(ERROR, "cache lookup failed for relation %u", myrelid);
5998  relkind = ((Form_pg_class) GETSTRUCT(reltup))->relkind;
5999 
6000  /* Determine the new attribute's number */
6001  newattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts + 1;
6002  if (newattnum > MaxHeapAttributeNumber)
6003  ereport(ERROR,
6004  (errcode(ERRCODE_TOO_MANY_COLUMNS),
6005  errmsg("tables can have at most %d columns",
6007 
6008  typeTuple = typenameType(NULL, colDef->typeName, &typmod);
6009  tform = (Form_pg_type) GETSTRUCT(typeTuple);
6010  typeOid = tform->oid;
6011 
6012  aclresult = pg_type_aclcheck(typeOid, GetUserId(), ACL_USAGE);
6013  if (aclresult != ACLCHECK_OK)
6014  aclcheck_error_type(aclresult, typeOid);
6015 
6016  collOid = GetColumnDefCollation(NULL, colDef, typeOid);
6017 
6018  /* make sure datatype is legal for a column */
6019  CheckAttributeType(colDef->colname, typeOid, collOid,
6020  list_make1_oid(rel->rd_rel->reltype),
6021  0);
6022 
6023  /* construct new attribute's pg_attribute entry */
6024  attribute.attrelid = myrelid;
6025  namestrcpy(&(attribute.attname), colDef->colname);
6026  attribute.atttypid = typeOid;
6027  attribute.attstattarget = (newattnum > 0) ? -1 : 0;
6028  attribute.attlen = tform->typlen;
6029  attribute.atttypmod = typmod;
6030  attribute.attnum = newattnum;
6031  attribute.attbyval = tform->typbyval;
6032  attribute.attndims = list_length(colDef->typeName->arrayBounds);
6033  attribute.attstorage = tform->typstorage;
6034  attribute.attalign = tform->typalign;
6035  attribute.attnotnull = colDef->is_not_null;
6036  attribute.atthasdef = false;
6037  attribute.atthasmissing = false;
6038  attribute.attidentity = colDef->identity;
6039  attribute.attgenerated = colDef->generated;
6040  attribute.attisdropped = false;
6041  attribute.attislocal = colDef->is_local;
6042  attribute.attinhcount = colDef->inhcount;
6043  attribute.attcollation = collOid;
6044  /* attribute.attacl is handled by InsertPgAttributeTuple */
6045 
6046  ReleaseSysCache(typeTuple);
6047 
6048  InsertPgAttributeTuple(attrdesc, &attribute, NULL);
6049 
6050  table_close(attrdesc, RowExclusiveLock);
6051 
6052  /*
6053  * Update pg_class tuple as appropriate
6054  */
6055  ((Form_pg_class) GETSTRUCT(reltup))->relnatts = newattnum;
6056 
6057  CatalogTupleUpdate(pgclass, &reltup->t_self, reltup);
6058 
6059  heap_freetuple(reltup);
6060 
6061  /* Post creation hook for new attribute */
6062  InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
6063 
6064  table_close(pgclass, RowExclusiveLock);
6065 
6066  /* Make the attribute's catalog entry visible */
6068 
6069  /*
6070  * Store the DEFAULT, if any, in the catalogs
6071  */
6072  if (colDef->raw_default)
6073  {
6074  RawColumnDefault *rawEnt;
6075 
6076  rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
6077  rawEnt->attnum = attribute.attnum;
6078  rawEnt->raw_default = copyObject(colDef->raw_default);
6079 
6080  /*
6081  * Attempt to skip a complete table rewrite by storing the specified
6082  * DEFAULT value outside of the heap. This may be disabled inside
6083  * AddRelationNewConstraints if the optimization cannot be applied.
6084  */
6085  rawEnt->missingMode = (!colDef->generated);
6086 
6087  rawEnt->generated = colDef->generated;
6088 
6089  /*
6090  * This function is intended for CREATE TABLE, so it processes a
6091  * _list_ of defaults, but we just do one.
6092  */
6094  false, true, false, NULL);
6095 
6096  /* Make the additional catalog changes visible */
6098 
6099  /*
6100  * Did the request for a missing value work? If not we'll have to do a
6101  * rewrite
6102  */
6103  if (!rawEnt->missingMode)
6105  }
6106 
6107  /*
6108  * Tell Phase 3 to fill in the default expression, if there is one.
6109  *
6110  * If there is no default, Phase 3 doesn't have to do anything, because
6111  * that effectively means that the default is NULL. The heap tuple access
6112  * routines always check for attnum > # of attributes in tuple, and return
6113  * NULL if so, so without any modification of the tuple data we will get
6114  * the effect of NULL values in the new column.
6115  *
6116  * An exception occurs when the new column is of a domain type: the domain
6117  * might have a NOT NULL constraint, or a check constraint that indirectly
6118  * rejects nulls. If there are any domain constraints then we construct
6119  * an explicit NULL default value that will be passed through
6120  * CoerceToDomain processing. (This is a tad inefficient, since it causes
6121  * rewriting the table which we really don't have to do, but the present
6122  * design of domain processing doesn't offer any simple way of checking
6123  * the constraints more directly.)
6124  *
6125  * Note: we use build_column_default, and not just the cooked default
6126  * returned by AddRelationNewConstraints, so that the right thing happens
6127  * when a datatype's default applies.
6128  *
6129  * We skip this step completely for views and foreign tables. For a view,
6130  * we can only get here from CREATE OR REPLACE VIEW, which historically
6131  * doesn't set up defaults, not even for domain-typed columns. And in any
6132  * case we mustn't invoke Phase 3 on a view or foreign table, since they
6133  * have no storage.
6134  */
6135  if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE
6136  && relkind != RELKIND_FOREIGN_TABLE && attribute.attnum > 0)
6137  {
6138  /*
6139  * For an identity column, we can't use build_column_default(),
6140  * because the sequence ownership isn't set yet. So do it manually.
6141  */
6142  if (colDef->identity)
6143  {
6145 
6146  nve->seqid = RangeVarGetRelid(colDef->identitySequence, NoLock, false);
6147  nve->typeId = typeOid;
6148 
6149  defval = (Expr *) nve;
6150 
6151  /* must do a rewrite for identity columns */
6153  }
6154  else
6155  defval = (Expr *) build_column_default(rel, attribute.attnum);
6156 
6157  if (!defval && DomainHasConstraints(typeOid))
6158  {
6159  Oid baseTypeId;
6160  int32 baseTypeMod;
6161  Oid baseTypeColl;
6162 
6163  baseTypeMod = typmod;
6164  baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
6165  baseTypeColl = get_typcollation(baseTypeId);
6166  defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
6167  defval = (Expr *) coerce_to_target_type(NULL,
6168  (Node *) defval,
6169  baseTypeId,
6170  typeOid,
6171  typmod,
6174  -1);
6175  if (defval == NULL) /* should not happen */
6176  elog(ERROR, "failed to coerce base type to domain");
6177  }
6178 
6179  if (defval)
6180  {
6182 
6183  newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
6184  newval->attnum = attribute.attnum;
6185  newval->expr = expression_planner(defval);
6186  newval->is_generated = (colDef->generated != '\0');
6187 
6188  tab->newvals = lappend(tab->newvals, newval);
6189  }
6190 
6191  if (DomainHasConstraints(typeOid))
6193 
6194  if (!TupleDescAttr(rel->rd_att, attribute.attnum - 1)->atthasmissing)
6195  {
6196  /*
6197  * If the new column is NOT NULL, and there is no missing value,
6198  * tell Phase 3 it needs to check for NULLs.
6199  */
6200  tab->verify_new_notnull |= colDef->is_not_null;
6201  }
6202  }
6203 
6204  /*
6205  * Add needed dependency entries for the new column.
6206  */
6207  add_column_datatype_dependency(myrelid, newattnum, attribute.atttypid);
6208  add_column_collation_dependency(myrelid, newattnum, attribute.attcollation);
6209 
6210  /*
6211  * Propagate to children as appropriate. Unlike most other ALTER
6212  * routines, we have to do this one level of recursion at a time; we can't
6213  * use find_all_inheritors to do it in one pass.
6214  */
6215  children = find_inheritance_children(RelationGetRelid(rel), lockmode);
6216 
6217  /*
6218  * If we are told not to recurse, there had better not be any child
6219  * tables; else the addition would put them out of step.
6220  */
6221  if (children && !recurse)
6222  ereport(ERROR,
6223  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6224  errmsg("column must be added to child tables too")));
6225 
6226  /* Children should see column as singly inherited */
6227  if (!recursing)
6228  {
6229  childcmd = copyObject(*cmd);
6230  colDef = castNode(ColumnDef, childcmd->def);
6231  colDef->inhcount = 1;
6232  colDef->is_local = false;
6233  }
6234  else
6235  childcmd = *cmd; /* no need to copy again */
6236 
6237  foreach(child, children)
6238  {
6239  Oid childrelid = lfirst_oid(child);
6240  Relation childrel;
6241  AlteredTableInfo *childtab;
6242 
6243  /* find_inheritance_children already got lock */
6244  childrel = table_open(childrelid, NoLock);
6245  CheckTableNotInUse(childrel, "ALTER TABLE");
6246 
6247  /* Find or create work queue entry for this table */
6248  childtab = ATGetQueueEntry(wqueue, childrel);
6249 
6250  /* Recurse to child; return value is ignored */
6251  ATExecAddColumn(wqueue, childtab, childrel,
6252  &childcmd, recurse, true,
6253  lockmode, cur_pass, context);
6254 
6255  table_close(childrel, NoLock);
6256  }
6257 
6258  ObjectAddressSubSet(address, RelationRelationId, myrelid, newattnum);
6259  return address;
6260 }
#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:2521
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2316
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:264
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:151
AttrNumber attnum
Definition: heap.h:29
bool is_local
Definition: parsenodes.h:649
Oid GetUserId(void)
Definition: miscinit.c:380
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
char identity
Definition: parsenodes.h:655
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:63
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
char * get_collation_name(Oid colloid)
Definition: lsyscache.c:923
Expr * expression_planner(Expr *expr)
Definition: planner.c:6051
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
char generated
Definition: parsenodes.h:658
bool is_not_null
Definition: parsenodes.h:650
Form_pg_class rd_rel
Definition: rel.h:84
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define ATT_TABLE
Definition: tablecmds.c:290
int namestrcpy(Name name, const char *str)
Definition: name.c:250
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3665
char relkind
Definition: pg_class.h:81
signed int int32
Definition: c.h:347
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:335
bool DomainHasConstraints(Oid type_id)
Definition: typcache.c:1289
#define list_make1(x1)
Definition: pg_list.h:227
RangeVar * identitySequence
Definition: parsenodes.h:656
#define AT_REWRITE_DEFAULT_VAL
Definition: event_trigger.h:32
static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
Definition: tablecmds.c:6320
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
HeapTuple SearchSysCacheCopyAttName(Oid relid, const char *attname)
Definition: syscache.c:1280
ItemPointerData t_self
Definition: htup.h:65
static void add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
Definition: tablecmds.c:6338
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:955
char generated
Definition: heap.h:32
#define RelationGetRelationName(relation)
Definition: rel.h:462
static AlteredTableInfo * ATGetQueueEntry(List **wqueue, Relation rel)
Definition: tablecmds.c:5352
Node * raw_default
Definition: heap.h:30
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
#define ACL_USAGE
Definition: parsenodes.h:82
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3445
#define ereport(elevel, rest)
Definition: elog.h:141
bool verify_new_notnull
Definition: tablecmds.c:166
Node * raw_default
Definition: parsenodes.h:653
List * lappend(List *list, void *datum)
Definition: list.c:322
int16 relnatts
Definition: pg_class.h:84
Oid GetColumnDefCollation(ParseState *pstate, ColumnDef *coldef, Oid typeOid)
Definition: parse_type.c:538
Node * build_column_default(Relation rel, int attrno)
void * palloc0(Size size)
Definition: mcxt.c:980
AclResult
Definition: acl.h:177
void CommandCounterIncrement(void)
Definition: xact.c:1005
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define list_make1_oid(x1)
Definition: pg_list.h:249
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:5865
TupleDesc rd_att
Definition: rel.h:85
void typenameTypeIdAndMod(ParseState *pstate, const TypeName *typeName, Oid *typeid_p, int32 *typmod_p)
Definition: parse_type.c:310
FormData_pg_attribute
Definition: pg_attribute.h:184
List * find_inheritance_children(Oid parentrelId, LOCKMODE lockmode)
Definition: pg_inherits.c:55
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2823
#define NOTICE
Definition: elog.h:37
#define MaxHeapAttributeNumber
Definition: htup_details.h:47
#define makeNode(_type_)
Definition: nodes.h:573
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:739
static AlterTableCmd * ATParseTransformCmd(List **wqueue, AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode, int cur_pass, AlterTableUtilityContext *context)
Definition: tablecmds.c:4607
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
FormData_pg_type * Form_pg_type
Definition: pg_type.h:250
static int list_length(const List *l)
Definition: pg_list.h:169
bool is_generated
Definition: tablecmds.c:207
#define newval
TypeName * typeName
Definition: parsenodes.h:647
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
List * arrayBounds
Definition: parsenodes.h:215
void InsertPgAttributeTuple(Relation pg_attribute_rel, Form_pg_attribute new_attribute, CatalogIndexState indstate)
Definition: heap.c:725
const ObjectAddress InvalidObjectAddress
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:822
static bool check_for_column_name_collision(Relation rel, const char *colname, bool if_not_exists)
Definition: tablecmds.c:6267
#define elog(elevel,...)
Definition: elog.h:228
int inhcount
Definition: parsenodes.h:648
static void ATSimplePermissions(Relation rel, int allowed_targets)
Definition: tablecmds.c:5389
char * colname
Definition: parsenodes.h:646
#define copyObject(obj)
Definition: nodes.h:641
void CheckAttributeType(const char *attname, Oid atttypid, Oid attcollation, List *containing_rowtypes, int flags)
Definition: heap.c:581
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4741
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define ATT_FOREIGN_TABLE
Definition: tablecmds.c:295
#define RelationGetRelid(relation)
Definition: rel.h:428
#define lfirst_oid(lc)
Definition: pg_list.h:192
AttrNumber attnum
Definition: tablecmds.c:204

◆ ATExecAddConstraint()

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

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

7796 {
7798 
7799  Assert(IsA(newConstraint, Constraint));
7800 
7801  /*
7802  * Currently, we only expect to see CONSTR_CHECK and CONSTR_FOREIGN nodes
7803  * arriving here (see the preprocessing done in parse_utilcmd.c). Use a
7804  * switch anyway to make it easier to add more code later.
7805  */
7806  switch (newConstraint->contype)
7807  {
7808  case CONSTR_CHECK:
7809  address =
7810  ATAddCheckConstraint(wqueue, tab, rel,
7811  newConstraint, recurse, false, is_readd,
7812  lockmode);
7813  break;
7814 
7815  case CONSTR_FOREIGN:
7816 
7817  /*
7818  * Assign or validate constraint name
7819  */
7820  if (newConstraint->conname)
7821  {
7823  RelationGetRelid(rel),
7824  newConstraint->conname))
7825  ereport(ERROR,
7827  errmsg("constraint \"%s\" for relation \"%s\" already exists",
7828  newConstraint->conname,
7829  RelationGetRelationName(rel))));
7830  }
7831  else
7832  newConstraint->conname =
7835  "fkey",
7836  RelationGetNamespace(rel),
7837  NIL);
7838 
7839  address = ATAddForeignKeyConstraint(wqueue, tab, rel,
7840  newConstraint, InvalidOid,
7841  recurse, false,
7842  lockmode);
7843  break;
7844 
7845  default:
7846  elog(ERROR, "unrecognized constraint type: %d",
7847  (int) newConstraint->contype);
7848  }
7849 
7850  return address;
7851 }
#define NIL
Definition: pg_list.h:65
char * ChooseConstraintName(const char *name1, const char *name2, const char *label, Oid namespaceid, List *others)
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
bool ConstraintNameIsUsed(ConstraintCategory conCat, Oid objId, const char *conname)
static char * ChooseForeignKeyConstraintNameAddition(List *colnames)
Definition: tablecmds.c:7866
int errcode(int sqlerrcode)
Definition: elog.c:608
static ObjectAddress ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *constr, bool recurse, bool recursing, bool is_readd, LOCKMODE lockmode)
Definition: tablecmds.c:7908
char * conname
Definition: parsenodes.h:2152
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:462
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:739
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
static ObjectAddress ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *fkconstraint, Oid parentConstr, bool recurse, bool recursing, LOCKMODE lockmode)
Definition: tablecmds.c:8044
ConstrType contype
Definition: parsenodes.h:2149
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:31
#define RelationGetRelid(relation)
Definition: rel.h:428
List * fk_attrs
Definition: parsenodes.h:2184
#define RelationGetNamespace(relation)
Definition: rel.h:469

◆ ATExecAddIdentity()

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

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

6775 {
6776  Relation attrelation;
6777  HeapTuple tuple;
6778  Form_pg_attribute attTup;
6780  ObjectAddress address;
6781  ColumnDef *cdef = castNode(ColumnDef, def);
6782 
6783  attrelation = table_open(AttributeRelationId, RowExclusiveLock);
6784 
6785  tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
6786  if (!HeapTupleIsValid(tuple))
6787  ereport(ERROR,
6788  (errcode(ERRCODE_UNDEFINED_COLUMN),
6789  errmsg("column \"%s\" of relation \"%s\" does not exist",
6790  colName, RelationGetRelationName(rel))));
6791  attTup = (Form_pg_attribute) GETSTRUCT(tuple);
6792  attnum = attTup->attnum;
6793 
6794  /* Can't alter a system attribute */
6795  if (attnum <= 0)
6796  ereport(ERROR,
6797  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6798  errmsg("cannot alter system column \"%s\"",
6799  colName)));
6800 
6801  /*
6802  * Creating a column as identity implies NOT NULL, so adding the identity
6803  * to an existing column that is not NOT NULL would create a state that
6804  * cannot be reproduced without contortions.
6805  */
6806  if (!attTup->attnotnull)
6807  ereport(ERROR,
6808  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6809  errmsg("column \"%s\" of relation \"%s\" must be declared NOT NULL before identity can be added",
6810  colName, RelationGetRelationName(rel))));
6811 
6812  if (attTup->attidentity)
6813  ereport(ERROR,
6814  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6815  errmsg("column \"%s\" of relation \"%s\" is already an identity column",
6816  colName, RelationGetRelationName(rel))));
6817 
6818  if (attTup->atthasdef)
6819  ereport(ERROR,
6820  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6821  errmsg("column \"%s\" of relation \"%s\" already has a default value",
6822  colName, RelationGetRelationName(rel))));
6823 
6824  attTup->attidentity = cdef->identity;
6825  CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
6826 
6827  InvokeObjectPostAlterHook(RelationRelationId,
6828  RelationGetRelid(rel),
6829  attTup->attnum);
6830  ObjectAddressSubSet(address, RelationRelationId,
6831  RelationGetRelid(rel), attnum);
6832  heap_freetuple(tuple);
6833 
6834  table_close(attrelation, RowExclusiveLock);
6835 
6836  return address;
6837 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
char identity
Definition: parsenodes.h:655
int errcode(int sqlerrcode)
Definition: elog.c:608
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCacheCopyAttName(Oid relid, const char *attname)
Definition: syscache.c:1280
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:462
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
int16 attnum
Definition: pg_attribute.h:79
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
int errmsg(const char *fmt,...)
Definition: elog.c:822
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:428

◆ ATExecAddIndex()

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

Definition at line 7646 of file tablecmds.c.

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

Referenced by ATExecCmd().

7648 {
7649  bool check_rights;
7650  bool skip_build;
7651  bool quiet;
7652  ObjectAddress address;
7653 
7654  Assert(IsA(stmt, IndexStmt));
7655  Assert(!stmt->concurrent);
7656 
7657  /* The IndexStmt has already been through transformIndexStmt */
7658  Assert(stmt->transformed);
7659 
7660  /* suppress schema rights check when rebuilding existing index */
7661  check_rights = !is_rebuild;
7662  /* skip index build if phase 3 will do it or we're reusing an old one */
7663  skip_build = tab->rewrite > 0 || OidIsValid(stmt->oldNode);
7664  /* suppress notices when rebuilding existing index */
7665  quiet = is_rebuild;
7666 
7667  address = DefineIndex(RelationGetRelid(rel),
7668  stmt,
7669  InvalidOid, /* no predefined OID */
7670  InvalidOid, /* no parent index */
7671  InvalidOid, /* no parent constraint */
7672  true, /* is_alter_table */
7673  check_rights,
7674  false, /* check_not_in_use - we did it already */
7675  skip_build,
7676  quiet);
7677 
7678  /*
7679  * If TryReuseIndex() stashed a relfilenode for us, we used it for the new
7680  * index instead of building from scratch. The DROP of the old edition of
7681  * this index will have scheduled the storage for deletion at commit, so
7682  * cancel that pending deletion.
7683  */
7684  if (OidIsValid(stmt->oldNode))
7685  {
7686  Relation irel = index_open(address.objectId, NoLock);
7687 
7688  RelationPreserveStorage(irel->rd_node, true);
7689  index_close(irel, NoLock);
7690  }
7691 
7692  return address;
7693 }
void RelationPreserveStorage(RelFileNode rnode, bool atCommit)
Definition: storage.c:192
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
ObjectAddress DefineIndex(Oid relationId, IndexStmt *stmt, Oid indexRelationId, Oid parentIndexId, Oid parentConstraintId, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
Definition: indexcmds.c:430
#define OidIsValid(objectId)
Definition: c.h:645
#define NoLock
Definition: lockdefs.h:34
bool transformed
Definition: parsenodes.h:2790
#define InvalidOid
Definition: postgres_ext.h:36
RelFileNode rd_node
Definition: rel.h:55
#define Assert(condition)
Definition: c.h:739
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:152
bool concurrent
Definition: parsenodes.h:2791
#define RelationGetRelid(relation)
Definition: rel.h:428
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:126

◆ ATExecAddIndexConstraint()

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

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

7703 {
7704  Oid index_oid = stmt->indexOid;
7705  Relation indexRel;
7706  char *indexName;
7707  IndexInfo *indexInfo;
7708  char *constraintName;
7709  char constraintType;
7710  ObjectAddress address;
7711  bits16 flags;
7712 
7713  Assert(IsA(stmt, IndexStmt));
7714  Assert(OidIsValid(index_oid));
7715  Assert(stmt->isconstraint);
7716 
7717  /*
7718  * Doing this on partitioned tables is not a simple feature to implement,
7719  * so let's punt for now.
7720  */
7721  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
7722  ereport(ERROR,
7723  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7724  errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX is not supported on partitioned tables")));
7725 
7726  indexRel = index_open(index_oid, AccessShareLock);
7727 
7728  indexName = pstrdup(RelationGetRelationName(indexRel));
7729 
7730  indexInfo = BuildIndexInfo(indexRel);
7731 
7732  /* this should have been checked at parse time */
7733  if (!indexInfo->ii_Unique)
7734  elog(ERROR, "index \"%s\" is not unique", indexName);
7735 
7736  /*
7737  * Determine name to assign to constraint. We require a constraint to
7738  * have the same name as the underlying index; therefore, use the index's
7739  * existing name as the default constraint name, and if the user
7740  * explicitly gives some other name for the constraint, rename the index
7741  * to match.
7742  */
7743  constraintName = stmt->idxname;
7744  if (constraintName == NULL)
7745  constraintName = indexName;
7746  else if (strcmp(constraintName, indexName) != 0)
7747  {
7748  ereport(NOTICE,
7749  (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
7750  indexName, constraintName)));
7751  RenameRelationInternal(index_oid, constraintName, false, true);
7752  }
7753 
7754  /* Extra checks needed if making primary key */
7755  if (stmt->primary)
7756  index_check_primary_key(rel, indexInfo, true, stmt);
7757 
7758  /* Note we currently don't support EXCLUSION constraints here */
7759  if (stmt->primary)
7760  constraintType = CONSTRAINT_PRIMARY;
7761  else
7762  constraintType = CONSTRAINT_UNIQUE;
7763 
7764  /* Create the catalog entries for the constraint */
7770 
7771  address = index_constraint_create(rel,
7772  index_oid,
7773  InvalidOid,
7774  indexInfo,
7775  constraintName,
7776  constraintType,
7777  flags,
7779  false); /* is_internal */
7780 
7781  index_close(indexRel, NoLock);
7782 
7783  return address;
7784 }
bool deferrable
Definition: parsenodes.h:2788
bool primary
Definition: parsenodes.h:2786
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
uint16 bits16
Definition: c.h:367
char * pstrdup(const char *in)
Definition: mcxt.c:1186
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:608
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2284
#define INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS
Definition: index.h:79
void index_check_primary_key(Relation heapRel, IndexInfo *indexInfo, bool is_alter_table, IndexStmt *stmt)
Definition: index.c:200
Form_pg_class rd_rel
Definition: rel.h:84
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
#define INDEX_CONSTR_CREATE_INIT_DEFERRED
Definition: index.h:77
Oid indexOid
Definition: parsenodes.h:2783
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:462
#define ereport(elevel, rest)
Definition: elog.h:141
char * idxname
Definition: parsenodes.h:2772
bool allowSystemTableMods
Definition: globals.c:120
#define InvalidOid
Definition: postgres_ext.h:36
#define NOTICE
Definition: elog.h:37
bool ii_Unique
Definition: execnodes.h:169
#define Assert(condition)
Definition: c.h:739
bool initdeferred
Definition: parsenodes.h:2789
#define INDEX_CONSTR_CREATE_UPDATE_INDEX
Definition: index.h:78
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:152
bool isconstraint
Definition: parsenodes.h:2787
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
Definition: tablecmds.c:3343
#define INDEX_CONSTR_CREATE_DEFERRABLE
Definition: index.h:76
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:126
#define INDEX_CONSTR_CREATE_MARK_AS_PRIMARY
Definition: index.h:75
ObjectAddress index_constraint_create(Relation heapRelation, Oid indexRelationId, Oid parentConstraintId, IndexInfo *indexInfo, const char *constraintName, char constraintType, bits16 constr_flags, bool allow_system_table_mods, bool is_internal)
Definition: index.c:1787

◆ ATExecAddInherit()

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

Definition at line 13263 of file tablecmds.c.

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

Referenced by ATExecCmd().

13264 {
13265  Relation parent_rel;
13266  List *children;
13267  ObjectAddress address;
13268  const char *trigger_name;
13269 
13270  /*
13271  * A self-exclusive lock is needed here. See the similar case in
13272  * MergeAttributes() for a full explanation.
13273  */
13274  parent_rel = table_openrv(parent, ShareUpdateExclusiveLock);
13275 
13276  /*
13277  * Must be owner of both parent and child -- child was checked by
13278  * ATSimplePermissions call in ATPrepCmd
13279  */
13281 
13282  /* Permanent rels cannot inherit from temporary ones */
13283  if (parent_rel->