PostgreSQL Source Code  git master
tablecmds.c File Reference
#include "postgres.h"
#include "access/attmap.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/heapam_xlog.h"
#include "access/multixact.h"
#include "access/reloptions.h"
#include "access/relscan.h"
#include "access/sysattr.h"
#include "access/tableam.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/objectaccess.h"
#include "catalog/partition.h"
#include "catalog/pg_am.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_depend.h"
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_tablespace.h"
#include "catalog/pg_trigger.h"
#include "catalog/pg_type.h"
#include "catalog/storage.h"
#include "catalog/storage_xlog.h"
#include "catalog/toasting.h"
#include "commands/cluster.h"
#include "commands/comment.h"
#include "commands/defrem.h"
#include "commands/event_trigger.h"
#include "commands/policy.h"
#include "commands/sequence.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "commands/trigger.h"
#include "commands/typecmds.h"
#include "commands/user.h"
#include "executor/executor.h"
#include "foreign/foreign.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/parsenodes.h"
#include "optimizer/optimizer.h"
#include "parser/parse_clause.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_expr.h"
#include "parser/parse_oper.h"
#include "parser/parse_relation.h"
#include "parser/parse_type.h"
#include "parser/parse_utilcmd.h"
#include "parser/parser.h"
#include "partitioning/partbounds.h"
#include "partitioning/partdesc.h"
#include "pgstat.h"
#include "rewrite/rewriteDefine.h"
#include "rewrite/rewriteHandler.h"
#include "rewrite/rewriteManip.h"
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "storage/lock.h"
#include "storage/predicate.h"
#include "storage/smgr.h"
#include "tcop/utility.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/partcache.h"
#include "utils/relcache.h"
#include "utils/ruleutils.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/timestamp.h"
#include "utils/typcache.h"
Include dependency graph for tablecmds.c:

Go to the source code of this file.

Data Structures

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

Macros

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

Typedefs

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

Functions

static void truncate_check_rel (Oid relid, Form_pg_class reltuple)
 
static void truncate_check_perms (Oid relid, Form_pg_class reltuple)
 
static void truncate_check_activity (Relation rel)
 
static void RangeVarCallbackForTruncate (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
static ListMergeAttributes (List *schema, List *supers, char relpersistence, bool is_partition, List **supconstr)
 
static bool MergeCheckConstraint (List *constraints, char *name, Node *expr)
 
static void MergeAttributesIntoExisting (Relation child_rel, Relation parent_rel)
 
static void MergeConstraintsIntoExisting (Relation child_rel, Relation parent_rel)
 
static void StoreCatalogInheritance (Oid relationId, List *supers, bool child_is_partition)
 
static void StoreCatalogInheritance1 (Oid relationId, Oid parentOid, int32 seqNumber, Relation inhRelation, bool child_is_partition)
 
static int findAttrByName (const char *attributeName, List *schema)
 
static void AlterIndexNamespaces (Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
 
static void AlterSeqNamespaces (Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved, LOCKMODE lockmode)
 
static ObjectAddress ATExecAlterConstraint (Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
 
static ObjectAddress ATExecValidateConstraint (Relation rel, char *constrName, bool recurse, bool recursing, LOCKMODE lockmode)
 
static int transformColumnNameList (Oid relId, List *colList, int16 *attnums, Oid *atttypids)
 
static int transformFkeyGetPrimaryKey (Relation pkrel, Oid *indexOid, List **attnamelist, int16 *attnums, Oid *atttypids, Oid *opclasses)
 
static Oid transformFkeyCheckAttrs (Relation pkrel, int numattrs, int16 *attnums, Oid *opclasses)
 
static void checkFkeyPermissions (Relation rel, int16 *attnums, int natts)
 
static CoercionPathType findFkeyCast (Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
 
static void validateCheckConstraint (Relation rel, HeapTuple constrtup)
 
static void validateForeignKeyConstraint (char *conname, Relation rel, Relation pkrel, Oid pkindOid, Oid constraintOid)
 
static void ATController (AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
static void ATPrepCmd (List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
static void ATRewriteCatalogs (List **wqueue, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
static void ATExecCmd (List **wqueue, AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd, LOCKMODE lockmode, int cur_pass, AlterTableUtilityContext *context)
 
static AlterTableCmdATParseTransformCmd (List **wqueue, AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode, int cur_pass, AlterTableUtilityContext *context)
 
static void ATRewriteTables (AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
static void ATRewriteTable (AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode)
 
static AlteredTableInfoATGetQueueEntry (List **wqueue, Relation rel)
 
static void ATSimplePermissions (Relation rel, int allowed_targets)
 
static void ATWrongRelkindError (Relation rel, int allowed_targets)
 
static void ATSimpleRecursion (List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
static void ATCheckPartitionsNotInUse (Relation rel, LOCKMODE lockmode)
 
static void ATTypedTableRecursion (List **wqueue, Relation rel, AlterTableCmd *cmd, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
static Listfind_typed_table_dependencies (Oid typeOid, const char *typeName, DropBehavior behavior)
 
static void ATPrepAddColumn (List **wqueue, Relation rel, bool recurse, bool recursing, bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
static ObjectAddress ATExecAddColumn (List **wqueue, AlteredTableInfo *tab, Relation rel, AlterTableCmd **cmd, bool recurse, bool recursing, LOCKMODE lockmode, int cur_pass, AlterTableUtilityContext *context)
 
static bool check_for_column_name_collision (Relation rel, const char *colname, bool if_not_exists)
 
static void add_column_datatype_dependency (Oid relid, int32 attnum, Oid typid)
 
static void add_column_collation_dependency (Oid relid, int32 attnum, Oid collid)
 
static void ATPrepDropNotNull (Relation rel, bool recurse, bool recursing)
 
static ObjectAddress ATExecDropNotNull (Relation rel, const char *colName, LOCKMODE lockmode)
 
static void ATPrepSetNotNull (List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
static ObjectAddress ATExecSetNotNull (AlteredTableInfo *tab, Relation rel, const char *colName, LOCKMODE lockmode)
 
static void ATExecCheckNotNull (AlteredTableInfo *tab, Relation rel, const char *colName, LOCKMODE lockmode)
 
static bool NotNullImpliedByRelConstraints (Relation rel, Form_pg_attribute attr)
 
static bool ConstraintImpliedByRelConstraint (Relation scanrel, List *testConstraint, List *provenConstraint)
 
static ObjectAddress ATExecColumnDefault (Relation rel, const char *colName, Node *newDefault, LOCKMODE lockmode)
 
static ObjectAddress ATExecAddIdentity (Relation rel, const char *colName, Node *def, LOCKMODE lockmode)
 
static ObjectAddress ATExecSetIdentity (Relation rel, const char *colName, Node *def, LOCKMODE lockmode)
 
static ObjectAddress ATExecDropIdentity (Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode)
 
static void ATPrepDropExpression (Relation rel, AlterTableCmd *cmd, bool recursing)
 
static ObjectAddress ATExecDropExpression (Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode)
 
static ObjectAddress ATExecSetStatistics (Relation rel, const char *colName, int16 colNum, Node *newValue, LOCKMODE lockmode)
 
static ObjectAddress ATExecSetOptions (Relation rel, const char *colName, Node *options, bool isReset, LOCKMODE lockmode)
 
static ObjectAddress ATExecSetStorage (Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
 
static void ATPrepDropColumn (List **wqueue, Relation rel, bool recurse, bool recursing, AlterTableCmd *cmd, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
static ObjectAddress ATExecDropColumn (List **wqueue, Relation rel, const char *colName, DropBehavior behavior, bool recurse, bool recursing, bool missing_ok, LOCKMODE lockmode, ObjectAddresses *addrs)
 
static ObjectAddress ATExecAddIndex (AlteredTableInfo *tab, Relation rel, IndexStmt *stmt, bool is_rebuild, LOCKMODE lockmode)
 
static ObjectAddress ATExecAddConstraint (List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *newConstraint, bool recurse, bool is_readd, LOCKMODE lockmode)
 
static char * ChooseForeignKeyConstraintNameAddition (List *colnames)
 
static ObjectAddress ATExecAddIndexConstraint (AlteredTableInfo *tab, Relation rel, IndexStmt *stmt, LOCKMODE lockmode)
 
static ObjectAddress ATAddCheckConstraint (List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *constr, bool recurse, bool recursing, bool is_readd, LOCKMODE lockmode)
 
static ObjectAddress ATAddForeignKeyConstraint (List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *fkconstraint, Oid parentConstr, bool recurse, bool recursing, LOCKMODE lockmode)
 
static ObjectAddress addFkRecurseReferenced (List **wqueue, Constraint *fkconstraint, Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr, int numfks, int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators, bool old_check_ok)
 
static void addFkRecurseReferencing (List **wqueue, Constraint *fkconstraint, Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr, int numfks, int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators, bool old_check_ok, LOCKMODE lockmode)
 
static void CloneForeignKeyConstraints (List **wqueue, Relation parentRel, Relation partitionRel)
 
static void CloneFkReferenced (Relation parentRel, Relation partitionRel)
 
static void CloneFkReferencing (List **wqueue, Relation parentRel, Relation partRel)
 
static void createForeignKeyCheckTriggers (Oid myRelOid, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid)
 
static void createForeignKeyActionTriggers (Relation rel, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid)
 
static bool tryAttachPartitionForeignKey (ForeignKeyCacheInfo *fk, Oid partRelid, Oid parentConstrOid, int numfks, AttrNumber *mapped_conkey, AttrNumber *confkey, Oid *conpfeqop)
 
static void ATExecDropConstraint (Relation rel, const char *constrName, DropBehavior behavior, bool recurse, bool recursing, bool missing_ok, LOCKMODE lockmode)
 
static void ATPrepAlterColumnType (List **wqueue, AlteredTableInfo *tab, Relation rel, bool recurse, bool recursing, AlterTableCmd *cmd, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
static bool ATColumnChangeRequiresRewrite (Node *expr, AttrNumber varattno)
 
static ObjectAddress ATExecAlterColumnType (AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static void RememberConstraintForRebuilding (Oid conoid, AlteredTableInfo *tab)
 
static void RememberIndexForRebuilding (Oid indoid, AlteredTableInfo *tab)
 
static void ATPostAlterTypeCleanup (List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode)
 
static void ATPostAlterTypeParse (Oid oldId, Oid oldRelId, Oid refRelId, char *cmd, List **wqueue, LOCKMODE lockmode, bool rewrite)
 
static void RebuildConstraintComment (AlteredTableInfo *tab, int pass, Oid objid, Relation rel, List *domname, const char *conname)
 
static void TryReuseIndex (Oid oldId, IndexStmt *stmt)
 
static void TryReuseForeignKey (Oid oldId, Constraint *con)
 
static ObjectAddress ATExecAlterColumnGenericOptions (Relation rel, const char *colName, List *options, LOCKMODE lockmode)
 
static void change_owner_fix_column_acls (Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
 
static void change_owner_recurse_to_sequences (Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
 
static ObjectAddress ATExecClusterOn (Relation rel, const char *indexName, LOCKMODE lockmode)
 
static void ATExecDropCluster (Relation rel, LOCKMODE lockmode)
 
static bool ATPrepChangePersistence (Relation rel, bool toLogged)
 
static void ATPrepSetTableSpace (AlteredTableInfo *tab, Relation rel, const char *tablespacename, LOCKMODE lockmode)
 
static void ATExecSetTableSpace (Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
 
static void ATExecSetTableSpaceNoStorage (Relation rel, Oid newTableSpace)
 
static void ATExecSetRelOptions (Relation rel, List *defList, AlterTableType operation, LOCKMODE lockmode)
 
static void ATExecEnableDisableTrigger (Relation rel, const char *trigname, char fires_when, bool skip_system, LOCKMODE lockmode)
 
static void ATExecEnableDisableRule (Relation rel, const char *rulename, char fires_when, LOCKMODE lockmode)
 
static void ATPrepAddInherit (Relation child_rel)
 
static ObjectAddress ATExecAddInherit (Relation child_rel, RangeVar *parent, LOCKMODE lockmode)
 
static ObjectAddress ATExecDropInherit (Relation rel, RangeVar *parent, LOCKMODE lockmode)
 
static void drop_parent_dependency (Oid relid, Oid refclassid, Oid refobjid, DependencyType deptype)
 
static ObjectAddress ATExecAddOf (Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
 
static void ATExecDropOf (Relation rel, LOCKMODE lockmode)
 
static void ATExecReplicaIdentity (Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode)
 
static void ATExecGenericOptions (Relation rel, List *options)
 
static void ATExecEnableRowSecurity (Relation rel)
 
static void ATExecDisableRowSecurity (Relation rel)
 
static void ATExecForceNoForceRowSecurity (Relation rel, bool force_rls)
 
static void index_copy_data (Relation rel, RelFileNode newrnode)
 
static const char * storage_name (char c)
 
static void RangeVarCallbackForDropRelation (const RangeVar *rel, Oid relOid, Oid oldRelOid, void *arg)
 
static void RangeVarCallbackForAlterRelation (const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
 
static PartitionSpectransformPartitionSpec (Relation rel, PartitionSpec *partspec, char *strategy)
 
static void ComputePartitionAttrs (ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs, List **partexprs, Oid *partopclass, Oid *partcollation, char strategy)
 
static void CreateInheritance (Relation child_rel, Relation parent_rel)
 
static void RemoveInheritance (Relation child_rel, Relation parent_rel)
 
static ObjectAddress ATExecAttachPartition (List **wqueue, Relation rel, PartitionCmd *cmd)
 
static void AttachPartitionEnsureIndexes (Relation rel, Relation attachrel)
 
static void QueuePartitionConstraintValidation (List **wqueue, Relation scanrel, List *partConstraint, bool validate_default)
 
static void CloneRowTriggersToPartition (Relation parent, Relation partition)
 
static ObjectAddress ATExecDetachPartition (Relation rel, RangeVar *name)
 
static ObjectAddress ATExecAttachPartitionIdx (List **wqueue, Relation rel, RangeVar *name)
 
static void validatePartitionedIndex (Relation partedIdx, Relation partedTbl)
 
static void refuseDupeIndexAttach (Relation parentIdx, Relation partIdx, Relation partitionTbl)
 
static ListGetParentedForeignKeyRefs (Relation partition)
 
static void ATDetachCheckNoForeignKeyRefs (Relation partition)
 
ObjectAddress DefineRelation (CreateStmt *stmt, char relkind, Oid ownerId, ObjectAddress *typaddress, const char *queryString)
 
static void DropErrorMsgNonExistent (RangeVar *rel, char rightkind, bool missing_ok)
 
static void DropErrorMsgWrongType (const char *relname, char wrongkind, char rightkind)
 
void RemoveRelations (DropStmt *drop)
 
void ExecuteTruncate (TruncateStmt *stmt)
 
void ExecuteTruncateGuts (List *explicit_rels, List *relids, List *relids_logged, DropBehavior behavior, bool restart_seqs)
 
void SetRelationHasSubclass (Oid relationId, bool relhassubclass)
 
static void renameatt_check (Oid myrelid, Form_pg_class classform, bool recursing)
 
static AttrNumber renameatt_internal (Oid myrelid, const char *oldattname, const char *newattname, bool recurse, bool recursing, int expected_parents, DropBehavior behavior)
 
static void RangeVarCallbackForRenameAttribute (const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
 
ObjectAddress renameatt (RenameStmt *stmt)
 
static ObjectAddress rename_constraint_internal (Oid myrelid, Oid mytypid, const char *oldconname, const char *newconname, bool recurse, bool recursing, int expected_parents)
 
ObjectAddress RenameConstraint (RenameStmt *stmt)
 
ObjectAddress RenameRelation (RenameStmt *stmt)
 
void RenameRelationInternal (Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
 
void CheckTableNotInUse (Relation rel, const char *stmt)
 
Oid AlterTableLookupRelation (AlterTableStmt *stmt, LOCKMODE lockmode)
 
void AlterTable (AlterTableStmt *stmt, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
void AlterTableInternal (Oid relid, List *cmds, bool recurse)
 
LOCKMODE AlterTableGetLockLevel (List *cmds)
 
void find_composite_type_dependencies (Oid typeOid, Relation origRelation, const char *origTypeName)
 
void check_of_type (HeapTuple typetuple)
 
static void CreateFKCheckTrigger (Oid myRelOid, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid, bool on_insert)
 
static void RememberReplicaIdentityForRebuilding (Oid indoid, AlteredTableInfo *tab)
 
static void RememberClusterOnForRebuilding (Oid indoid, AlteredTableInfo *tab)
 
void ATExecChangeOwner (Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
 
Oid AlterTableMoveAll (AlterTableMoveAllStmt *stmt)
 
static char * decompile_conbin (HeapTuple contup, TupleDesc tupdesc)
 
static bool constraints_equivalent (HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
 
static void relation_mark_replica_identity (Relation rel, char ri_type, Oid indexOid, bool is_internal)
 
ObjectAddress AlterTableNamespace (AlterObjectSchemaStmt *stmt, Oid *oldschema)
 
void AlterTableNamespaceInternal (Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
 
void AlterRelationNamespaceInternal (Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
 
void register_on_commit_action (Oid relid, OnCommitAction action)
 
void remove_on_commit_action (Oid relid)
 
void PreCommit_on_commit_actions (void)
 
void AtEOXact_on_commit_actions (bool isCommit)
 
void AtEOSubXact_on_commit_actions (bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
 
void RangeVarCallbackOwnsTable (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
void RangeVarCallbackOwnsRelation (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
bool PartConstraintImpliedByRelConstraint (Relation scanrel, List *partConstraint)
 
static void RangeVarCallbackForAttachIndex (const RangeVar *rv, Oid relOid, Oid oldRelOid, void *arg)
 

Variables

static Liston_commits = NIL
 
static const struct dropmsgstrings dropmsgstringarray []
 

Macro Definition Documentation

◆ AT_NUM_PASSES

#define AT_NUM_PASSES   11

Definition at line 152 of file tablecmds.c.

Referenced by ATRewriteCatalogs().

◆ AT_PASS_ADD_COL

#define AT_PASS_ADD_COL   4 /* ADD COLUMN */

Definition at line 145 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ AT_PASS_ADD_CONSTR

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

Definition at line 146 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ AT_PASS_ADD_INDEX

#define AT_PASS_ADD_INDEX   8 /* ADD indexes */

Definition at line 149 of file tablecmds.c.

Referenced by ATParseTransformCmd(), and ATPrepCmd().

◆ AT_PASS_ADD_INDEXCONSTR

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

Definition at line 148 of file tablecmds.c.

Referenced by ATParseTransformCmd(), and ATPrepCmd().

◆ AT_PASS_ADD_OTHERCONSTR

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

Definition at line 150 of file tablecmds.c.

Referenced by ATParseTransformCmd(), and ATPrepCmd().

◆ AT_PASS_ALTER_TYPE

#define AT_PASS_ALTER_TYPE   1 /* ALTER COLUMN TYPE */

Definition at line 141 of file tablecmds.c.

Referenced by ATPrepCmd(), and ATRewriteCatalogs().

◆ AT_PASS_COL_ATTRS

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

Definition at line 147 of file tablecmds.c.

Referenced by ATParseTransformCmd(), and ATPrepCmd().

◆ AT_PASS_DROP

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

Definition at line 140 of file tablecmds.c.

Referenced by ATPrepCmd().

◆ AT_PASS_MISC

#define AT_PASS_MISC   10 /* other stuff */

Definition at line 151 of file tablecmds.c.

Referenced by ATParseTransformCmd(), and ATPrepCmd().

◆ AT_PASS_OLD_CONSTR

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

Definition at line 143 of file tablecmds.c.

Referenced by ATPostAlterTypeCleanup(), and ATPostAlterTypeParse().

◆ AT_PASS_OLD_INDEX

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

Definition at line 142 of file tablecmds.c.

Referenced by ATPostAlterTypeParse().

◆ AT_PASS_UNSET

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

Definition at line 139 of file tablecmds.c.

Referenced by ATParseTransformCmd(), and ATPrepCmd().

◆ ATT_COMPOSITE_TYPE

#define ATT_COMPOSITE_TYPE   0x0010

Definition at line 296 of file tablecmds.c.

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

◆ ATT_FOREIGN_TABLE

◆ ATT_INDEX

#define ATT_INDEX   0x0008

Definition at line 295 of file tablecmds.c.

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

◆ ATT_MATVIEW

#define ATT_MATVIEW   0x0004

Definition at line 294 of file tablecmds.c.

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

◆ ATT_PARTITIONED_INDEX

#define ATT_PARTITIONED_INDEX   0x0040

Definition at line 298 of file tablecmds.c.

Referenced by ATPrepCmd(), and ATSimplePermissions().

◆ ATT_TABLE

◆ ATT_VIEW

#define ATT_VIEW   0x0002

Definition at line 293 of file tablecmds.c.

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

◆ child_dependency_type

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

Definition at line 305 of file tablecmds.c.

Referenced by RemoveInheritance(), and StoreCatalogInheritance1().

Typedef Documentation

◆ AlteredTableInfo

◆ NewColumnValue

◆ NewConstraint

typedef struct NewConstraint NewConstraint

◆ OnCommitItem

typedef struct OnCommitItem OnCommitItem

Function Documentation

◆ add_column_collation_dependency()

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

Definition at line 6378 of file tablecmds.c.

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

Referenced by ATExecAddColumn(), and ATExecAlterColumnType().

6379 {
6380  ObjectAddress myself,
6381  referenced;
6382 
6383  /* We know the default collation is pinned, so don't bother recording it */
6384  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
6385  {
6386  myself.classId = RelationRelationId;
6387  myself.objectId = relid;
6388  myself.objectSubId = attnum;
6389  referenced.classId = CollationRelationId;
6390  referenced.objectId = collid;
6391  referenced.objectSubId = 0;
6392  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
6393  }
6394 }
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
#define OidIsValid(objectId)
Definition: c.h:644
int16 attnum
Definition: pg_attribute.h:79

◆ add_column_datatype_dependency()

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

Definition at line 6360 of file tablecmds.c.

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

Referenced by ATExecAddColumn(), and ATExecAlterColumnType().

6361 {
6362  ObjectAddress myself,
6363  referenced;
6364 
6365  myself.classId = RelationRelationId;
6366  myself.objectId = relid;
6367  myself.objectSubId = attnum;
6368  referenced.classId = TypeRelationId;
6369  referenced.objectId = typid;
6370  referenced.objectSubId = 0;
6371  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
6372 }
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 8528 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().

8533 {
8534  ObjectAddress address;
8535  Oid constrOid;
8536  char *conname;
8537  bool conislocal;
8538  int coninhcount;
8539  bool connoinherit;
8540 
8541  /*
8542  * Verify relkind for each referenced partition. At the top level, this
8543  * is redundant with a previous check, but we need it when recursing.
8544  */
8545  if (pkrel->rd_rel->relkind != RELKIND_RELATION &&
8546  pkrel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
8547  ereport(ERROR,
8548  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8549  errmsg("referenced relation \"%s\" is not a table",
8550  RelationGetRelationName(pkrel))));
8551 
8552  /*
8553  * Caller supplies us with a constraint name; however, it may be used in
8554  * this partition, so come up with a different one in that case.
8555  */
8557  RelationGetRelid(rel),
8558  fkconstraint->conname))
8561  "fkey",
8562  RelationGetNamespace(rel), NIL);
8563  else
8564  conname = fkconstraint->conname;
8565 
8566  if (OidIsValid(parentConstr))
8567  {
8568  conislocal = false;
8569  coninhcount = 1;
8570  connoinherit = false;
8571  }
8572  else
8573  {
8574  conislocal = true;
8575  coninhcount = 0;
8576 
8577  /*
8578  * always inherit for partitioned tables, never for legacy inheritance
8579  */
8580  connoinherit = rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE;
8581  }
8582 
8583  /*
8584  * Record the FK constraint in pg_constraint.
8585  */
8586  constrOid = CreateConstraintEntry(conname,
8587  RelationGetNamespace(rel),
8588  CONSTRAINT_FOREIGN,
8589  fkconstraint->deferrable,
8590  fkconstraint->initdeferred,
8591  fkconstraint->initially_valid,
8592  parentConstr,
8593  RelationGetRelid(rel),
8594  fkattnum,
8595  numfks,
8596  numfks,
8597  InvalidOid, /* not a domain constraint */
8598  indexOid,
8599  RelationGetRelid(pkrel),
8600  pkattnum,
8601  pfeqoperators,
8602  ppeqoperators,
8603  ffeqoperators,
8604  numfks,
8605  fkconstraint->fk_upd_action,
8606  fkconstraint->fk_del_action,
8607  fkconstraint->fk_matchtype,
8608  NULL, /* no exclusion constraint */
8609  NULL, /* no check constraint */
8610  NULL,
8611  conislocal, /* islocal */
8612  coninhcount, /* inhcount */
8613  connoinherit, /* conNoInherit */
8614  false); /* is_internal */
8615 
8616  ObjectAddressSet(address, ConstraintRelationId, constrOid);
8617 
8618  /*
8619  * Mark the child constraint as part of the parent constraint; it must not
8620  * be dropped on its own. (This constraint is deleted when the partition
8621  * is detached, but a special check needs to occur that the partition
8622  * contains no referenced values.)
8623  */
8624  if (OidIsValid(parentConstr))
8625  {
8626  ObjectAddress referenced;
8627 
8628  ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
8629  recordDependencyOn(&address, &referenced, DEPENDENCY_INTERNAL);
8630  }
8631 
8632  /* make new constraint visible, in case we add more */
8634 
8635  /*
8636  * If the referenced table is a plain relation, create the action triggers
8637  * that enforce the constraint.
8638  */
8639  if (pkrel->rd_rel->relkind == RELKIND_RELATION)
8640  {
8642  fkconstraint,
8643  constrOid, indexOid);
8644  }
8645 
8646  /*
8647  * If the referenced table is partitioned, recurse on ourselves to handle
8648  * each partition. We need one pg_constraint row created for each
8649  * partition in addition to the pg_constraint row for the parent table.
8650  */
8651  if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
8652  {
8654 
8655  for (int i = 0; i < pd->nparts; i++)
8656  {
8657  Relation partRel;
8658  AttrMap *map;
8659  AttrNumber *mapped_pkattnum;
8660  Oid partIndexId;
8661 
8662  partRel = table_open(pd->oids[i], ShareRowExclusiveLock);
8663 
8664  /*
8665  * Map the attribute numbers in the referenced side of the FK
8666  * definition to match the partition's column layout.
8667  */
8669  RelationGetDescr(pkrel));
8670  if (map)
8671  {
8672  mapped_pkattnum = palloc(sizeof(AttrNumber) * numfks);
8673  for (int j = 0; j < numfks; j++)
8674  mapped_pkattnum[j] = map->attnums[pkattnum[j] - 1];
8675  }
8676  else
8677  mapped_pkattnum = pkattnum;
8678 
8679  /* do the deed */
8680  partIndexId = index_get_partition(partRel, indexOid);
8681  if (!OidIsValid(partIndexId))
8682  elog(ERROR, "index for %u not found in partition %s",
8683  indexOid, RelationGetRelationName(partRel));
8684  addFkRecurseReferenced(wqueue, fkconstraint, rel, partRel,
8685  partIndexId, constrOid, numfks,
8686  mapped_pkattnum, fkattnum,
8687  pfeqoperators, ppeqoperators, ffeqoperators,
8688  old_check_ok);
8689 
8690  /* Done -- clean up (but keep the lock) */
8691  table_close(partRel, NoLock);
8692  if (map)
8693  {
8694  pfree(mapped_pkattnum);
8695  free_attrmap(map);
8696  }
8697  }
8698  }
8699 
8700  return address;
8701 }
#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:7911
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
void free_attrmap(AttrMap *map)
Definition: attmap.c:57
#define RelationGetDescr(relation)
Definition: rel.h:482
char fk_matchtype
Definition: parsenodes.h:2189
Oid CreateConstraintEntry(const char *constraintName, Oid constraintNamespace, char constraintType, bool isDeferrable, bool isDeferred, bool isValidated, Oid parentConstrId, Oid relId, const int16 *constraintKey, int constraintNKeys, int constraintNTotalKeys, Oid domainId, Oid indexRelId, Oid foreignRelId, const int16 *foreignKey, const Oid *pfEqOp, const Oid *ppEqOp, const Oid *ffEqOp, int foreignNKeys, char foreignUpdateType, char foreignDeleteType, char foreignMatchType, const Oid *exclOp, Node *conExpr, const char *conBin, bool conIsLocal, int conInhCount, bool conNoInherit, bool is_internal)
Definition: pg_constraint.c:50
int errcode(int sqlerrcode)
Definition: elog.c:610
bool initdeferred
Definition: parsenodes.h:2157
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
char * conname
Definition: parsenodes.h:2155
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:644
Definition: attmap.h:34
void pfree(void *pointer)
Definition: mcxt.c:1056
static ObjectAddress addFkRecurseReferenced(List **wqueue, Constraint *fkconstraint, Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr, int numfks, int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators, bool old_check_ok)
Definition: tablecmds.c:8528
AttrMap * build_attrmap_by_name_if_req(TupleDesc indesc, TupleDesc outdesc)
Definition: attmap.c:259
#define ERROR
Definition: elog.h:43
bool deferrable
Definition: parsenodes.h:2156
#define NoLock
Definition: lockdefs.h:34
PartitionDesc RelationGetPartitionDesc(Relation rel)
Definition: partdesc.c:65
#define RelationGetRelationName(relation)
Definition: rel.h:490
static void createForeignKeyActionTriggers(Relation rel, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid)
Definition: tablecmds.c:10361
void CommandCounterIncrement(void)
Definition: xact.c:1005
#define InvalidOid
Definition: postgres_ext.h:36
bool initially_valid
Definition: parsenodes.h:2198
#define ereport(elevel,...)
Definition: elog.h:144
char fk_del_action
Definition: parsenodes.h:2191
#define ShareRowExclusiveLock
Definition: lockdefs.h:42
AttrNumber * attnums
Definition: attmap.h:36
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
int i
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:456
List * fk_attrs
Definition: parsenodes.h:2187
char fk_upd_action
Definition: parsenodes.h:2190
#define RelationGetNamespace(relation)
Definition: rel.h:497

◆ addFkRecurseReferencing()

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

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

8738 {
8739  AssertArg(OidIsValid(parentConstr));
8740 
8741  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
8742  ereport(ERROR,
8743  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
8744  errmsg("foreign key constraints are not supported on foreign tables")));
8745 
8746  /*
8747  * If the referencing relation is a plain table, add the check triggers to
8748  * it and, if necessary, schedule it to be checked in Phase 3.
8749  *
8750  * If the relation is partitioned, drill down to do it to its partitions.
8751  */
8752  if (rel->rd_rel->relkind == RELKIND_RELATION)
8753  {
8755  RelationGetRelid(pkrel),
8756  fkconstraint,
8757  parentConstr,
8758  indexOid);
8759 
8760  /*
8761  * Tell Phase 3 to check that the constraint is satisfied by existing
8762  * rows. We can skip this during table creation, when requested
8763  * explicitly by specifying NOT VALID in an ADD FOREIGN KEY command,
8764  * and when we're recreating a constraint following a SET DATA TYPE
8765  * operation that did not impugn its validity.
8766  */
8767  if (wqueue && !old_check_ok && !fkconstraint->skip_validation)
8768  {
8769  NewConstraint *newcon;
8770  AlteredTableInfo *tab;
8771 
8772  tab = ATGetQueueEntry(wqueue, rel);
8773 
8774  newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
8775  newcon->name = get_constraint_name(parentConstr);
8776  newcon->contype = CONSTR_FOREIGN;
8777  newcon->refrelid = RelationGetRelid(pkrel);
8778  newcon->refindid = indexOid;
8779  newcon->conid = parentConstr;
8780  newcon->qual = (Node *) fkconstraint;
8781 
8782  tab->constraints = lappend(tab->constraints, newcon);
8783  }
8784  }
8785  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
8786  {
8788 
8789  /*
8790  * Recurse to take appropriate action on each partition; either we
8791  * find an existing constraint to reparent to ours, or we create a new
8792  * one.
8793  */
8794  for (int i = 0; i < pd->nparts; i++)
8795  {
8796  Oid partitionId = pd->oids[i];
8797  Relation partition = table_open(partitionId, lockmode);
8798  List *partFKs;
8799  AttrMap *attmap;
8800  AttrNumber mapped_fkattnum[INDEX_MAX_KEYS];
8801  bool attached;
8802  char *conname;
8803  Oid constrOid;
8804  ObjectAddress address,
8805  referenced;
8806  ListCell *cell;
8807 
8808  CheckTableNotInUse(partition, "ALTER TABLE");
8809 
8810  attmap = build_attrmap_by_name(RelationGetDescr(partition),
8811  RelationGetDescr(rel));
8812  for (int j = 0; j < numfks; j++)
8813  mapped_fkattnum[j] = attmap->attnums[fkattnum[j] - 1];
8814 
8815  /* Check whether an existing constraint can be repurposed */
8816  partFKs = copyObject(RelationGetFKeyList(partition));
8817  attached = false;
8818  foreach(cell, partFKs)
8819  {
8820  ForeignKeyCacheInfo *fk;
8821 
8822  fk = lfirst_node(ForeignKeyCacheInfo, cell);
8824  partitionId,
8825  parentConstr,
8826  numfks,
8827  mapped_fkattnum,
8828  pkattnum,
8829  pfeqoperators))
8830  {
8831  attached = true;
8832  break;
8833  }
8834  }
8835  if (attached)
8836  {
8837  table_close(partition, NoLock);
8838  continue;
8839  }
8840 
8841  /*
8842  * No luck finding a good constraint to reuse; create our own.
8843  */
8845  RelationGetRelid(partition),
8846  fkconstraint->conname))
8847  conname = ChooseConstraintName(RelationGetRelationName(partition),
8849  "fkey",
8850  RelationGetNamespace(partition), NIL);
8851  else
8852  conname = fkconstraint->conname;
8853  constrOid =
8854  CreateConstraintEntry(conname,
8855  RelationGetNamespace(partition),
8856  CONSTRAINT_FOREIGN,
8857  fkconstraint->deferrable,
8858  fkconstraint->initdeferred,
8859  fkconstraint->initially_valid,
8860  parentConstr,
8861  partitionId,
8862  mapped_fkattnum,
8863  numfks,
8864  numfks,
8865  InvalidOid,
8866  indexOid,
8867  RelationGetRelid(pkrel),
8868  pkattnum,
8869  pfeqoperators,
8870  ppeqoperators,
8871  ffeqoperators,
8872  numfks,
8873  fkconstraint->fk_upd_action,
8874  fkconstraint->fk_del_action,
8875  fkconstraint->fk_matchtype,
8876  NULL,
8877  NULL,
8878  NULL,
8879  false,
8880  1,
8881  false,
8882  false);
8883 
8884  /*
8885  * Give this constraint partition-type dependencies on the parent
8886  * constraint as well as the table.
8887  */
8888  ObjectAddressSet(address, ConstraintRelationId, constrOid);
8889  ObjectAddressSet(referenced, ConstraintRelationId, parentConstr);
8890  recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_PRI);
8891  ObjectAddressSet(referenced, RelationRelationId, partitionId);
8892  recordDependencyOn(&address, &referenced, DEPENDENCY_PARTITION_SEC);
8893 
8894  /* Make all this visible before recursing */
8896 
8897  /* call ourselves to finalize the creation and we're done */
8898  addFkRecurseReferencing(wqueue, fkconstraint, partition, pkrel,
8899  indexOid,
8900  constrOid,
8901  numfks,
8902  pkattnum,
8903  mapped_fkattnum,
8904  pfeqoperators,
8905  ppeqoperators,
8906  ffeqoperators,
8907  old_check_ok,
8908  lockmode);
8909 
8910  table_close(partition, NoLock);
8911  }
8912  }
8913 }
#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:10482
bool ConstraintNameIsUsed(ConstraintCategory conCat, Oid objId, const char *conname)
char * name
Definition: tablecmds.c:187
static char * ChooseForeignKeyConstraintNameAddition(List *colnames)
Definition: tablecmds.c:7911
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define RelationGetDescr(relation)
Definition: rel.h:482
char * get_constraint_name(Oid conoid)
Definition: lsyscache.c:1030
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:8733
char fk_matchtype
Definition: parsenodes.h:2189
Oid CreateConstraintEntry(const char *constraintName, Oid constraintNamespace, char constraintType, bool isDeferrable, bool isDeferred, bool isValidated, Oid parentConstrId, Oid relId, const int16 *constraintKey, int constraintNKeys, int constraintNTotalKeys, Oid domainId, Oid indexRelId, Oid foreignRelId, const int16 *foreignKey, const Oid *pfEqOp, const Oid *ppEqOp, const Oid *ffEqOp, int foreignNKeys, char foreignUpdateType, char foreignDeleteType, char foreignMatchType, const Oid *exclOp, Node *conExpr, const char *conBin, bool conIsLocal, int conInhCount, bool conNoInherit, bool is_internal)
Definition: pg_constraint.c:50
Node * qual
Definition: tablecmds.c:192
Definition: nodes.h:529
int errcode(int sqlerrcode)
Definition: elog.c:610
bool initdeferred
Definition: parsenodes.h:2157
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
char * conname
Definition: parsenodes.h:2155
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:644
List * constraints
Definition: tablecmds.c:163
Definition: attmap.h:34
static bool tryAttachPartitionForeignKey(ForeignKeyCacheInfo *fk, Oid partRelid, Oid parentConstrOid, int numfks, AttrNumber *mapped_conkey, AttrNumber *confkey, Oid *conpfeqop)
Definition: tablecmds.c:9330
#define ERROR
Definition: elog.h:43
bool deferrable
Definition: parsenodes.h:2156
#define lfirst_node(type, lc)
Definition: pg_list.h:193
#define NoLock
Definition: lockdefs.h:34
PartitionDesc RelationGetPartitionDesc(Relation rel)
Definition: partdesc.c:65
#define RelationGetRelationName(relation)
Definition: rel.h:490
static AlteredTableInfo * ATGetQueueEntry(List **wqueue, Relation rel)
Definition: tablecmds.c:5388
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3480
#define AssertArg(condition)
Definition: c.h:740
List * lappend(List *list, void *datum)
Definition: list.c:321
ConstrType contype
Definition: tablecmds.c:188
void * palloc0(Size size)
Definition: mcxt.c:980
void CommandCounterIncrement(void)
Definition: xact.c:1005
#define InvalidOid
Definition: postgres_ext.h:36
bool initially_valid
Definition: parsenodes.h:2198
#define ereport(elevel,...)
Definition: elog.h:144
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc)
Definition: attmap.c:174
char fk_del_action
Definition: parsenodes.h:2191
AttrNumber * attnums
Definition: attmap.h:36
#define INDEX_MAX_KEYS
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
List * RelationGetFKeyList(Relation relation)
Definition: relcache.c:4397
int errmsg(const char *fmt,...)
Definition: elog.c:824
int i
#define copyObject(obj)
Definition: nodes.h:645
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
bool skip_validation
Definition: parsenodes.h:2197
#define RelationGetRelid(relation)
Definition: rel.h:456
List * fk_attrs
Definition: parsenodes.h:2187
char fk_upd_action
Definition: parsenodes.h:2190
#define RelationGetNamespace(relation)
Definition: rel.h:497

◆ AlterIndexNamespaces()

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

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

15011 {
15012  List *indexList;
15013  ListCell *l;
15014 
15015  indexList = RelationGetIndexList(rel);
15016 
15017  foreach(l, indexList)
15018  {
15019  Oid indexOid = lfirst_oid(l);
15020  ObjectAddress thisobj;
15021 
15022  thisobj.classId = RelationRelationId;
15023  thisobj.objectId = indexOid;
15024  thisobj.objectSubId = 0;
15025 
15026  /*
15027  * Note: currently, the index will not have its own dependency on the
15028  * namespace, so we don't need to do changeDependencyFor(). There's no
15029  * row type in pg_type, either.
15030  *
15031  * XXX this objsMoved test may be pointless -- surely we have a single
15032  * dependency link from a relation to each index?
15033  */
15034  if (!object_address_present(&thisobj, objsMoved))
15035  {
15036  AlterRelationNamespaceInternal(classRel, indexOid,
15037  oldNspOid, newNspOid,
15038  false, objsMoved);
15039  add_exact_object_address(&thisobj, objsMoved);
15040  }
15041  }
15042 
15043  list_free(indexList);
15044 }
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2530
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2470
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:14939
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4506
void list_free(List *list)
Definition: list.c:1376
Definition: pg_list.h:50
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ AlterRelationNamespaceInternal()

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

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

14943 {
14944  HeapTuple classTup;
14945  Form_pg_class classForm;
14946  ObjectAddress thisobj;
14947  bool already_done = false;
14948 
14949  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
14950  if (!HeapTupleIsValid(classTup))
14951  elog(ERROR, "cache lookup failed for relation %u", relOid);
14952  classForm = (Form_pg_class) GETSTRUCT(classTup);
14953 
14954  Assert(classForm->relnamespace == oldNspOid);
14955 
14956  thisobj.classId = RelationRelationId;
14957  thisobj.objectId = relOid;
14958  thisobj.objectSubId = 0;
14959 
14960  /*
14961  * If the object has already been moved, don't move it again. If it's
14962  * already in the right place, don't move it, but still fire the object
14963  * access hook.
14964  */
14965  already_done = object_address_present(&thisobj, objsMoved);
14966  if (!already_done && oldNspOid != newNspOid)
14967  {
14968  /* check for duplicate name (more friendly than unique-index failure) */
14969  if (get_relname_relid(NameStr(classForm->relname),
14970  newNspOid) != InvalidOid)
14971  ereport(ERROR,
14972  (errcode(ERRCODE_DUPLICATE_TABLE),
14973  errmsg("relation \"%s\" already exists in schema \"%s\"",
14974  NameStr(classForm->relname),
14975  get_namespace_name(newNspOid))));
14976 
14977  /* classTup is a copy, so OK to scribble on */
14978  classForm->relnamespace = newNspOid;
14979 
14980  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
14981 
14982  /* Update dependency on schema if caller said so */
14983  if (hasDependEntry &&
14984  changeDependencyFor(RelationRelationId,
14985  relOid,
14986  NamespaceRelationId,
14987  oldNspOid,
14988  newNspOid) != 1)
14989  elog(ERROR, "failed to change schema dependency for relation \"%s\"",
14990  NameStr(classForm->relname));
14991  }
14992  if (!already_done)
14993  {
14994  add_exact_object_address(&thisobj, objsMoved);
14995 
14996  InvokeObjectPostAlterHook(RelationRelationId, relOid, 0);
14997  }
14998 
14999  heap_freetuple(classTup);
15000 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2530
int errcode(int sqlerrcode)
Definition: elog.c:610
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2470
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:1748
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3155
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:738
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
int errmsg(const char *fmt,...)
Definition: elog.c:824
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:297
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:615

◆ AlterSeqNamespaces()

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

Definition at line 15054 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, DropRelationCallbackState::relkind, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), and table_open().

Referenced by AlterTableNamespaceInternal().

15057 {
15058  Relation depRel;
15059  SysScanDesc scan;
15060  ScanKeyData key[2];
15061  HeapTuple tup;
15062 
15063  /*
15064  * SERIAL sequences are those having an auto dependency on one of the
15065  * table's columns (we don't care *which* column, exactly).
15066  */
15067  depRel = table_open(DependRelationId, AccessShareLock);
15068 
15069  ScanKeyInit(&key[0],
15070  Anum_pg_depend_refclassid,
15071  BTEqualStrategyNumber, F_OIDEQ,
15072  ObjectIdGetDatum(RelationRelationId));
15073  ScanKeyInit(&key[1],
15074  Anum_pg_depend_refobjid,
15075  BTEqualStrategyNumber, F_OIDEQ,
15077  /* we leave refobjsubid unspecified */
15078 
15079  scan = systable_beginscan(depRel, DependReferenceIndexId, true,
15080  NULL, 2, key);
15081 
15082  while (HeapTupleIsValid(tup = systable_getnext(scan)))
15083  {
15084  Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
15085  Relation seqRel;
15086 
15087  /* skip dependencies other than auto dependencies on columns */
15088  if (depForm->refobjsubid == 0 ||
15089  depForm->classid != RelationRelationId ||
15090  depForm->objsubid != 0 ||
15091  !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
15092  continue;
15093 
15094  /* Use relation_open just in case it's an index */
15095  seqRel = relation_open(depForm->objid, lockmode);
15096 
15097  /* skip non-sequence relations */
15098  if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
15099  {
15100  /* No need to keep the lock */
15101  relation_close(seqRel, lockmode);
15102  continue;
15103  }
15104 
15105  /* Fix the pg_class and pg_depend entries */
15106  AlterRelationNamespaceInternal(classRel, depForm->objid,
15107  oldNspOid, newNspOid,
15108  true, objsMoved);
15109 
15110  /*
15111  * Sequences have entries in pg_type. We need to be careful to move
15112  * them to the new namespace, too.
15113  */
15115  newNspOid, false, false, objsMoved);
15116 
15117  /* Now we can close it. Keep the lock till end of transaction. */
15118  relation_close(seqRel, NoLock);
15119  }
15120 
15121  systable_endscan(scan);
15122 
15124 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:529
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define RelationGetForm(relation)
Definition: rel.h:450
#define DependReferenceIndexId
Definition: indexing.h:151
#define AccessShareLock
Definition: lockdefs.h:36
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:3510
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:356
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:448
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:71
#define 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:14939
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:456
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ AlterTable()

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

Definition at line 3564 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3566 {
3567  Relation rel;
3568 
3569  /* Caller is required to provide an adequate lock. */
3570  rel = relation_open(context->relid, NoLock);
3571 
3572  CheckTableNotInUse(rel, "ALTER TABLE");
3573 
3574  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
3575 }
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:3899
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:3480
bool inh
Definition: primnodes.h:69
RangeVar * relation
Definition: parsenodes.h:1777

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)

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

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

◆ AlterTableInternal()

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

Definition at line 3593 of file tablecmds.c.

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

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

3594 {
3595  Relation rel;
3596  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
3597 
3598  rel = relation_open(relid, lockmode);
3599 
3601 
3602  ATController(NULL, rel, cmds, recurse, lockmode, NULL);
3603 }
int LOCKMODE
Definition: lockdefs.h:26
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:3899
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:3638
void EventTriggerAlterTableRelid(Oid objectId)

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 3508 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3509 {
3510  return RangeVarGetRelidExtended(stmt->relation, lockmode,
3511  stmt->missing_ok ? RVR_MISSING_OK : 0,
3513  (void *) stmt);
3514 }
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:15453
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:236
RangeVar * relation
Definition: parsenodes.h:1777

◆ AlterTableMoveAll()

Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

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

13135 {
13136  List *relations = NIL;
13137  ListCell *l;
13138  ScanKeyData key[1];
13139  Relation rel;
13140  TableScanDesc scan;
13141  HeapTuple tuple;
13142  Oid orig_tablespaceoid;
13143  Oid new_tablespaceoid;
13144  List *role_oids = roleSpecsToIds(stmt->roles);
13145 
13146  /* Ensure we were not asked to move something we can't */
13147  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
13148  stmt->objtype != OBJECT_MATVIEW)
13149  ereport(ERROR,
13150  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
13151  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
13152 
13153  /* Get the orig and new tablespace OIDs */
13154  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
13155  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
13156 
13157  /* Can't move shared relations in to or out of pg_global */
13158  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
13159  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
13160  new_tablespaceoid == GLOBALTABLESPACE_OID)
13161  ereport(ERROR,
13162  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
13163  errmsg("cannot move relations in to or out of pg_global tablespace")));
13164 
13165  /*
13166  * Must have CREATE rights on the new tablespace, unless it is the
13167  * database default tablespace (which all users implicitly have CREATE
13168  * rights on).
13169  */
13170  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
13171  {
13172  AclResult aclresult;
13173 
13174  aclresult = pg_tablespace_aclcheck(new_tablespaceoid, GetUserId(),
13175  ACL_CREATE);
13176  if (aclresult != ACLCHECK_OK)
13177  aclcheck_error(aclresult, OBJECT_TABLESPACE,
13178  get_tablespace_name(new_tablespaceoid));
13179  }
13180 
13181  /*
13182  * Now that the checks are done, check if we should set either to
13183  * InvalidOid because it is our database's default tablespace.
13184  */
13185  if (orig_tablespaceoid == MyDatabaseTableSpace)
13186  orig_tablespaceoid = InvalidOid;
13187 
13188  if (new_tablespaceoid == MyDatabaseTableSpace)
13189  new_tablespaceoid = InvalidOid;
13190 
13191  /* no-op */
13192  if (orig_tablespaceoid == new_tablespaceoid)
13193  return new_tablespaceoid;
13194 
13195  /*
13196  * Walk the list of objects in the tablespace and move them. This will
13197  * only find objects in our database, of course.
13198  */
13199  ScanKeyInit(&key[0],
13200  Anum_pg_class_reltablespace,
13201  BTEqualStrategyNumber, F_OIDEQ,
13202  ObjectIdGetDatum(orig_tablespaceoid));
13203 
13204  rel = table_open(RelationRelationId, AccessShareLock);
13205  scan = table_beginscan_catalog(rel, 1, key);
13206  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
13207  {
13208  Form_pg_class relForm = (Form_pg_class) GETSTRUCT(tuple);
13209  Oid relOid = relForm->oid;
13210 
13211  /*
13212  * Do not move objects in pg_catalog as part of this, if an admin
13213  * really wishes to do so, they can issue the individual ALTER
13214  * commands directly.
13215  *
13216  * Also, explicitly avoid any shared tables, temp tables, or TOAST
13217  * (TOAST will be moved with the main table).
13218  */
13219  if (IsCatalogNamespace(relForm->relnamespace) ||
13220  relForm->relisshared ||
13221  isAnyTempNamespace(relForm->relnamespace) ||
13222  IsToastNamespace(relForm->relnamespace))
13223  continue;
13224 
13225  /* Only move the object type requested */
13226  if ((stmt->objtype == OBJECT_TABLE &&
13227  relForm->relkind != RELKIND_RELATION &&
13228  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
13229  (stmt->objtype == OBJECT_INDEX &&
13230  relForm->relkind != RELKIND_INDEX &&
13231  relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
13232  (stmt->objtype == OBJECT_MATVIEW &&
13233  relForm->relkind != RELKIND_MATVIEW))
13234  continue;
13235 
13236  /* Check if we are only moving objects owned by certain roles */
13237  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
13238  continue;
13239 
13240  /*
13241  * Handle permissions-checking here since we are locking the tables
13242  * and also to avoid doing a bunch of work only to fail part-way. Note
13243  * that permissions will also be checked by AlterTableInternal().
13244  *
13245  * Caller must be considered an owner on the table to move it.
13246  */
13247  if (!pg_class_ownercheck(relOid, GetUserId()))
13249  NameStr(relForm->relname));
13250 
13251  if (stmt->nowait &&
13253  ereport(ERROR,
13254  (errcode(ERRCODE_OBJECT_IN_USE),
13255  errmsg("aborting because lock on relation \"%s.%s\" is not available",
13256  get_namespace_name(relForm->relnamespace),
13257  NameStr(relForm->relname))));
13258  else
13260 
13261  /* Add to our list of objects to move */
13262  relations = lappend_oid(relations, relOid);
13263  }
13264 
13265  table_endscan(scan);
13267 
13268  if (relations == NIL)
13269  ereport(NOTICE,
13270  (errcode(ERRCODE_NO_DATA_FOUND),
13271  errmsg("no matching relations in tablespace \"%s\" found",
13272  orig_tablespaceoid == InvalidOid ? "(database default)" :
13273  get_tablespace_name(orig_tablespaceoid))));
13274 
13275  /* Everything is locked, loop through and move all of the relations. */
13276  foreach(l, relations)
13277  {
13278  List *cmds = NIL;
13280 
13281  cmd->subtype = AT_SetTableSpace;
13282  cmd->name = stmt->new_tablespacename;
13283 
13284  cmds = lappend(cmds, cmd);
13285 
13287  /* OID is set by AlterTableInternal */
13288  AlterTableInternal(lfirst_oid(l), cmds, false);
13290  }
13291 
13292  return new_tablespaceoid;
13293 }
#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:448
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1866
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:529
int errcode(int sqlerrcode)
Definition: elog.c:610
AlterTableType subtype
Definition: parsenodes.h:1863
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:195
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
#define OidIsValid(objectId)
Definition: c.h:644
Oid MyDatabaseTableSpace
Definition: globals.c:87
void EventTriggerAlterTableStart(Node *parsetree)
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c: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:3155
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1290
List * lappend(List *list, void *datum)
Definition: list.c:321
AclResult
Definition: acl.h:177
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define NOTICE
Definition: elog.h:37
#define makeNode(_type_)
Definition: nodes.h:577
List * roleSpecsToIds(List *memberNames)
Definition: user.c:1423
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:674
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4753
bool IsCatalogNamespace(Oid namespaceId)
Definition: catalog.c:177
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:862
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:3593
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:824
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1462
ObjectType get_relkind_objtype(char relkind)
#define NameStr(name)
Definition: c.h:615
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
bool isAnyTempNamespace(Oid namespaceId)
Definition: namespace.c:3195
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:108
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define lfirst_oid(lc)
Definition: pg_list.h:192
void EventTriggerAlterTableEnd(void)

◆ AlterTableNamespace()

ObjectAddress AlterTableNamespace ( AlterObjectSchemaStmt stmt,
Oid oldschema 
)

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

14831 {
14832  Relation rel;
14833  Oid relid;
14834  Oid oldNspOid;
14835  Oid nspOid;
14836  RangeVar *newrv;
14837  ObjectAddresses *objsMoved;
14838  ObjectAddress myself;
14839 
14841  stmt->missing_ok ? RVR_MISSING_OK : 0,
14843  (void *) stmt);
14844 
14845  if (!OidIsValid(relid))
14846  {
14847  ereport(NOTICE,
14848  (errmsg("relation \"%s\" does not exist, skipping",
14849  stmt->relation->relname)));
14850  return InvalidObjectAddress;
14851  }
14852 
14853  rel = relation_open(relid, NoLock);
14854 
14855  oldNspOid = RelationGetNamespace(rel);
14856 
14857  /* If it's an owned sequence, disallow moving it by itself. */
14858  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
14859  {
14860  Oid tableId;
14861  int32 colId;
14862 
14863  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
14864  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
14865  ereport(ERROR,
14866  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14867  errmsg("cannot move an owned sequence into another schema"),
14868  errdetail("Sequence \"%s\" is linked to table \"%s\".",
14870  get_rel_name(tableId))));
14871  }
14872 
14873  /* Get and lock schema OID and check its permissions. */
14874  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
14875  nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
14876 
14877  /* common checks on switching namespaces */
14878  CheckSetNamespace(oldNspOid, nspOid);
14879 
14880  objsMoved = new_object_addresses();
14881  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
14882  free_object_addresses(objsMoved);
14883 
14884  ObjectAddressSet(myself, RelationRelationId, relid);
14885 
14886  if (oldschema)
14887  *oldschema = oldNspOid;
14888 
14889  /* close rel, but keep lock until commit */
14890  relation_close(rel, NoLock);
14891 
14892  return myself;
14893 }
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition: pg_depend.c:706
int errcode(int sqlerrcode)
Definition: elog.c:610
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2415
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2710
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:644
signed int int32
Definition: c.h:355
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
void AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:14901
#define NoLock
Definition: lockdefs.h:34
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:15453
int errdetail(const char *fmt,...)
Definition: elog.c:957
#define RelationGetRelationName(relation)
Definition: rel.h:490
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:236
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition: namespace.c:2967
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:534
#define ereport(elevel,...)
Definition: elog.h:144
#define NOTICE
Definition: elog.h:37
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define AccessExclusiveLock
Definition: lockdefs.h:45
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:824
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1791
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:420
#define RelationGetNamespace(relation)
Definition: rel.h:497

◆ AlterTableNamespaceInternal()

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

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

14903 {
14904  Relation classRel;
14905 
14906  Assert(objsMoved != NULL);
14907 
14908  /* OK, modify the pg_class row and pg_depend entry */
14909  classRel = table_open(RelationRelationId, RowExclusiveLock);
14910 
14911  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
14912  nspOid, true, objsMoved);
14913 
14914  /* Fix the table's row type too */
14915  AlterTypeNamespaceInternal(rel->rd_rel->reltype,
14916  nspOid, false, false, objsMoved);
14917 
14918  /* Fix other dependent stuff */
14919  if (rel->rd_rel->relkind == RELKIND_RELATION ||
14920  rel->rd_rel->relkind == RELKIND_MATVIEW ||
14921  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
14922  {
14923  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
14924  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
14925  objsMoved, AccessExclusiveLock);
14926  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
14927  false, objsMoved);
14928  }
14929 
14930  table_close(classRel, RowExclusiveLock);
14931 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:3510
Form_pg_class rd_rel
Definition: rel.h:109
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:15009
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:15054
#define RowExclusiveLock
Definition: lockdefs.h:38
#define Assert(condition)
Definition: c.h:738
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:14939
#define AccessExclusiveLock
Definition: lockdefs.h:45
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:456

◆ ATAddCheckConstraint()

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

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

7956 {
7957  List *newcons;
7958  ListCell *lcon;
7959  List *children;
7960  ListCell *child;
7962 
7963  /* At top level, permission check was done in ATPrepCmd, else do it */
7964  if (recursing)
7966 
7967  /*
7968  * Call AddRelationNewConstraints to do the work, making sure it works on
7969  * a copy of the Constraint so transformExpr can't modify the original. It
7970  * returns a list of cooked constraints.
7971  *
7972  * If the constraint ends up getting merged with a pre-existing one, it's
7973  * omitted from the returned list, which is what we want: we do not need
7974  * to do any validation work. That can only happen at child tables,
7975  * though, since we disallow merging at the top level.
7976  */
7977  newcons = AddRelationNewConstraints(rel, NIL,
7978  list_make1(copyObject(constr)),
7979  recursing | is_readd, /* allow_merge */
7980  !recursing, /* is_local */
7981  is_readd, /* is_internal */
7982  NULL); /* queryString not available
7983  * here */
7984 
7985  /* we don't expect more than one constraint here */
7986  Assert(list_length(newcons) <= 1);
7987 
7988  /* Add each to-be-validated constraint to Phase 3's queue */
7989  foreach(lcon, newcons)
7990  {
7991  CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
7992 
7993  if (!ccon->skip_validation)
7994  {
7995  NewConstraint *newcon;
7996 
7997  newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
7998  newcon->name = ccon->name;
7999  newcon->contype = ccon->contype;
8000  newcon->qual = ccon->expr;
8001 
8002  tab->constraints = lappend(tab->constraints, newcon);
8003  }
8004 
8005  /* Save the actually assigned name if it was defaulted */
8006  if (constr->conname == NULL)
8007  constr->conname = ccon->name;
8008 
8009  ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
8010  }
8011 
8012  /* At this point we must have a locked-down name to use */
8013  Assert(constr->conname != NULL);
8014 
8015  /* Advance command counter in case same table is visited multiple times */
8017 
8018  /*
8019  * If the constraint got merged with an existing constraint, we're done.
8020  * We mustn't recurse to child tables in this case, because they've
8021  * already got the constraint, and visiting them again would lead to an
8022  * incorrect value for coninhcount.
8023  */
8024  if (newcons == NIL)
8025  return address;
8026 
8027  /*
8028  * If adding a NO INHERIT constraint, no need to find our children.
8029  */
8030  if (constr->is_no_inherit)
8031  return address;
8032 
8033  /*
8034  * Propagate to children as appropriate. Unlike most other ALTER
8035  * routines, we have to do this one level of recursion at a time; we can't
8036  * use find_all_inheritors to do it in one pass.
8037  */
8038  children = find_inheritance_children(RelationGetRelid(rel), lockmode);
8039 
8040  /*
8041  * Check if ONLY was specified with ALTER TABLE. If so, allow the
8042  * constraint creation only if there are no children currently. Error out
8043  * otherwise.
8044  */
8045  if (!recurse && children != NIL)
8046  ereport(ERROR,
8047  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
8048  errmsg("constraint must be added to child tables too")));
8049 
8050  foreach(child, children)
8051  {
8052  Oid childrelid = lfirst_oid(child);
8053  Relation childrel;
8054  AlteredTableInfo *childtab;
8055 
8056  /* find_inheritance_children already got lock */
8057  childrel = table_open(childrelid, NoLock);
8058  CheckTableNotInUse(childrel, "ALTER TABLE");
8059 
8060  /* Find or create work queue entry for this table */
8061  childtab = ATGetQueueEntry(wqueue, childrel);
8062 
8063  /* Recurse to child */
8064  ATAddCheckConstraint(wqueue, childtab, childrel,
8065  constr, recurse, true, is_readd, lockmode);
8066 
8067  table_close(childrel, NoLock);
8068  }
8069 
8070  return address;
8071 }
#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:2523
char * name
Definition: tablecmds.c:187
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Node * qual
Definition: tablecmds.c:192
int errcode(int sqlerrcode)
Definition: elog.c:610
static ObjectAddress ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *constr, bool recurse, bool recursing, bool is_readd, LOCKMODE lockmode)
Definition: tablecmds.c:7953
char * conname
Definition: parsenodes.h:2155
unsigned int Oid
Definition: postgres_ext.h:31
#define ATT_TABLE
Definition: tablecmds.c:292
List * constraints
Definition: tablecmds.c:163
#define list_make1(x1)
Definition: pg_list.h:227
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
static AlteredTableInfo * ATGetQueueEntry(List **wqueue, Relation rel)
Definition: tablecmds.c:5388
bool skip_validation
Definition: heap.h:42
ConstrType contype
Definition: heap.h:37
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3480
List * lappend(List *list, void *datum)
Definition: list.c:321
ConstrType contype
Definition: tablecmds.c:188
void * palloc0(Size size)
Definition: mcxt.c:980
void CommandCounterIncrement(void)
Definition: xact.c:1005
bool is_no_inherit
Definition: parsenodes.h:2161
List * find_inheritance_children(Oid parentrelId, LOCKMODE lockmode)
Definition: pg_inherits.c:55
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:738
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:824
Oid conoid
Definition: heap.h:38
Node * expr
Definition: heap.h:41
static void ATSimplePermissions(Relation rel, int allowed_targets)
Definition: tablecmds.c:5425
#define copyObject(obj)
Definition: nodes.h:645
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define ATT_FOREIGN_TABLE
Definition: tablecmds.c:297
char * name
Definition: heap.h:39
#define RelationGetRelid(relation)
Definition: rel.h:456
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ ATAddForeignKeyConstraint()

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

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

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

◆ ATCheckPartitionsNotInUse()

static void ATCheckPartitionsNotInUse ( Relation  rel,
LOCKMODE  lockmode 
)
static

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

5593 {
5594  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
5595  {
5596  List *inh;
5597  ListCell *cell;
5598 
5599  inh = find_all_inheritors(RelationGetRelid(rel), lockmode, NULL);
5600  /* first element is the parent rel; must ignore it */
5601  for_each_cell(cell, inh, list_second_cell(inh))
5602  {
5603  Relation childrel;
5604 
5605  /* find_all_inheritors already got lock */
5606  childrel = table_open(lfirst_oid(cell), NoLock);
5607  CheckTableNotInUse(childrel, "ALTER TABLE");
5608  table_close(childrel, NoLock);
5609  }
5610  list_free(inh);
5611  }
5612 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:390
Form_pg_class rd_rel
Definition: rel.h:109
#define NoLock
Definition: lockdefs.h:34
static ListCell * list_second_cell(const List *l)
Definition: pg_list.h:139
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3480
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:165
void list_free(List *list)
Definition: list.c:1376
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:456
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ ATColumnChangeRequiresRewrite()

static bool ATColumnChangeRequiresRewrite ( Node expr,
AttrNumber  varattno 
)
static

Definition at line 11032 of file tablecmds.c.

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

Referenced by ATPrepAlterColumnType().

11033 {
11034  Assert(expr != NULL);
11035 
11036  for (;;)
11037  {
11038  /* only one varno, so no need to check that */
11039  if (IsA(expr, Var) &&((Var *) expr)->varattno == varattno)
11040  return false;
11041  else if (IsA(expr, RelabelType))
11042  expr = (Node *) ((RelabelType *) expr)->arg;
11043  else if (IsA(expr, CoerceToDomain))
11044  {
11045  CoerceToDomain *d = (CoerceToDomain *) expr;
11046 
11048  return true;
11049  expr = (Node *) d->arg;
11050  }
11051  else if (IsA(expr, FuncExpr))
11052  {
11053  FuncExpr *f = (FuncExpr *) expr;
11054 
11055  switch (f->funcid)
11056  {
11057  case F_TIMESTAMPTZ_TIMESTAMP:
11058  case F_TIMESTAMP_TIMESTAMPTZ:
11060  return true;
11061  else
11062  expr = linitial(f->args);
11063  break;
11064  default:
11065  return true;
11066  }
11067  }
11068  else
11069  return true;
11070  }
11071 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
List * args
Definition: primnodes.h:477
Definition: nodes.h:529
Definition: primnodes.h:181
bool DomainHasConstraints(Oid type_id)
Definition: typcache.c:1347
#define linitial(l)
Definition: pg_list.h:195
Oid funcid
Definition: primnodes.h:469
#define Assert(condition)
Definition: c.h:738
void * arg
bool TimestampTimestampTzRequiresRewrite(void)
Definition: timestamp.c:5161

◆ ATController()

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

Definition at line 3899 of file tablecmds.c.

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

Referenced by AlterTable(), and AlterTableInternal().

3902 {
3903  List *wqueue = NIL;
3904  ListCell *lcmd;
3905 
3906  /* Phase 1: preliminary examination of commands, create work queue */
3907  foreach(lcmd, cmds)
3908  {
3909  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3910 
3911  ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode, context);
3912  }
3913 
3914  /* Close the relation, but keep lock until commit */
3915  relation_close(rel, NoLock);
3916 
3917  /* Phase 2: update system catalogs */
3918  ATRewriteCatalogs(&wqueue, lockmode, context);
3919 
3920  /* Phase 3: scan/rewrite tables as needed, and run afterStmts */
3921  ATRewriteTables(parsetree, &wqueue, lockmode, context);
3922 }
#define NIL
Definition: pg_list.h:65
static void ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition: tablecmds.c:4764
#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:3934
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:4256
Definition: pg_list.h:50

◆ ATDetachCheckNoForeignKeyRefs()

static void ATDetachCheckNoForeignKeyRefs ( Relation  partition)
static

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

17274 {
17275  List *constraints;
17276  ListCell *cell;
17277 
17278  constraints = GetParentedForeignKeyRefs(partition);
17279 
17280  foreach(cell, constraints)
17281  {
17282  Oid constrOid = lfirst_oid(cell);
17283  HeapTuple tuple;
17284  Form_pg_constraint constrForm;
17285  Relation rel;
17286  Trigger trig;
17287 
17288  tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
17289  if (!HeapTupleIsValid(tuple))
17290  elog(ERROR, "cache lookup failed for constraint %u", constrOid);
17291  constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
17292 
17293  Assert(OidIsValid(constrForm->conparentid));
17294  Assert(constrForm->confrelid == RelationGetRelid(partition));
17295 
17296  /* prevent data changes into the referencing table until commit */
17297  rel = table_open(constrForm->conrelid, ShareLock);
17298 
17299  MemSet(&trig, 0, sizeof(trig));
17300  trig.tgoid = InvalidOid;
17301  trig.tgname = NameStr(constrForm->conname);
17303  trig.tgisinternal = true;
17304  trig.tgconstrrelid = RelationGetRelid(partition);
17305  trig.tgconstrindid = constrForm->conindid;
17306  trig.tgconstraint = constrForm->oid;
17307  trig.tgdeferrable = false;
17308  trig.tginitdeferred = false;
17309  /* we needn't fill in remaining fields */
17310 
17311  RI_PartitionRemove_Check(&trig, rel, partition);
17312 
17313  ReleaseSysCache(tuple);
17314 
17315  table_close(rel, NoLock);
17316  }
17317 }
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:17220
Oid tgoid
Definition: reltrigger.h:25
bool tgisinternal
Definition: reltrigger.h:31
#define MemSet(start, val, len)
Definition: c.h:971
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:644
#define TRIGGER_FIRES_ON_ORIGIN
Definition: trigger.h:156
char tgenabled
Definition: reltrigger.h:30
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Oid tgconstraint
Definition: reltrigger.h:35
char * tgname
Definition: reltrigger.h:27
void RI_PartitionRemove_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
Definition: ri_triggers.c:1570
bool tgdeferrable
Definition: reltrigger.h:36
bool tginitdeferred
Definition: reltrigger.h:37
#define NoLock
Definition: lockdefs.h:34
Oid tgconstrrelid
Definition: reltrigger.h:33
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define InvalidOid
Definition: postgres_ext.h:36
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:738
Oid tgconstrindid
Definition: reltrigger.h:34
#define elog(elevel,...)
Definition: elog.h:214
#define ShareLock
Definition: lockdefs.h:41
#define NameStr(name)
Definition: c.h:615
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:456
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ AtEOSubXact_on_commit_actions()

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

Definition at line 15330 of file tablecmds.c.

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

15332 {
15333  ListCell *cur_item;
15334 
15335  foreach(cur_item, on_commits)
15336  {
15337  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
15338 
15339  if (!isCommit && oc->creating_subid == mySubid)
15340  {
15341  /* cur_item must be removed */
15343  pfree(oc);
15344  }
15345  else
15346  {
15347  /* cur_item must be preserved */
15348  if (oc->creating_subid == mySubid)
15349  oc->creating_subid = parentSubid;
15350  if (oc->deleting_subid == mySubid)
15351  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
15352  }
15353  }
15354 }
SubTransactionId creating_subid
Definition: tablecmds.c:118
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:368
void pfree(void *pointer)
Definition: mcxt.c:1056
static List * on_commits
Definition: tablecmds.c:122
SubTransactionId deleting_subid
Definition: tablecmds.c:119
#define lfirst(lc)
Definition: pg_list.h:190
#define InvalidSubTransactionId
Definition: c.h:519

◆ AtEOXact_on_commit_actions()

void AtEOXact_on_commit_actions ( bool  isCommit)

Definition at line 15298 of file tablecmds.c.

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

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

15299 {
15300  ListCell *cur_item;
15301 
15302  foreach(cur_item, on_commits)
15303  {
15304  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
15305 
15306  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
15308  {
15309  /* cur_item must be removed */
15311  pfree(oc);
15312  }
15313  else
15314  {
15315  /* cur_item must be preserved */
15318  }
15319  }
15320 }
SubTransactionId creating_subid
Definition: tablecmds.c:118
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:368
void pfree(void *pointer)
Definition: mcxt.c:1056
static List * on_commits
Definition: tablecmds.c:122
SubTransactionId deleting_subid
Definition: tablecmds.c:119
#define lfirst(lc)
Definition: pg_list.h:190
#define InvalidSubTransactionId
Definition: c.h:519

◆ ATExecAddColumn()

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

Definition at line 5901 of file tablecmds.c.

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

Referenced by ATExecCmd().

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

◆ ATExecAddConstraint()

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

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

7841 {
7843 
7844  Assert(IsA(newConstraint, Constraint));
7845 
7846  /*
7847  * Currently, we only expect to see CONSTR_CHECK and CONSTR_FOREIGN nodes
7848  * arriving here (see the preprocessing done in parse_utilcmd.c). Use a
7849  * switch anyway to make it easier to add more code later.
7850  */
7851  switch (newConstraint->contype)
7852  {
7853  case CONSTR_CHECK:
7854  address =
7855  ATAddCheckConstraint(wqueue, tab, rel,
7856  newConstraint, recurse, false, is_readd,
7857  lockmode);
7858  break;
7859 
7860  case CONSTR_FOREIGN:
7861 
7862  /*
7863  * Assign or validate constraint name
7864  */
7865  if (newConstraint->conname)
7866  {
7868  RelationGetRelid(rel),
7869  newConstraint->conname))
7870  ereport(ERROR,
7872  errmsg("constraint \"%s\" for relation \"%s\" already exists",
7873  newConstraint->conname,
7874  RelationGetRelationName(rel))));
7875  }
7876  else
7877  newConstraint->conname =
7880  "fkey",
7881  RelationGetNamespace(rel),
7882  NIL);
7883 
7884  address = ATAddForeignKeyConstraint(wqueue, tab, rel,
7885  newConstraint, InvalidOid,
7886  recurse, false,
7887  lockmode);
7888  break;
7889 
7890  default:
7891  elog(ERROR, "unrecognized constraint type: %d",
7892  (int) newConstraint->contype);
7893  }
7894 
7895  return address;
7896 }
#define NIL
Definition: pg_list.h:65
char * ChooseConstraintName(const char *name1, const char *name2, const char *label, Oid namespaceid, List *others)
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
bool ConstraintNameIsUsed(ConstraintCategory conCat, Oid objId, const char *conname)
static char * ChooseForeignKeyConstraintNameAddition(List *colnames)
Definition: tablecmds.c:7911
int errcode(int sqlerrcode)
Definition: elog.c:610
static ObjectAddress ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *constr, bool recurse, bool recursing, bool is_readd, LOCKMODE lockmode)
Definition: tablecmds.c:7953
char * conname
Definition: parsenodes.h:2155
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:490
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:738
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
static ObjectAddress ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *fkconstraint, Oid parentConstr, bool recurse, bool recursing, LOCKMODE lockmode)
Definition: tablecmds.c:8089
ConstrType contype
Definition: parsenodes.h:2152
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:31
#define RelationGetRelid(relation)
Definition: rel.h:456
List * fk_attrs
Definition: parsenodes.h:2187
#define RelationGetNamespace(relation)
Definition: rel.h:497

◆ ATExecAddIdentity()

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

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

6815 {
6816  Relation attrelation;
6817  HeapTuple tuple;
6818  Form_pg_attribute attTup;
6820  ObjectAddress address;
6821  ColumnDef *cdef = castNode(ColumnDef, def);
6822 
6823  attrelation = table_open(AttributeRelationId, RowExclusiveLock);
6824 
6825  tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
6826  if (!HeapTupleIsValid(tuple))
6827  ereport(ERROR,
6828  (errcode(ERRCODE_UNDEFINED_COLUMN),
6829  errmsg("column \"%s\" of relation \"%s\" does not exist",
6830  colName, RelationGetRelationName(rel))));
6831  attTup = (Form_pg_attribute) GETSTRUCT(tuple);
6832  attnum = attTup->attnum;
6833 
6834  /* Can't alter a system attribute */
6835  if (attnum <= 0)
6836  ereport(ERROR,
6837  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6838  errmsg("cannot alter system column \"%s\"",
6839  colName)));
6840 
6841  /*
6842  * Creating a column as identity implies NOT NULL, so adding the identity
6843  * to an existing column that is not NOT NULL would create a state that
6844  * cannot be reproduced without contortions.
6845  */
6846  if (!attTup->attnotnull)
6847  ereport(ERROR,
6848  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6849  errmsg("column \"%s\" of relation \"%s\" must be declared NOT NULL before identity can be added",
6850  colName, RelationGetRelationName(rel))));
6851 
6852  if (attTup->attidentity)
6853  ereport(ERROR,
6854  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6855  errmsg("column \"%s\" of relation \"%s\" is already an identity column",
6856  colName, RelationGetRelationName(rel))));
6857 
6858  if (attTup->atthasdef)
6859  ereport(ERROR,
6860  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6861  errmsg("column \"%s\" of relation \"%s\" already has a default value",
6862  colName, RelationGetRelationName(rel))));
6863 
6864  attTup->attidentity = cdef->identity;
6865  CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
6866 
6867  InvokeObjectPostAlterHook(RelationRelationId,
6868  RelationGetRelid(rel),
6869  attTup->attnum);
6870  ObjectAddressSubSet(address, RelationRelationId,
6871  RelationGetRelid(rel), attnum);
6872  heap_freetuple(tuple);
6873 
6874  table_close(attrelation, RowExclusiveLock);
6875 
6876  return address;
6877 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define castNode(_type_, nodeptr)
Definition: nodes.h:598
char identity
Definition: parsenodes.h:656
int errcode(int sqlerrcode)
Definition: elog.c:610
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCacheCopyAttName(Oid relid, const char *attname)
Definition: syscache.c:1280
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:490
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
int16 attnum
Definition: pg_attribute.h:79
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
int errmsg(const char *fmt,...)
Definition: elog.c:824
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:456

◆ ATExecAddIndex()

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

Definition at line 7686 of file tablecmds.c.

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

Referenced by ATExecCmd().

7688 {
7689  bool check_rights;
7690  bool skip_build;
7691  bool quiet;
7692  ObjectAddress address;
7693 
7694  Assert(IsA(stmt, IndexStmt));
7695  Assert(!stmt->concurrent);
7696 
7697  /* The IndexStmt has already been through transformIndexStmt */
7698  Assert(stmt->transformed);
7699 
7700  /* suppress schema rights check when rebuilding existing index */
7701  check_rights = !is_rebuild;
7702  /* skip index build if phase 3 will do it or we're reusing an old one */
7703  skip_build = tab->rewrite > 0 || OidIsValid(stmt->oldNode);
7704  /* suppress notices when rebuilding existing index */
7705  quiet = is_rebuild;
7706 
7707  address = DefineIndex(RelationGetRelid(rel),
7708  stmt,
7709  InvalidOid, /* no predefined OID */
7710  InvalidOid, /* no parent index */
7711  InvalidOid, /* no parent constraint */
7712  true, /* is_alter_table */
7713  check_rights,
7714  false, /* check_not_in_use - we did it already */
7715  skip_build,
7716  quiet);
7717 
7718  /*
7719  * If TryReuseIndex() stashed a relfilenode for us, we used it for the new
7720  * index instead of building from scratch. Restore associated fields.
7721  * This may store InvalidSubTransactionId in both fields, in which case
7722  * relcache.c will assume it can rebuild the relcache entry. Hence, do
7723  * this after the CCI that made catalog rows visible to any rebuild. The
7724  * DROP of the old edition of this index will have scheduled the storage
7725  * for deletion at commit, so cancel that pending deletion.
7726  */
7727  if (OidIsValid(stmt->oldNode))
7728  {
7729  Relation irel = index_open(address.objectId, NoLock);
7730 
7731  irel->rd_createSubid = stmt->oldCreateSubid;
7733  RelationPreserveStorage(irel->rd_node, true);
7734  index_close(irel, NoLock);
7735  }
7736 
7737  return address;
7738 }
void RelationPreserveStorage(RelFileNode rnode, bool atCommit)
Definition: storage.c:240
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
ObjectAddress DefineIndex(Oid relationId, IndexStmt *stmt, Oid indexRelationId, Oid parentIndexId, Oid parentConstraintId, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
Definition: indexcmds.c:479
SubTransactionId oldCreateSubid
Definition: parsenodes.h:2788
#define OidIsValid(objectId)
Definition: c.h:644
#define NoLock
Definition: lockdefs.h:34
bool transformed
Definition: parsenodes.h:2796
SubTransactionId oldFirstRelfilenodeSubid
Definition: parsenodes.h:2789
SubTransactionId rd_createSubid
Definition: rel.h:102
SubTransactionId rd_firstRelfilenodeSubid
Definition: rel.h:105
#define InvalidOid
Definition: postgres_ext.h:36
RelFileNode rd_node
Definition: rel.h:55
#define Assert(condition)
Definition: c.h:738
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
bool concurrent
Definition: parsenodes.h:2797
#define RelationGetRelid(relation)
Definition: rel.h:456
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132

◆ ATExecAddIndexConstraint()

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

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

7748 {
7749  Oid index_oid = stmt->indexOid;
7750  Relation indexRel;
7751  char *indexName;
7752  IndexInfo *indexInfo;
7753  char *constraintName;
7754  char constraintType;
7755  ObjectAddress address;
7756  bits16 flags;
7757 
7758  Assert(IsA(stmt, IndexStmt));
7759  Assert(OidIsValid(index_oid));
7760  Assert(stmt->isconstraint);
7761 
7762  /*
7763  * Doing this on partitioned tables is not a simple feature to implement,
7764  * so let's punt for now.
7765  */
7766  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
7767  ereport(ERROR,
7768  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7769  errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX is not supported on partitioned tables")));
7770 
7771  indexRel = index_open(index_oid, AccessShareLock);
7772 
7773  indexName = pstrdup(RelationGetRelationName(indexRel));
7774 
7775  indexInfo = BuildIndexInfo(indexRel);
7776 
7777  /* this should have been checked at parse time */
7778  if (!indexInfo->ii_Unique)
7779  elog(ERROR, "index \"%s\" is not unique", indexName);
7780 
7781  /*
7782  * Determine name to assign to constraint. We require a constraint to
7783  * have the same name as the underlying index; therefore, use the index's
7784  * existing name as the default constraint name, and if the user
7785  * explicitly gives some other name for the constraint, rename the index
7786  * to match.
7787  */
7788  constraintName = stmt->idxname;
7789  if (constraintName == NULL)
7790  constraintName = indexName;
7791  else if (strcmp(constraintName, indexName) != 0)
7792  {
7793  ereport(NOTICE,
7794  (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
7795  indexName, constraintName)));
7796  RenameRelationInternal(index_oid, constraintName, false, true);
7797  }
7798 
7799  /* Extra checks needed if making primary key */
7800  if (stmt->primary)
7801  index_check_primary_key(rel, indexInfo, true, stmt);
7802 
7803  /* Note we currently don't support EXCLUSION constraints here */
7804  if (stmt->primary)
7805  constraintType = CONSTRAINT_PRIMARY;
7806  else
7807  constraintType = CONSTRAINT_UNIQUE;
7808 
7809  /* Create the catalog entries for the constraint */
7815 
7816  address = index_constraint_create(rel,
7817  index_oid,
7818  InvalidOid,
7819  indexInfo,
7820  constraintName,
7821  constraintType,
7822  flags,
7824  false); /* is_internal */
7825 
7826  index_close(indexRel, NoLock);
7827 
7828  return address;
7829 }
bool deferrable
Definition: parsenodes.h:2794
bool primary
Definition: parsenodes.h:2792
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
uint16 bits16
Definition: c.h:375
char * pstrdup(const char *in)
Definition: mcxt.c:1186
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:610
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2312
#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:202
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:644
#define INDEX_CONSTR_CREATE_INIT_DEFERRED
Definition: index.h:77
Oid indexOid
Definition: parsenodes.h:2786
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:490
char * idxname
Definition: parsenodes.h:2775
bool allowSystemTableMods
Definition: globals.c:120
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define NOTICE
Definition: elog.h:37
bool ii_Unique
Definition: execnodes.h:172
#define Assert(condition)
Definition: c.h:738
bool initdeferred
Definition: parsenodes.h:2795
#define INDEX_CONSTR_CREATE_UPDATE_INDEX
Definition: index.h:78
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
bool isconstraint
Definition: parsenodes.h:2793
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
Definition: tablecmds.c:3378
#define INDEX_CONSTR_CREATE_DEFERRABLE
Definition: index.h:76
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
#define INDEX_CONSTR_CREATE_MARK_AS_PRIMARY
Definition: index.h:75
ObjectAddress index_constraint_create(Relation heapRelation, Oid indexRelationId, Oid parentConstraintId, IndexInfo *indexInfo, const char *constraintName, char constraintType, bits16 constr_flags, bool allow_system_table_mods, bool is_internal)
Definition: index.c:1806

◆ ATExecAddInherit()