PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
tablecmds.c File Reference
#include "postgres.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/multixact.h"
#include "access/reloptions.h"
#include "access/relscan.h"
#include "access/sysattr.h"
#include "access/tupconvert.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/objectaccess.h"
#include "catalog/partition.h"
#include "catalog/pg_am.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_constraint_fn.h"
#include "catalog/pg_depend.h"
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_inherits_fn.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/pg_type_fn.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/clauses.h"
#include "optimizer/planner.h"
#include "optimizer/predtest.h"
#include "optimizer/prep.h"
#include "optimizer/var.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 "pgstat.h"
#include "rewrite/rewriteDefine.h"
#include "rewrite/rewriteHandler.h"
#include "rewrite/rewriteManip.h"
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "storage/lock.h"
#include "storage/predicate.h"
#include "storage/smgr.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/relcache.h"
#include "utils/ruleutils.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/tqual.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
 

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_COL_ATTRS   4 /* set other column attributes */
 
#define AT_PASS_ADD_COL   5 /* ADD COLUMN */
 
#define AT_PASS_ADD_INDEX   6 /* ADD indexes */
 
#define AT_PASS_ADD_CONSTR   7 /* ADD constraints, defaults */
 
#define AT_PASS_MISC   8 /* other stuff */
 
#define AT_NUM_PASSES   9
 
#define ATT_TABLE   0x0001
 
#define ATT_VIEW   0x0002
 
#define ATT_MATVIEW   0x0004
 
#define ATT_INDEX   0x0008
 
#define ATT_COMPOSITE_TYPE   0x0010
 
#define ATT_FOREIGN_TABLE   0x0020
 
#define 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 (Relation rel)
 
static ListMergeAttributes (List *schema, List *supers, char relpersistence, bool is_partition, List **supOids, List **supconstr, int *supOidCount)
 
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, int16 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 createForeignKeyTriggers (Relation rel, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid)
 
static void ATController (AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
 
static void ATPrepCmd (List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
 
static void ATRewriteCatalogs (List **wqueue, LOCKMODE lockmode)
 
static void ATExecCmd (List **wqueue, AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static void ATRewriteTables (AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode)
 
static void ATRewriteTable (AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode)
 
static AlteredTableInfoATGetQueueEntry (List **wqueue, Relation rel)
 
static void ATSimplePermissions (Relation rel, int allowed_targets)
 
static void ATWrongRelkindError (Relation rel, int allowed_targets)
 
static void ATSimpleRecursion (List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode)
 
static void ATTypedTableRecursion (List **wqueue, Relation rel, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static Listfind_typed_table_dependencies (Oid typeOid, const char *typeName, DropBehavior behavior)
 
static void ATPrepAddColumn (List **wqueue, Relation rel, bool recurse, bool recursing, bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static ObjectAddress ATExecAddColumn (List **wqueue, AlteredTableInfo *tab, Relation rel, ColumnDef *colDef, bool isOid, bool recurse, bool recursing, bool if_not_exists, LOCKMODE lockmode)
 
static bool check_for_column_name_collision (Relation rel, const char *colname, bool if_not_exists)
 
static void add_column_datatype_dependency (Oid relid, int32 attnum, Oid typid)
 
static void add_column_collation_dependency (Oid relid, int32 attnum, Oid collid)
 
static void ATPrepAddOids (List **wqueue, Relation rel, bool recurse, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static void ATPrepDropNotNull (Relation rel, bool recurse, bool recursing)
 
static ObjectAddress ATExecDropNotNull (Relation rel, const char *colName, LOCKMODE lockmode)
 
static void ATPrepSetNotNull (Relation rel, bool recurse, bool recursing)
 
static ObjectAddress ATExecSetNotNull (AlteredTableInfo *tab, Relation rel, const char *colName, LOCKMODE lockmode)
 
static ObjectAddress ATExecColumnDefault (Relation rel, const char *colName, Node *newDefault, LOCKMODE lockmode)
 
static ObjectAddress ATExecAddIdentity (Relation rel, const char *colName, Node *def, LOCKMODE lockmode)
 
static ObjectAddress ATExecSetIdentity (Relation rel, const char *colName, Node *def, LOCKMODE lockmode)
 
static ObjectAddress ATExecDropIdentity (Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode)
 
static void ATPrepSetStatistics (Relation rel, const char *colName, int16 colNum, Node *newValue, LOCKMODE lockmode)
 
static ObjectAddress ATExecSetStatistics (Relation rel, const char *colName, int16 colNum, Node *newValue, LOCKMODE lockmode)
 
static ObjectAddress ATExecSetOptions (Relation rel, const char *colName, Node *options, bool isReset, LOCKMODE lockmode)
 
static ObjectAddress ATExecSetStorage (Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
 
static void ATPrepDropColumn (List **wqueue, Relation rel, bool recurse, bool recursing, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static ObjectAddress ATExecDropColumn (List **wqueue, Relation rel, const char *colName, DropBehavior behavior, bool recurse, bool recursing, bool missing_ok, LOCKMODE lockmode)
 
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 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 (AlteredTableInfo *tab, Relation rel, Constraint *fkconstraint, LOCKMODE lockmode)
 
static void ATExecDropConstraint (Relation rel, const char *constrName, DropBehavior behavior, bool recurse, bool recursing, bool missing_ok, LOCKMODE lockmode)
 
static void ATPrepAlterColumnType (List **wqueue, AlteredTableInfo *tab, Relation rel, bool recurse, bool recursing, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static bool ATColumnChangeRequiresRewrite (Node *expr, AttrNumber varattno)
 
static ObjectAddress ATExecAlterColumnType (AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static ObjectAddress ATExecAlterColumnGenericOptions (Relation rel, const char *colName, List *options, LOCKMODE lockmode)
 
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, char *conname)
 
static void TryReuseIndex (Oid oldId, IndexStmt *stmt)
 
static void TryReuseForeignKey (Oid oldId, Constraint *con)
 
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, char *tablespacename, LOCKMODE lockmode)
 
static void ATExecSetTableSpace (Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
 
static void ATExecSetRelOptions (Relation rel, List *defList, AlterTableType operation, LOCKMODE lockmode)
 
static void ATExecEnableDisableTrigger (Relation rel, char *trigname, char fires_when, bool skip_system, LOCKMODE lockmode)
 
static void ATExecEnableDisableRule (Relation rel, 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 copy_relation_data (SMgrRelation rel, SMgrRelation dst, ForkNumber forkNum, char relpersistence)
 
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 bool is_partition_attr (Relation rel, AttrNumber attnum, bool *used_in_expr)
 
static PartitionSpectransformPartitionSpec (Relation rel, PartitionSpec *partspec, char *strategy)
 
static void ComputePartitionAttrs (Relation rel, List *partParams, AttrNumber *partattrs, List **partexprs, Oid *partopclass, Oid *partcollation)
 
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 ValidatePartitionConstraints (List **wqueue, Relation scanrel, List *scanrel_children, List *partConstraint, bool validate_default)
 
static ObjectAddress ATExecDetachPartition (Relation rel, RangeVar *name)
 
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 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)
 
void CheckTableNotInUse (Relation rel, const char *stmt)
 
Oid AlterTableLookupRelation (AlterTableStmt *stmt, LOCKMODE lockmode)
 
void AlterTable (Oid relid, LOCKMODE lockmode, AlterTableStmt *stmt)
 
void AlterTableInternal (Oid relid, List *cmds, bool recurse)
 
LOCKMODE AlterTableGetLockLevel (List *cmds)
 
void find_composite_type_dependencies (Oid typeOid, Relation origRelation, const char *origTypeName)
 
void check_of_type (HeapTuple typetuple)
 
static void CreateFKCheckTrigger (Oid myRelOid, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid, bool on_insert)
 
void ATExecChangeOwner (Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
 
Oid AlterTableMoveAll (AlterTableMoveAllStmt *stmt)
 
static char * decompile_conbin (HeapTuple contup, TupleDesc tupdesc)
 
static bool constraints_equivalent (HeapTuple a, HeapTuple b, TupleDesc tupleDesc)
 
static void relation_mark_replica_identity (Relation rel, char ri_type, Oid indexOid, bool is_internal)
 
ObjectAddress AlterTableNamespace (AlterObjectSchemaStmt *stmt, Oid *oldschema)
 
void AlterTableNamespaceInternal (Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
 
void AlterRelationNamespaceInternal (Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
 
void register_on_commit_action (Oid relid, OnCommitAction action)
 
void remove_on_commit_action (Oid relid)
 
void PreCommit_on_commit_actions (void)
 
void AtEOXact_on_commit_actions (bool isCommit)
 
void AtEOSubXact_on_commit_actions (bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
 
void RangeVarCallbackOwnsTable (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
void RangeVarCallbackOwnsRelation (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
bool PartConstraintImpliedByRelConstraint (Relation scanrel, List *partConstraint)
 

Variables

static Liston_commits = NIL
 
static const struct dropmsgstrings dropmsgstringarray []
 

Macro Definition Documentation

#define AT_NUM_PASSES   9

Definition at line 152 of file tablecmds.c.

Referenced by ATRewriteCatalogs().

#define AT_PASS_ADD_COL   5 /* ADD COLUMN */

Definition at line 148 of file tablecmds.c.

Referenced by ATPrepCmd().

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

Definition at line 150 of file tablecmds.c.

Referenced by ATPrepCmd().

#define AT_PASS_ADD_INDEX   6 /* ADD indexes */

Definition at line 149 of file tablecmds.c.

Referenced by ATPrepCmd().

#define AT_PASS_ALTER_TYPE   1 /* ALTER COLUMN TYPE */

Definition at line 143 of file tablecmds.c.

Referenced by ATPrepCmd(), and ATRewriteCatalogs().

#define AT_PASS_COL_ATTRS   4 /* set other column attributes */

Definition at line 146 of file tablecmds.c.

Referenced by ATPrepCmd().

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

Definition at line 142 of file tablecmds.c.

Referenced by ATPrepCmd().

#define AT_PASS_MISC   8 /* other stuff */

Definition at line 151 of file tablecmds.c.

Referenced by ATPrepCmd().

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

Definition at line 145 of file tablecmds.c.

Referenced by ATPostAlterTypeParse().

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

Definition at line 144 of file tablecmds.c.

Referenced by ATPostAlterTypeParse().

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

Definition at line 141 of file tablecmds.c.

Referenced by ATPrepCmd().

#define ATT_COMPOSITE_TYPE   0x0010

Definition at line 285 of file tablecmds.c.

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

#define ATT_INDEX   0x0008

Definition at line 284 of file tablecmds.c.

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

#define ATT_MATVIEW   0x0004

Definition at line 283 of file tablecmds.c.

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

#define ATT_VIEW   0x0002

Definition at line 282 of file tablecmds.c.

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

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

Definition at line 293 of file tablecmds.c.

Referenced by RemoveInheritance(), and StoreCatalogInheritance1().

Typedef Documentation

Function Documentation

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

Definition at line 5592 of file tablecmds.c.

References ObjectAddress::classId, CollationRelationId, DEFAULT_COLLATION_OID, DEPENDENCY_NORMAL, ObjectAddress::objectId, ObjectAddress::objectSubId, OidIsValid, recordDependencyOn(), and RelationRelationId.

Referenced by ATExecAddColumn(), and ATExecAlterColumnType().

5593 {
5594  ObjectAddress myself,
5595  referenced;
5596 
5597  /* We know the default collation is pinned, so don't bother recording it */
5598  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
5599  {
5600  myself.classId = RelationRelationId;
5601  myself.objectId = relid;
5602  myself.objectSubId = attnum;
5603  referenced.classId = CollationRelationId;
5604  referenced.objectId = collid;
5605  referenced.objectSubId = 0;
5606  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
5607  }
5608 }
#define RelationRelationId
Definition: pg_class.h:29
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
#define OidIsValid(objectId)
Definition: c.h:532
#define DEFAULT_COLLATION_OID
Definition: pg_collation.h:75
#define CollationRelationId
Definition: pg_collation.h:30
static void add_column_datatype_dependency ( Oid  relid,
int32  attnum,
Oid  typid 
)
static

Definition at line 5574 of file tablecmds.c.

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

Referenced by ATExecAddColumn(), and ATExecAlterColumnType().

5575 {
5576  ObjectAddress myself,
5577  referenced;
5578 
5579  myself.classId = RelationRelationId;
5580  myself.objectId = relid;
5581  myself.objectSubId = attnum;
5582  referenced.classId = TypeRelationId;
5583  referenced.objectId = typid;
5584  referenced.objectSubId = 0;
5585  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
5586 }
#define RelationRelationId
Definition: pg_class.h:29
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
#define TypeRelationId
Definition: pg_type.h:34
static void AlterIndexNamespaces ( Relation  classRel,
Relation  rel,
Oid  oldNspOid,
Oid  newNspOid,
ObjectAddresses objsMoved 
)
static

Definition at line 12725 of file tablecmds.c.

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

Referenced by AlterTableNamespaceInternal().

12727 {
12728  List *indexList;
12729  ListCell *l;
12730 
12731  indexList = RelationGetIndexList(rel);
12732 
12733  foreach(l, indexList)
12734  {
12735  Oid indexOid = lfirst_oid(l);
12736  ObjectAddress thisobj;
12737 
12738  thisobj.classId = RelationRelationId;
12739  thisobj.objectId = indexOid;
12740  thisobj.objectSubId = 0;
12741 
12742  /*
12743  * Note: currently, the index will not have its own dependency on the
12744  * namespace, so we don't need to do changeDependencyFor(). There's no
12745  * row type in pg_type, either.
12746  *
12747  * XXX this objsMoved test may be pointless -- surely we have a single
12748  * dependency link from a relation to each index?
12749  */
12750  if (!object_address_present(&thisobj, objsMoved))
12751  {
12752  AlterRelationNamespaceInternal(classRel, indexOid,
12753  oldNspOid, newNspOid,
12754  false, objsMoved);
12755  add_exact_object_address(&thisobj, objsMoved);
12756  }
12757  }
12758 
12759  list_free(indexList);
12760 }
#define RelationRelationId
Definition: pg_class.h:29
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2196
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2136
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:12655
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4357
void list_free(List *list)
Definition: list.c:1133
Definition: pg_list.h:45
#define lfirst_oid(lc)
Definition: pg_list.h:108
void AlterRelationNamespaceInternal ( Relation  classRel,
Oid  relOid,
Oid  oldNspOid,
Oid  newNspOid,
bool  hasDependEntry,
ObjectAddresses objsMoved 
)

Definition at line 12655 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, NamespaceRelationId, NameStr, object_address_present(), ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, RelationRelationId, RELOID, SearchSysCacheCopy1, and HeapTupleData::t_self.

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

12659 {
12660  HeapTuple classTup;
12661  Form_pg_class classForm;
12662  ObjectAddress thisobj;
12663  bool already_done = false;
12664 
12665  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
12666  if (!HeapTupleIsValid(classTup))
12667  elog(ERROR, "cache lookup failed for relation %u", relOid);
12668  classForm = (Form_pg_class) GETSTRUCT(classTup);
12669 
12670  Assert(classForm->relnamespace == oldNspOid);
12671 
12672  thisobj.classId = RelationRelationId;
12673  thisobj.objectId = relOid;
12674  thisobj.objectSubId = 0;
12675 
12676  /*
12677  * If the object has already been moved, don't move it again. If it's
12678  * already in the right place, don't move it, but still fire the object
12679  * access hook.
12680  */
12681  already_done = object_address_present(&thisobj, objsMoved);
12682  if (!already_done && oldNspOid != newNspOid)
12683  {
12684  /* check for duplicate name (more friendly than unique-index failure) */
12685  if (get_relname_relid(NameStr(classForm->relname),
12686  newNspOid) != InvalidOid)
12687  ereport(ERROR,
12688  (errcode(ERRCODE_DUPLICATE_TABLE),
12689  errmsg("relation \"%s\" already exists in schema \"%s\"",
12690  NameStr(classForm->relname),
12691  get_namespace_name(newNspOid))));
12692 
12693  /* classTup is a copy, so OK to scribble on */
12694  classForm->relnamespace = newNspOid;
12695 
12696  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
12697 
12698  /* Update dependency on schema if caller said so */
12699  if (hasDependEntry &&
12701  relOid,
12703  oldNspOid,
12704  newNspOid) != 1)
12705  elog(ERROR, "failed to change schema dependency for relation \"%s\"",
12706  NameStr(classForm->relname));
12707  }
12708  if (!already_done)
12709  {
12710  add_exact_object_address(&thisobj, objsMoved);
12711 
12713  }
12714 
12715  heap_freetuple(classTup);
12716 }
#define NamespaceRelationId
Definition: pg_namespace.h:34
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define RelationRelationId
Definition: pg_class.h:29
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2196
int errcode(int sqlerrcode)
Definition: elog.c:575
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2136
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#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:1683
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:681
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
int errmsg(const char *fmt,...)
Definition: elog.c:797
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:295
#define NameStr(name)
Definition: c.h:493
#define elog
Definition: elog.h:219
static void AlterSeqNamespaces ( Relation  classRel,
Relation  rel,
Oid  oldNspOid,
Oid  newNspOid,
ObjectAddresses objsMoved,
LOCKMODE  lockmode 
)
static

Definition at line 12770 of file tablecmds.c.

References AccessShareLock, AlterRelationNamespaceInternal(), AlterTypeNamespaceInternal(), Anum_pg_depend_refclassid, Anum_pg_depend_refobjid, BTEqualStrategyNumber, DEPENDENCY_AUTO, DEPENDENCY_INTERNAL, DependReferenceIndexId, DependRelationId, GETSTRUCT, heap_open(), HeapTupleIsValid, NoLock, ObjectIdGetDatum, relation_close(), relation_open(), RelationGetForm, RelationGetRelid, RelationRelationId, DropRelationCallbackState::relkind, RELKIND_SEQUENCE, ScanKeyInit(), systable_beginscan(), systable_endscan(), and systable_getnext().

Referenced by AlterTableNamespaceInternal().

12773 {
12774  Relation depRel;
12775  SysScanDesc scan;
12776  ScanKeyData key[2];
12777  HeapTuple tup;
12778 
12779  /*
12780  * SERIAL sequences are those having an auto dependency on one of the
12781  * table's columns (we don't care *which* column, exactly).
12782  */
12784 
12785  ScanKeyInit(&key[0],
12787  BTEqualStrategyNumber, F_OIDEQ,
12789  ScanKeyInit(&key[1],
12791  BTEqualStrategyNumber, F_OIDEQ,
12793  /* we leave refobjsubid unspecified */
12794 
12795  scan = systable_beginscan(depRel, DependReferenceIndexId, true,
12796  NULL, 2, key);
12797 
12798  while (HeapTupleIsValid(tup = systable_getnext(scan)))
12799  {
12800  Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
12801  Relation seqRel;
12802 
12803  /* skip dependencies other than auto dependencies on columns */
12804  if (depForm->refobjsubid == 0 ||
12805  depForm->classid != RelationRelationId ||
12806  depForm->objsubid != 0 ||
12807  !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
12808  continue;
12809 
12810  /* Use relation_open just in case it's an index */
12811  seqRel = relation_open(depForm->objid, lockmode);
12812 
12813  /* skip non-sequence relations */
12814  if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
12815  {
12816  /* No need to keep the lock */
12817  relation_close(seqRel, lockmode);
12818  continue;
12819  }
12820 
12821  /* Fix the pg_class and pg_depend entries */
12822  AlterRelationNamespaceInternal(classRel, depForm->objid,
12823  oldNspOid, newNspOid,
12824  true, objsMoved);
12825 
12826  /*
12827  * Sequences have entries in pg_type. We need to be careful to move
12828  * them to the new namespace, too.
12829  */
12831  newNspOid, false, false, objsMoved);
12832 
12833  /* Now we can close it. Keep the lock till end of transaction. */
12834  relation_close(seqRel, NoLock);
12835  }
12836 
12837  systable_endscan(scan);
12838 
12840 }
#define Anum_pg_depend_refobjid
Definition: pg_depend.h:72
#define Anum_pg_depend_refclassid
Definition: pg_depend.h:71
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define RelationGetForm(relation)
Definition: rel.h:410
#define RelationRelationId
Definition: pg_class.h:29
#define DependReferenceIndexId
Definition: indexing.h:147
#define DependRelationId
Definition: pg_depend.h:29
#define AccessShareLock
Definition: lockdefs.h:36
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:3577
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1266
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:328
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:416
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define NoLock
Definition: lockdefs.h:34
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:61
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:12655
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1120
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
#define RelationGetRelid(relation)
Definition: rel.h:416
#define BTEqualStrategyNumber
Definition: stratnum.h:31
void AlterTable ( Oid  relid,
LOCKMODE  lockmode,
AlterTableStmt stmt 
)

Definition at line 3141 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3142 {
3143  Relation rel;
3144 
3145  /* Caller is required to provide an adequate lock. */
3146  rel = relation_open(relid, NoLock);
3147 
3148  CheckTableNotInUse(rel, "ALTER TABLE");
3149 
3150  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode);
3151 }
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
Definition: tablecmds.c:3458
#define NoLock
Definition: lockdefs.h:34
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3062
bool inh
Definition: primnodes.h:69
RangeVar * relation
Definition: parsenodes.h:1691
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1120
LOCKMODE AlterTableGetLockLevel ( List cmds)

Definition at line 3210 of file tablecmds.c.

References AccessExclusiveLock, AlterTableGetRelOptionsLockLevel(), AT_AddColumn, AT_AddColumnToView, AT_AddConstraint, AT_AddConstraintRecurse, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AddInherit, AT_AddOf, AT_AddOids, AT_AlterColumnGenericOptions, AT_AlterColumnType, AT_AlterConstraint, AT_AttachPartition, AT_ChangeOwner, AT_ClusterOn, AT_ColumnDefault, AT_DetachPartition, AT_DisableRowSecurity, AT_DisableRule, AT_DisableTrig, AT_DisableTrigAll, AT_DisableTrigUser, AT_DropCluster, AT_DropColumn, AT_DropConstraint, AT_DropIdentity, AT_DropInherit, AT_DropNotNull, AT_DropOf, AT_DropOids, AT_EnableAlwaysRule, AT_EnableAlwaysTrig, AT_EnableReplicaRule, AT_EnableReplicaTrig, AT_EnableRowSecurity, AT_EnableRule, AT_EnableTrig, AT_EnableTrigAll, AT_EnableTrigUser, AT_ForceRowSecurity, AT_GenericOptions, AT_NoForceRowSecurity, AT_ProcessedConstraint, AT_ReAddConstraint, AT_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().

3211 {
3212  /*
3213  * This only works if we read catalog tables using MVCC snapshots.
3214  */
3215  ListCell *lcmd;
3217 
3218  foreach(lcmd, cmds)
3219  {
3220  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3221  LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
3222 
3223  switch (cmd->subtype)
3224  {
3225  /*
3226  * These subcommands rewrite the heap, so require full locks.
3227  */
3228  case AT_AddColumn: /* may rewrite heap, in some cases and visible
3229  * to SELECT */
3230  case AT_SetTableSpace: /* must rewrite heap */
3231  case AT_AlterColumnType: /* must rewrite heap */
3232  case AT_AddOids: /* must rewrite heap */
3233  cmd_lockmode = AccessExclusiveLock;
3234  break;
3235 
3236  /*
3237  * These subcommands may require addition of toast tables. If
3238  * we add a toast table to a table currently being scanned, we
3239  * might miss data added to the new toast table by concurrent
3240  * insert transactions.
3241  */
3242  case AT_SetStorage: /* may add toast tables, see
3243  * ATRewriteCatalogs() */
3244  cmd_lockmode = AccessExclusiveLock;
3245  break;
3246 
3247  /*
3248  * Removing constraints can affect SELECTs that have been
3249  * optimised assuming the constraint holds true.
3250  */
3251  case AT_DropConstraint: /* as DROP INDEX */
3252  case AT_DropNotNull: /* may change some SQL plans */
3253  cmd_lockmode = AccessExclusiveLock;
3254  break;
3255 
3256  /*
3257  * Subcommands that may be visible to concurrent SELECTs
3258  */
3259  case AT_DropColumn: /* change visible to SELECT */
3260  case AT_AddColumnToView: /* CREATE VIEW */
3261  case AT_DropOids: /* calls AT_DropColumn */
3262  case AT_EnableAlwaysRule: /* may change SELECT rules */
3263  case AT_EnableReplicaRule: /* may change SELECT rules */
3264  case AT_EnableRule: /* may change SELECT rules */
3265  case AT_DisableRule: /* may change SELECT rules */
3266  cmd_lockmode = AccessExclusiveLock;
3267  break;
3268 
3269  /*
3270  * Changing owner may remove implicit SELECT privileges
3271  */
3272  case AT_ChangeOwner: /* change visible to SELECT */
3273  cmd_lockmode = AccessExclusiveLock;
3274  break;
3275 
3276  /*
3277  * Changing foreign table options may affect optimization.
3278  */
3279  case AT_GenericOptions:
3281  cmd_lockmode = AccessExclusiveLock;
3282  break;
3283 
3284  /*
3285  * These subcommands affect write operations only.
3286  */
3287  case AT_EnableTrig:
3288  case AT_EnableAlwaysTrig:
3289  case AT_EnableReplicaTrig:
3290  case AT_EnableTrigAll:
3291  case AT_EnableTrigUser:
3292  case AT_DisableTrig:
3293  case AT_DisableTrigAll:
3294  case AT_DisableTrigUser:
3295  cmd_lockmode = ShareRowExclusiveLock;
3296  break;
3297 
3298  /*
3299  * These subcommands affect write operations only. XXX
3300  * Theoretically, these could be ShareRowExclusiveLock.
3301  */
3302  case AT_ColumnDefault:
3303  case AT_AlterConstraint:
3304  case AT_AddIndex: /* from ADD CONSTRAINT */
3305  case AT_AddIndexConstraint:
3306  case AT_ReplicaIdentity:
3307  case AT_SetNotNull:
3308  case AT_EnableRowSecurity:
3309  case AT_DisableRowSecurity:
3310  case AT_ForceRowSecurity:
3311  case AT_NoForceRowSecurity:
3312  case AT_AddIdentity:
3313  case AT_DropIdentity:
3314  case AT_SetIdentity:
3315  cmd_lockmode = AccessExclusiveLock;
3316  break;
3317 
3318  case AT_AddConstraint:
3319  case AT_ProcessedConstraint: /* becomes AT_AddConstraint */
3320  case AT_AddConstraintRecurse: /* becomes AT_AddConstraint */
3321  case AT_ReAddConstraint: /* becomes AT_AddConstraint */
3322  if (IsA(cmd->def, Constraint))
3323  {
3324  Constraint *con = (Constraint *) cmd->def;
3325 
3326  switch (con->contype)
3327  {
3328  case CONSTR_EXCLUSION:
3329  case CONSTR_PRIMARY:
3330  case CONSTR_UNIQUE:
3331 
3332  /*
3333  * Cases essentially the same as CREATE INDEX. We
3334  * could reduce the lock strength to ShareLock if
3335  * we can work out how to allow concurrent catalog
3336  * updates. XXX Might be set down to
3337  * ShareRowExclusiveLock but requires further
3338  * analysis.
3339  */
3340  cmd_lockmode = AccessExclusiveLock;
3341  break;
3342  case CONSTR_FOREIGN:
3343 
3344  /*
3345  * We add triggers to both tables when we add a
3346  * Foreign Key, so the lock level must be at least
3347  * as strong as CREATE TRIGGER.
3348  */
3349  cmd_lockmode = ShareRowExclusiveLock;
3350  break;
3351 
3352  default:
3353  cmd_lockmode = AccessExclusiveLock;
3354  }
3355  }
3356  break;
3357 
3358  /*
3359  * These subcommands affect inheritance behaviour. Queries
3360  * started before us will continue to see the old inheritance
3361  * behaviour, while queries started after we commit will see
3362  * new behaviour. No need to prevent reads or writes to the
3363  * subtable while we hook it up though. Changing the TupDesc
3364  * may be a problem, so keep highest lock.
3365  */
3366  case AT_AddInherit:
3367  case AT_DropInherit:
3368  cmd_lockmode = AccessExclusiveLock;
3369  break;
3370 
3371  /*
3372  * These subcommands affect implicit row type conversion. They
3373  * have affects similar to CREATE/DROP CAST on queries. don't
3374  * provide for invalidating parse trees as a result of such
3375  * changes, so we keep these at AccessExclusiveLock.
3376  */
3377  case AT_AddOf:
3378  case AT_DropOf:
3379  cmd_lockmode = AccessExclusiveLock;
3380  break;
3381 
3382  /*
3383  * Only used by CREATE OR REPLACE VIEW which must conflict
3384  * with an SELECTs currently using the view.
3385  */
3386  case AT_ReplaceRelOptions:
3387  cmd_lockmode = AccessExclusiveLock;
3388  break;
3389 
3390  /*
3391  * These subcommands affect general strategies for performance
3392  * and maintenance, though don't change the semantic results
3393  * from normal data reads and writes. Delaying an ALTER TABLE
3394  * behind currently active writes only delays the point where
3395  * the new strategy begins to take effect, so there is no
3396  * benefit in waiting. In this case the minimum restriction
3397  * applies: we don't currently allow concurrent catalog
3398  * updates.
3399  */
3400  case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
3401  case AT_ClusterOn: /* Uses MVCC in getIndexes() */
3402  case AT_DropCluster: /* Uses MVCC in getIndexes() */
3403  case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
3404  case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
3405  cmd_lockmode = ShareUpdateExclusiveLock;
3406  break;
3407 
3408  case AT_SetLogged:
3409  case AT_SetUnLogged:
3410  cmd_lockmode = AccessExclusiveLock;
3411  break;
3412 
3413  case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
3414  cmd_lockmode = ShareUpdateExclusiveLock;
3415  break;
3416 
3417  /*
3418  * Rel options are more complex than first appears. Options
3419  * are set here for tables, views and indexes; for historical
3420  * reasons these can all be used with ALTER TABLE, so we can't
3421  * decide between them using the basic grammar.
3422  */
3423  case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
3424  * getTables() */
3425  case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
3426  * getTables() */
3427  cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
3428  break;
3429 
3430  case AT_AttachPartition:
3431  case AT_DetachPartition:
3432  cmd_lockmode = AccessExclusiveLock;
3433  break;
3434 
3435  default: /* oops */
3436  elog(ERROR, "unrecognized alter table type: %d",
3437  (int) cmd->subtype);
3438  break;
3439  }
3440 
3441  /*
3442  * Take the greatest lockmode from any subcommand
3443  */
3444  if (cmd_lockmode > lockmode)
3445  lockmode = cmd_lockmode;
3446  }
3447 
3448  return lockmode;
3449 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
int LOCKMODE
Definition: lockdefs.h:26
AlterTableType subtype
Definition: parsenodes.h:1778
#define ERROR
Definition: elog.h:43
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define lfirst(lc)
Definition: pg_list.h:106
#define ShareRowExclusiveLock
Definition: lockdefs.h:42
LOCKMODE AlterTableGetRelOptionsLockLevel(List *defList)
Definition: reloptions.c:1528
#define AccessExclusiveLock
Definition: lockdefs.h:45
ConstrType contype
Definition: parsenodes.h:2081
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
void AlterTableInternal ( Oid  relid,
List cmds,
bool  recurse 
)

Definition at line 3165 of file tablecmds.c.

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

Referenced by AlterTableMoveAll(), DefineVirtualRelation(), and index_check_primary_key().

3166 {
3167  Relation rel;
3168  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
3169 
3170  rel = relation_open(relid, lockmode);
3171 
3173 
3174  ATController(NULL, rel, cmds, recurse, lockmode);
3175 }
int LOCKMODE
Definition: lockdefs.h:26
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
Definition: tablecmds.c:3458
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:3210
void EventTriggerAlterTableRelid(Oid objectId)
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1120
Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 3091 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3092 {
3093  return RangeVarGetRelidExtended(stmt->relation, lockmode, stmt->missing_ok, false,
3095  (void *) stmt);
3096 }
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:218
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:13132
RangeVar * relation
Definition: parsenodes.h:1691
Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

Definition at line 10733 of file tablecmds.c.

References AccessExclusiveLock, AccessShareLock, ACL_CREATE, ACL_KIND_CLASS, ACL_KIND_TABLESPACE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, AlterTableInternal(), Anum_pg_class_reltablespace, AT_SetTableSpace, BTEqualStrategyNumber, ConditionalLockRelationOid(), ereport, errcode(), errmsg(), ERROR, EventTriggerAlterTableEnd(), EventTriggerAlterTableStart(), ForwardScanDirection, get_namespace_name(), get_tablespace_name(), get_tablespace_oid(), GETSTRUCT, GetUserId(), GLOBALTABLESPACE_OID, heap_beginscan_catalog(), heap_close, heap_endscan(), heap_getnext(), heap_open(), HeapTupleGetOid, InvalidOid, isAnyTempNamespace(), IsSystemNamespace(), 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, ObjectIdGetDatum, AlterTableMoveAllStmt::objtype, OidIsValid, AlterTableMoveAllStmt::orig_tablespacename, pg_class_ownercheck(), pg_tablespace_aclcheck(), PG_TOAST_NAMESPACE, RelationRelationId, RELKIND_INDEX, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, AlterTableMoveAllStmt::roles, roleSpecsToIds(), ScanKeyInit(), and AlterTableCmd::subtype.

Referenced by ProcessUtilitySlow().

10734 {
10735  List *relations = NIL;
10736  ListCell *l;
10737  ScanKeyData key[1];
10738  Relation rel;
10739  HeapScanDesc scan;
10740  HeapTuple tuple;
10741  Oid orig_tablespaceoid;
10742  Oid new_tablespaceoid;
10743  List *role_oids = roleSpecsToIds(stmt->roles);
10744 
10745  /* Ensure we were not asked to move something we can't */
10746  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
10747  stmt->objtype != OBJECT_MATVIEW)
10748  ereport(ERROR,
10749  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
10750  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
10751 
10752  /* Get the orig and new tablespace OIDs */
10753  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
10754  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
10755 
10756  /* Can't move shared relations in to or out of pg_global */
10757  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
10758  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
10759  new_tablespaceoid == GLOBALTABLESPACE_OID)
10760  ereport(ERROR,
10761  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
10762  errmsg("cannot move relations in to or out of pg_global tablespace")));
10763 
10764  /*
10765  * Must have CREATE rights on the new tablespace, unless it is the
10766  * database default tablespace (which all users implicitly have CREATE
10767  * rights on).
10768  */
10769  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
10770  {
10771  AclResult aclresult;
10772 
10773  aclresult = pg_tablespace_aclcheck(new_tablespaceoid, GetUserId(),
10774  ACL_CREATE);
10775  if (aclresult != ACLCHECK_OK)
10777  get_tablespace_name(new_tablespaceoid));
10778  }
10779 
10780  /*
10781  * Now that the checks are done, check if we should set either to
10782  * InvalidOid because it is our database's default tablespace.
10783  */
10784  if (orig_tablespaceoid == MyDatabaseTableSpace)
10785  orig_tablespaceoid = InvalidOid;
10786 
10787  if (new_tablespaceoid == MyDatabaseTableSpace)
10788  new_tablespaceoid = InvalidOid;
10789 
10790  /* no-op */
10791  if (orig_tablespaceoid == new_tablespaceoid)
10792  return new_tablespaceoid;
10793 
10794  /*
10795  * Walk the list of objects in the tablespace and move them. This will
10796  * only find objects in our database, of course.
10797  */
10798  ScanKeyInit(&key[0],
10800  BTEqualStrategyNumber, F_OIDEQ,
10801  ObjectIdGetDatum(orig_tablespaceoid));
10802 
10804  scan = heap_beginscan_catalog(rel, 1, key);
10805  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
10806  {
10807  Oid relOid = HeapTupleGetOid(tuple);
10808  Form_pg_class relForm;
10809 
10810  relForm = (Form_pg_class) GETSTRUCT(tuple);
10811 
10812  /*
10813  * Do not move objects in pg_catalog as part of this, if an admin
10814  * really wishes to do so, they can issue the individual ALTER
10815  * commands directly.
10816  *
10817  * Also, explicitly avoid any shared tables, temp tables, or TOAST
10818  * (TOAST will be moved with the main table).
10819  */
10820  if (IsSystemNamespace(relForm->relnamespace) || relForm->relisshared ||
10821  isAnyTempNamespace(relForm->relnamespace) ||
10822  relForm->relnamespace == PG_TOAST_NAMESPACE)
10823  continue;
10824 
10825  /* Only move the object type requested */
10826  if ((stmt->objtype == OBJECT_TABLE &&
10827  relForm->relkind != RELKIND_RELATION &&
10828  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
10829  (stmt->objtype == OBJECT_INDEX &&
10830  relForm->relkind != RELKIND_INDEX) ||
10831  (stmt->objtype == OBJECT_MATVIEW &&
10832  relForm->relkind != RELKIND_MATVIEW))
10833  continue;
10834 
10835  /* Check if we are only moving objects owned by certain roles */
10836  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
10837  continue;
10838 
10839  /*
10840  * Handle permissions-checking here since we are locking the tables
10841  * and also to avoid doing a bunch of work only to fail part-way. Note
10842  * that permissions will also be checked by AlterTableInternal().
10843  *
10844  * Caller must be considered an owner on the table to move it.
10845  */
10846  if (!pg_class_ownercheck(relOid, GetUserId()))
10848  NameStr(relForm->relname));
10849 
10850  if (stmt->nowait &&
10852  ereport(ERROR,
10853  (errcode(ERRCODE_OBJECT_IN_USE),
10854  errmsg("aborting because lock on relation \"%s.%s\" is not available",
10855  get_namespace_name(relForm->relnamespace),
10856  NameStr(relForm->relname))));
10857  else
10859 
10860  /* Add to our list of objects to move */
10861  relations = lappend_oid(relations, relOid);
10862  }
10863 
10864  heap_endscan(scan);
10866 
10867  if (relations == NIL)
10868  ereport(NOTICE,
10869  (errcode(ERRCODE_NO_DATA_FOUND),
10870  errmsg("no matching relations in tablespace \"%s\" found",
10871  orig_tablespaceoid == InvalidOid ? "(database default)" :
10872  get_tablespace_name(orig_tablespaceoid))));
10873 
10874  /* Everything is locked, loop through and move all of the relations. */
10875  foreach(l, relations)
10876  {
10877  List *cmds = NIL;
10879 
10880  cmd->subtype = AT_SetTableSpace;
10881  cmd->name = stmt->new_tablespacename;
10882 
10883  cmds = lappend(cmds, cmd);
10884 
10886  /* OID is set by AlterTableInternal */
10887  AlterTableInternal(lfirst_oid(l), cmds, false);
10889  }
10890 
10891  return new_tablespaceoid;
10892 }
#define NIL
Definition: pg_list.h:69
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:138
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1380
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4496
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1565
Oid GetUserId(void)
Definition: miscinit.c:284
#define RelationRelationId
Definition: pg_class.h:29
#define Anum_pg_class_reltablespace
Definition: pg_class.h:110
#define RELKIND_MATVIEW
Definition: pg_class.h:165
#define AccessShareLock
Definition: lockdefs.h:36
#define GLOBALTABLESPACE_OID
Definition: pg_tablespace.h:64
Definition: nodes.h:510
int errcode(int sqlerrcode)
Definition: elog.c:575
AlterTableType subtype
Definition: parsenodes.h:1778
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
#define PG_TOAST_NAMESPACE
Definition: pg_namespace.h:74
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
#define OidIsValid(objectId)
Definition: c.h:532
Oid MyDatabaseTableSpace
Definition: globals.c:79
void EventTriggerAlterTableStart(Node *parsetree)
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:82
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1405
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
AclResult
Definition: acl.h:178
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1808
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
bool IsSystemNamespace(Oid namespaceId)
Definition: catalog.c:163
#define InvalidOid
Definition: postgres_ext.h:36
#define NOTICE
Definition: elog.h:37
#define makeNode(_type_)
Definition: nodes.h:558
List * roleSpecsToIds(List *memberNames)
Definition: user.c:1396
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4546
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:3165
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1426
#define NameStr(name)
Definition: c.h:493
#define RELKIND_INDEX
Definition: pg_class.h:161
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
bool isAnyTempNamespace(Oid namespaceId)
Definition: namespace.c:3156
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:105
#define RELKIND_RELATION
Definition: pg_class.h:160
Definition: pg_list.h:45
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define lfirst_oid(lc)
Definition: pg_list.h:108
void EventTriggerAlterTableEnd(void)
ObjectAddress AlterTableNamespace ( AlterObjectSchemaStmt stmt,
Oid oldschema 
)

Definition at line 12546 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(), AlterObjectSchemaStmt::newschema, NoLock, NOTICE, ObjectAddressSet, OidIsValid, RangeVarCallbackForAlterRelation(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetRelidExtended(), RelationData::rd_rel, AlterObjectSchemaStmt::relation, relation_close(), relation_open(), RelationGetNamespace, RelationGetRelationName, RelationRelationId, RELKIND_SEQUENCE, RangeVar::relname, and sequenceIsOwned().

Referenced by ExecAlterObjectSchemaStmt().

12547 {
12548  Relation rel;
12549  Oid relid;
12550  Oid oldNspOid;
12551  Oid nspOid;
12552  RangeVar *newrv;
12553  ObjectAddresses *objsMoved;
12554  ObjectAddress myself;
12555 
12557  stmt->missing_ok, false,
12559  (void *) stmt);
12560 
12561  if (!OidIsValid(relid))
12562  {
12563  ereport(NOTICE,
12564  (errmsg("relation \"%s\" does not exist, skipping",
12565  stmt->relation->relname)));
12566  return InvalidObjectAddress;
12567  }
12568 
12569  rel = relation_open(relid, NoLock);
12570 
12571  oldNspOid = RelationGetNamespace(rel);
12572 
12573  /* If it's an owned sequence, disallow moving it by itself. */
12574  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
12575  {
12576  Oid tableId;
12577  int32 colId;
12578 
12579  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
12580  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
12581  ereport(ERROR,
12582  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
12583  errmsg("cannot move an owned sequence into another schema"),
12584  errdetail("Sequence \"%s\" is linked to table \"%s\".",
12586  get_rel_name(tableId))));
12587  }
12588 
12589  /* Get and lock schema OID and check its permissions. */
12590  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
12591  nspOid = RangeVarGetAndCheckCreationNamespace(newrv, NoLock, NULL);
12592 
12593  /* common checks on switching namespaces */
12594  CheckSetNamespace(oldNspOid, nspOid);
12595 
12596  objsMoved = new_object_addresses();
12597  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
12598  free_object_addresses(objsMoved);
12599 
12600  ObjectAddressSet(myself, RelationRelationId, relid);
12601 
12602  if (oldschema)
12603  *oldschema = oldNspOid;
12604 
12605  /* close rel, but keep lock until commit */
12606  relation_close(rel, NoLock);
12607 
12608  return myself;
12609 }
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition: pg_depend.c:500
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:218
#define RelationRelationId
Definition: pg_class.h:29
int errcode(int sqlerrcode)
Definition: elog.c:575
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1266
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2081
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2352
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:532
signed int int32
Definition: c.h:246
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:43
void AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:12617
#define NoLock
Definition: lockdefs.h:34
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:13132
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:436
#define ereport(elevel, rest)
Definition: elog.h:122
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition: namespace.c:2928
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:508
#define NOTICE
Definition: elog.h:37
#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:797
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1120
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1726
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:419
#define RelationGetNamespace(relation)
Definition: rel.h:443
void AlterTableNamespaceInternal ( Relation  rel,
Oid  oldNspOid,
Oid  nspOid,
ObjectAddresses objsMoved 
)

Definition at line 12617 of file tablecmds.c.

References AccessExclusiveLock, AlterConstraintNamespaces(), AlterIndexNamespaces(), AlterRelationNamespaceInternal(), AlterSeqNamespaces(), AlterTypeNamespaceInternal(), Assert, heap_close, heap_open(), RelationData::rd_rel, RelationGetRelid, RelationRelationId, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, and RowExclusiveLock.

Referenced by AlterObjectNamespace_oid(), and AlterTableNamespace().

12619 {
12620  Relation classRel;
12621 
12622  Assert(objsMoved != NULL);
12623 
12624  /* OK, modify the pg_class row and pg_depend entry */
12626 
12627  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
12628  nspOid, true, objsMoved);
12629 
12630  /* Fix the table's row type too */
12631  AlterTypeNamespaceInternal(rel->rd_rel->reltype,
12632  nspOid, false, false, objsMoved);
12633 
12634  /* Fix other dependent stuff */
12635  if (rel->rd_rel->relkind == RELKIND_RELATION ||
12636  rel->rd_rel->relkind == RELKIND_MATVIEW ||
12637  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
12638  {
12639  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
12640  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
12641  objsMoved, AccessExclusiveLock);
12642  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
12643  false, objsMoved);
12644  }
12645 
12646  heap_close(classRel, RowExclusiveLock);
12647 }
#define RelationRelationId
Definition: pg_class.h:29
#define RELKIND_MATVIEW
Definition: pg_class.h:165
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:3577
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:114
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:12725
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:12770
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define Assert(condition)
Definition: c.h:681
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:12655
#define AccessExclusiveLock
Definition: lockdefs.h:45
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RelationGetRelid(relation)
Definition: rel.h:416
static ObjectAddress ATAddCheckConstraint ( List **  wqueue,
AlteredTableInfo tab,
Relation  rel,
Constraint constr,
bool  recurse,
bool  recursing,
bool  is_readd,
LOCKMODE  lockmode 
)
static

Definition at line 6973 of file tablecmds.c.

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

Referenced by ATExecAddConstraint().

6976 {
6977  List *newcons;
6978  ListCell *lcon;
6979  List *children;
6980  ListCell *child;
6982 
6983  /* At top level, permission check was done in ATPrepCmd, else do it */
6984  if (recursing)
6986 
6987  /*
6988  * Call AddRelationNewConstraints to do the work, making sure it works on
6989  * a copy of the Constraint so transformExpr can't modify the original. It
6990  * returns a list of cooked constraints.
6991  *
6992  * If the constraint ends up getting merged with a pre-existing one, it's
6993  * omitted from the returned list, which is what we want: we do not need
6994  * to do any validation work. That can only happen at child tables,
6995  * though, since we disallow merging at the top level.
6996  */
6997  newcons = AddRelationNewConstraints(rel, NIL,
6998  list_make1(copyObject(constr)),
6999  recursing | is_readd, /* allow_merge */
7000  !recursing, /* is_local */
7001  is_readd); /* is_internal */
7002 
7003  /* we don't expect more than one constraint here */
7004  Assert(list_length(newcons) <= 1);
7005 
7006  /* Add each to-be-validated constraint to Phase 3's queue */
7007  foreach(lcon, newcons)
7008  {
7009  CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
7010 
7011  if (!ccon->skip_validation)
7012  {
7013  NewConstraint *newcon;
7014 
7015  newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
7016  newcon->name = ccon->name;
7017  newcon->contype = ccon->contype;
7018  newcon->qual = ccon->expr;
7019 
7020  tab->constraints = lappend(tab->constraints, newcon);
7021  }
7022 
7023  /* Save the actually assigned name if it was defaulted */
7024  if (constr->conname == NULL)
7025  constr->conname = ccon->name;
7026 
7027  ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
7028  }
7029 
7030  /* At this point we must have a locked-down name to use */
7031  Assert(constr->conname != NULL);
7032 
7033  /* Advance command counter in case same table is visited multiple times */
7035 
7036  /*
7037  * If the constraint got merged with an existing constraint, we're done.
7038  * We mustn't recurse to child tables in this case, because they've
7039  * already got the constraint, and visiting them again would lead to an
7040  * incorrect value for coninhcount.
7041  */
7042  if (newcons == NIL)
7043  return address;
7044 
7045  /*
7046  * If adding a NO INHERIT constraint, no need to find our children.
7047  */
7048  if (constr->is_no_inherit)
7049  return address;
7050 
7051  /*
7052  * Propagate to children as appropriate. Unlike most other ALTER
7053  * routines, we have to do this one level of recursion at a time; we can't
7054  * use find_all_inheritors to do it in one pass.
7055  */
7056  children = find_inheritance_children(RelationGetRelid(rel), lockmode);
7057 
7058  /*
7059  * Check if ONLY was specified with ALTER TABLE. If so, allow the
7060  * constraint creation only if there are no children currently. Error out
7061  * otherwise.
7062  */
7063  if (!recurse && children != NIL)
7064  ereport(ERROR,
7065  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7066  errmsg("constraint must be added to child tables too")));
7067 
7068  foreach(child, children)
7069  {
7070  Oid childrelid = lfirst_oid(child);
7071  Relation childrel;
7072  AlteredTableInfo *childtab;
7073 
7074  /* find_inheritance_children already got lock */
7075  childrel = heap_open(childrelid, NoLock);
7076  CheckTableNotInUse(childrel, "ALTER TABLE");
7077 
7078  /* Find or create work queue entry for this table */
7079  childtab = ATGetQueueEntry(wqueue, childrel);
7080 
7081  /* Recurse to child */
7082  ATAddCheckConstraint(wqueue, childtab, childrel,
7083  constr, recurse, true, is_readd, lockmode);
7084 
7085  heap_close(childrel, NoLock);
7086  }
7087 
7088  return address;
7089 }
#define NIL
Definition: pg_list.h:69
char * name
Definition: tablecmds.c:184
Node * qual
Definition: tablecmds.c:189
int errcode(int sqlerrcode)
Definition: elog.c:575
static ObjectAddress ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *constr, bool recurse, bool recursing, bool is_readd, LOCKMODE lockmode)
Definition: tablecmds.c:6973
#define heap_close(r, l)
Definition: heapam.h:97
char * conname
Definition: parsenodes.h:2084
unsigned int Oid
Definition: postgres_ext.h:31
#define ATT_TABLE
Definition: tablecmds.c:281
List * constraints
Definition: tablecmds.c:163
#define list_make1(x1)
Definition: pg_list.h:139
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
static AlteredTableInfo * ATGetQueueEntry(List **wqueue, Relation rel)
Definition: tablecmds.c:4689
bool skip_validation
Definition: heap.h:35
ConstrType contype
Definition: heap.h:30
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3062
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
ConstrType contype
Definition: tablecmds.c:185
void * palloc0(Size size)
Definition: mcxt.c:877
void CommandCounterIncrement(void)
Definition: xact.c:915
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
bool is_no_inherit
Definition: parsenodes.h:2090
List * find_inheritance_children(Oid parentrelId, LOCKMODE lockmode)
Definition: pg_inherits.c:57
#define Assert(condition)
Definition: c.h:681
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:797
Oid conoid
Definition: heap.h:31
Node * expr
Definition: heap.h:34
static void ATSimplePermissions(Relation rel, int allowed_targets)
Definition: tablecmds.c:4726
#define ConstraintRelationId
Definition: pg_constraint.h:29
#define copyObject(obj)
Definition: nodes.h:623
Definition: pg_list.h:45
#define ATT_FOREIGN_TABLE
Definition: tablecmds.c:286
char * name
Definition: heap.h:32
#define RelationGetRelid(relation)
Definition: rel.h:416
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal)
Definition: heap.c:2227
#define lfirst_oid(lc)
Definition: pg_list.h:108
static ObjectAddress ATAddForeignKeyConstraint ( AlteredTableInfo tab,
Relation  rel,
Constraint fkconstraint,
LOCKMODE  lockmode 
)
static

Definition at line 7100 of file tablecmds.c.

References allowSystemTableMods, Assert, BTEqualStrategyNumber, BTREE_AM_OID, can_coerce_type(), checkFkeyPermissions(), CLAOID, COERCION_IMPLICIT, NewConstraint::conid, Constraint::conname, CONSTR_FOREIGN, CONSTRAINT_FOREIGN, ConstraintRelationId, AlteredTableInfo::constraints, NewConstraint::contype, CreateConstraintEntry(), createForeignKeyTriggers(), Constraint::deferrable, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, findFkeyCast(), Constraint::fk_attrs, Constraint::fk_del_action, Constraint::fk_matchtype, Constraint::fk_upd_action, format_type_be(), get_opfamily_member(), getBaseType(), GETSTRUCT, heap_close, heap_open(), heap_openrv(), HeapTupleIsValid, i, INDEX_MAX_KEYS, Constraint::initdeferred, Constraint::initially_valid, InvalidOid, IsPolymorphicType, IsSystemRelation(), lappend(), lfirst_oid, list_head(), list_length(), list_nth(), lnext, MemSet, NewConstraint::name, NIL, NoLock, ObjectAddressSet, ObjectIdGetDatum, OidIsValid, Constraint::old_conpfeqop, Constraint::old_pktable_oid, AlteredTableInfo::oldDesc, palloc0(), Constraint::pk_attrs, Constraint::pktable, NewConstraint::qual, RelationData::rd_islocaltemp, RelationData::rd_rel, NewConstraint::refindid, NewConstraint::refrelid, RelationGetNamespace, RelationGetRelationName, RelationGetRelid, ReleaseSysCache(), RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RELPERSISTENCE_PERMANENT, RELPERSISTENCE_TEMP, RELPERSISTENCE_UNLOGGED, SearchSysCache1(), ShareRowExclusiveLock, Constraint::skip_validation, strVal, transformColumnNameList(), transformFkeyCheckAttrs(), transformFkeyGetPrimaryKey(), and TupleDescAttr.

Referenced by ATExecAddConstraint().

7102 {
7103  Relation pkrel;
7104  int16 pkattnum[INDEX_MAX_KEYS];
7105  int16 fkattnum[INDEX_MAX_KEYS];
7106  Oid pktypoid[INDEX_MAX_KEYS];
7107  Oid fktypoid[INDEX_MAX_KEYS];
7108  Oid opclasses[INDEX_MAX_KEYS];
7109  Oid pfeqoperators[INDEX_MAX_KEYS];
7110  Oid ppeqoperators[INDEX_MAX_KEYS];
7111  Oid ffeqoperators[INDEX_MAX_KEYS];
7112  int i;
7113  int numfks,
7114  numpks;
7115  Oid indexOid;
7116  Oid constrOid;
7117  bool old_check_ok;
7118  ObjectAddress address;
7119  ListCell *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
7120 
7121  /*
7122  * Grab ShareRowExclusiveLock on the pk table, so that someone doesn't
7123  * delete rows out from under us.
7124  */
7125  if (OidIsValid(fkconstraint->old_pktable_oid))
7126  pkrel = heap_open(fkconstraint->old_pktable_oid, ShareRowExclusiveLock);
7127  else
7128  pkrel = heap_openrv(fkconstraint->pktable, ShareRowExclusiveLock);
7129 
7130  /*
7131  * Validity checks (permission checks wait till we have the column
7132  * numbers)
7133  */
7134  if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
7135  ereport(ERROR,
7136  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7137  errmsg("cannot reference partitioned table \"%s\"",
7138  RelationGetRelationName(pkrel))));
7139 
7140  if (pkrel->rd_rel->relkind != RELKIND_RELATION)
7141  ereport(ERROR,
7142  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7143  errmsg("referenced relation \"%s\" is not a table",
7144  RelationGetRelationName(pkrel))));
7145 
7146  if (!allowSystemTableMods && IsSystemRelation(pkrel))
7147  ereport(ERROR,
7148  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
7149  errmsg("permission denied: \"%s\" is a system catalog",
7150  RelationGetRelationName(pkrel))));
7151 
7152  /*
7153  * References from permanent or unlogged tables to temp tables, and from
7154  * permanent tables to unlogged tables, are disallowed because the
7155  * referenced data can vanish out from under us. References from temp
7156  * tables to any other table type are also disallowed, because other
7157  * backends might need to run the RI triggers on the perm table, but they
7158  * can't reliably see tuples in the local buffers of other backends.
7159  */
7160  switch (rel->rd_rel->relpersistence)
7161  {
7163  if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT)
7164  ereport(ERROR,
7165  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7166  errmsg("constraints on permanent tables may reference only permanent tables")));
7167  break;
7169  if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT
7170  && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
7171  ereport(ERROR,
7172  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7173  errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
7174  break;
7175  case RELPERSISTENCE_TEMP:
7176  if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
7177  ereport(ERROR,
7178  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7179  errmsg("constraints on temporary tables may reference only temporary tables")));
7180  if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
7181  ereport(ERROR,
7182  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7183  errmsg("constraints on temporary tables must involve temporary tables of this session")));
7184  break;
7185  }
7186 
7187  /*
7188  * Look up the referencing attributes to make sure they exist, and record
7189  * their attnums and type OIDs.
7190  */
7191  MemSet(pkattnum, 0, sizeof(pkattnum));
7192  MemSet(fkattnum, 0, sizeof(fkattnum));
7193  MemSet(pktypoid, 0, sizeof(pktypoid));
7194  MemSet(fktypoid, 0, sizeof(fktypoid));
7195  MemSet(opclasses, 0, sizeof(opclasses));
7196  MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
7197  MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
7198  MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
7199 
7201  fkconstraint->fk_attrs,
7202  fkattnum, fktypoid);
7203 
7204  /*
7205  * If the attribute list for the referenced table was omitted, lookup the
7206  * definition of the primary key and use it. Otherwise, validate the
7207  * supplied attribute list. In either case, discover the index OID and
7208  * index opclasses, and the attnums and type OIDs of the attributes.
7209  */
7210  if (fkconstraint->pk_attrs == NIL)
7211  {
7212  numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
7213  &fkconstraint->pk_attrs,
7214  pkattnum, pktypoid,
7215  opclasses);
7216  }
7217  else
7218  {
7219  numpks = transformColumnNameList(RelationGetRelid(pkrel),
7220  fkconstraint->pk_attrs,
7221  pkattnum, pktypoid);
7222  /* Look for an index matching the column list */
7223  indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
7224  opclasses);
7225  }
7226 
7227  /*
7228  * Now we can check permissions.
7229  */
7230  checkFkeyPermissions(pkrel, pkattnum, numpks);
7231 
7232  /*
7233  * Look up the equality operators to use in the constraint.
7234  *
7235  * Note that we have to be careful about the difference between the actual
7236  * PK column type and the opclass' declared input type, which might be
7237  * only binary-compatible with it. The declared opcintype is the right
7238  * thing to probe pg_amop with.
7239  */
7240  if (numfks != numpks)
7241  ereport(ERROR,
7242  (errcode(ERRCODE_INVALID_FOREIGN_KEY),
7243  errmsg("number of referencing and referenced columns for foreign key disagree")));
7244 
7245  /*
7246  * On the strength of a previous constraint, we might avoid scanning
7247  * tables to validate this one. See below.
7248  */
7249  old_check_ok = (fkconstraint->old_conpfeqop != NIL);
7250  Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
7251 
7252  for (i = 0; i < numpks; i++)
7253  {
7254  Oid pktype = pktypoid[i];
7255  Oid fktype = fktypoid[i];
7256  Oid fktyped;
7257  HeapTuple cla_ht;
7258  Form_pg_opclass cla_tup;
7259  Oid amid;
7260  Oid opfamily;
7261  Oid opcintype;
7262  Oid pfeqop;
7263  Oid ppeqop;
7264  Oid ffeqop;
7265  int16 eqstrategy;
7266  Oid pfeqop_right;
7267 
7268  /* We need several fields out of the pg_opclass entry */
7269  cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
7270  if (!HeapTupleIsValid(cla_ht))
7271  elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
7272  cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
7273  amid = cla_tup->opcmethod;
7274  opfamily = cla_tup->opcfamily;
7275  opcintype = cla_tup->opcintype;
7276  ReleaseSysCache(cla_ht);
7277 
7278  /*
7279  * Check it's a btree; currently this can never fail since no other
7280  * index AMs support unique indexes. If we ever did have other types
7281  * of unique indexes, we'd need a way to determine which operator
7282  * strategy number is equality. (Is it reasonable to insist that
7283  * every such index AM use btree's number for equality?)
7284  */
7285  if (amid != BTREE_AM_OID)
7286  elog(ERROR, "only b-tree indexes are supported for foreign keys");
7287  eqstrategy = BTEqualStrategyNumber;
7288 
7289  /*
7290  * There had better be a primary equality operator for the index.
7291  * We'll use it for PK = PK comparisons.
7292  */
7293  ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
7294  eqstrategy);
7295 
7296  if (!OidIsValid(ppeqop))
7297  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
7298  eqstrategy, opcintype, opcintype, opfamily);
7299 
7300  /*
7301  * Are there equality operators that take exactly the FK type? Assume
7302  * we should look through any domain here.
7303  */
7304  fktyped = getBaseType(fktype);
7305 
7306  pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
7307  eqstrategy);
7308  if (OidIsValid(pfeqop))
7309  {
7310  pfeqop_right = fktyped;
7311  ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
7312  eqstrategy);
7313  }
7314  else
7315  {
7316  /* keep compiler quiet */
7317  pfeqop_right = InvalidOid;
7318  ffeqop = InvalidOid;
7319  }
7320 
7321  if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
7322  {
7323  /*
7324  * Otherwise, look for an implicit cast from the FK type to the
7325  * opcintype, and if found, use the primary equality operator.
7326  * This is a bit tricky because opcintype might be a polymorphic
7327  * type such as ANYARRAY or ANYENUM; so what we have to test is
7328  * whether the two actual column types can be concurrently cast to
7329  * that type. (Otherwise, we'd fail to reject combinations such
7330  * as int[] and point[].)
7331  */
7332  Oid input_typeids[2];
7333  Oid target_typeids[2];
7334 
7335  input_typeids[0] = pktype;
7336  input_typeids[1] = fktype;
7337  target_typeids[0] = opcintype;
7338  target_typeids[1] = opcintype;
7339  if (can_coerce_type(2, input_typeids, target_typeids,
7341  {
7342  pfeqop = ffeqop = ppeqop;
7343  pfeqop_right = opcintype;
7344  }
7345  }
7346 
7347  if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
7348  ereport(ERROR,
7349  (errcode(ERRCODE_DATATYPE_MISMATCH),
7350  errmsg("foreign key constraint \"%s\" "
7351  "cannot be implemented",
7352  fkconstraint->conname),
7353  errdetail("Key columns \"%s\" and \"%s\" "
7354  "are of incompatible types: %s and %s.",
7355  strVal(list_nth(fkconstraint->fk_attrs, i)),
7356  strVal(list_nth(fkconstraint->pk_attrs, i)),
7357  format_type_be(fktype),
7358  format_type_be(pktype))));
7359 
7360  if (old_check_ok)
7361  {
7362  /*
7363  * When a pfeqop changes, revalidate the constraint. We could
7364  * permit intra-opfamily changes, but that adds subtle complexity
7365  * without any concrete benefit for core types. We need not
7366  * assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
7367  */
7368  old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
7369  old_pfeqop_item = lnext(old_pfeqop_item);
7370  }
7371  if (old_check_ok)
7372  {
7373  Oid old_fktype;
7374  Oid new_fktype;
7375  CoercionPathType old_pathtype;
7376  CoercionPathType new_pathtype;
7377  Oid old_castfunc;
7378  Oid new_castfunc;
7380  fkattnum[i] - 1);
7381 
7382  /*
7383  * Identify coercion pathways from each of the old and new FK-side
7384  * column types to the right (foreign) operand type of the pfeqop.
7385  * We may assume that pg_constraint.conkey is not changing.
7386  */
7387  old_fktype = attr->atttypid;
7388  new_fktype = fktype;
7389  old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
7390  &old_castfunc);
7391  new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
7392  &new_castfunc);
7393 
7394  /*
7395  * Upon a change to the cast from the FK column to its pfeqop
7396  * operand, revalidate the constraint. For this evaluation, a
7397  * binary coercion cast is equivalent to no cast at all. While
7398  * type implementors should design implicit casts with an eye
7399  * toward consistency of operations like equality, we cannot
7400  * assume here that they have done so.
7401  *
7402  * A function with a polymorphic argument could change behavior
7403  * arbitrarily in response to get_fn_expr_argtype(). Therefore,
7404  * when the cast destination is polymorphic, we only avoid
7405  * revalidation if the input type has not changed at all. Given
7406  * just the core data types and operator classes, this requirement
7407  * prevents no would-be optimizations.
7408  *
7409  * If the cast converts from a base type to a domain thereon, then
7410  * that domain type must be the opcintype of the unique index.
7411  * Necessarily, the primary key column must then be of the domain
7412  * type. Since the constraint was previously valid, all values on
7413  * the foreign side necessarily exist on the primary side and in
7414  * turn conform to the domain. Consequently, we need not treat
7415  * domains specially here.
7416  *
7417  * Since we require that all collations share the same notion of
7418  * equality (which they do, because texteq reduces to bitwise
7419  * equality), we don't compare collation here.
7420  *
7421  * We need not directly consider the PK type. It's necessarily
7422  * binary coercible to the opcintype of the unique index column,
7423  * and ri_triggers.c will only deal with PK datums in terms of
7424  * that opcintype. Changing the opcintype also changes pfeqop.
7425  */
7426  old_check_ok = (new_pathtype == old_pathtype &&
7427  new_castfunc == old_castfunc &&
7428  (!IsPolymorphicType(pfeqop_right) ||
7429  new_fktype == old_fktype));
7430 
7431  }
7432 
7433  pfeqoperators[i] = pfeqop;
7434  ppeqoperators[i] = ppeqop;
7435  ffeqoperators[i] = ffeqop;
7436  }
7437 
7438  /*
7439  * Record the FK constraint in pg_constraint.
7440  */
7441  constrOid = CreateConstraintEntry(fkconstraint->conname,
7442  RelationGetNamespace(rel),
7444  fkconstraint->deferrable,
7445  fkconstraint->initdeferred,
7446  fkconstraint->initially_valid,
7447  RelationGetRelid(rel),
7448  fkattnum,
7449  numfks,
7450  InvalidOid, /* not a domain constraint */
7451  indexOid,
7452  RelationGetRelid(pkrel),
7453  pkattnum,
7454  pfeqoperators,
7455  ppeqoperators,
7456  ffeqoperators,
7457  numpks,
7458  fkconstraint->fk_upd_action,
7459  fkconstraint->fk_del_action,
7460  fkconstraint->fk_matchtype,
7461  NULL, /* no exclusion constraint */
7462  NULL, /* no check constraint */
7463  NULL,
7464  NULL,
7465  true, /* islocal */
7466  0, /* inhcount */
7467  true, /* isnoinherit */
7468  false); /* is_internal */
7469  ObjectAddressSet(address, ConstraintRelationId, constrOid);
7470 
7471  /*
7472  * Create the triggers that will enforce the constraint.
7473  */
7474  createForeignKeyTriggers(rel, RelationGetRelid(pkrel), fkconstraint,
7475  constrOid, indexOid);
7476 
7477  /*
7478  * Tell Phase 3 to check that the constraint is satisfied by existing
7479  * rows. We can skip this during table creation, when requested explicitly
7480  * by specifying NOT VALID in an ADD FOREIGN KEY command, and when we're
7481  * recreating a constraint following a SET DATA TYPE operation that did
7482  * not impugn its validity.
7483  */
7484  if (!old_check_ok && !fkconstraint->skip_validation)
7485  {
7486  NewConstraint *newcon;
7487 
7488  newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
7489  newcon->name = fkconstraint->conname;
7490  newcon->contype = CONSTR_FOREIGN;
7491  newcon->refrelid = RelationGetRelid(pkrel);
7492  newcon->refindid = indexOid;
7493  newcon->conid = constrOid;
7494  newcon->qual = (Node *) fkconstraint;
7495 
7496  tab->constraints = lappend(tab->constraints, newcon);
7497  }
7498 
7499  /*
7500  * Close pk table, but keep lock until we've committed.
7501  */
7502  heap_close(pkrel, NoLock);
7503 
7504  return address;
7505 }
signed short int16
Definition: c.h:245
#define NIL
Definition: pg_list.h:69
#define CONSTRAINT_FOREIGN
char * name
Definition: tablecmds.c:184
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
List * old_conpfeqop
Definition: parsenodes.h:2116
bool IsSystemRelation(Relation relation)
Definition: catalog.c:63
#define RELPERSISTENCE_UNLOGGED
Definition: pg_class.h:171
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
char fk_matchtype
Definition: parsenodes.h:2113
static int transformColumnNameList(Oid relId, List *colList, int16 *attnums, Oid *atttypids)
Definition: tablecmds.c:7855
#define BTREE_AM_OID
Definition: pg_am.h:70
bool rd_islocaltemp
Definition: rel.h:90
Node * qual
Definition: tablecmds.c:189
Definition: nodes.h:510
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
bool initdeferred
Definition: parsenodes.h:2086
#define MemSet(start, val, len)
Definition: c.h:863
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
#define heap_close(r, l)
Definition: heapam.h:97
List * pk_attrs
Definition: parsenodes.h:2112
char * conname
Definition: parsenodes.h:2084
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
Definition: tablecmds.c:8167
#define OidIsValid(objectId)
Definition: c.h:532
CoercionPathType
Definition: parse_coerce.h:24
List * constraints
Definition: tablecmds.c:163
#define RELPERSISTENCE_PERMANENT
Definition: pg_class.h:170
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define IsPolymorphicType(typid)
Definition: pg_type.h:745
bool deferrable
Definition: parsenodes.h:2085
TupleDesc oldDesc
Definition: tablecmds.c:159
void * list_nth(const List *list, int n)
Definition: list.c:410
#define NoLock
Definition: lockdefs.h:34
int errdetail(const char *fmt,...)
Definition: elog.c:873
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:163
#define RelationGetRelationName(relation)
Definition: rel.h:436
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
static void createForeignKeyTriggers(Relation rel, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid)
Definition: tablecmds.c:8414
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
Oid old_pktable_oid
Definition: parsenodes.h:2117
List * lappend(List *list, void *datum)
Definition: list.c:128
ConstrType contype
Definition: tablecmds.c:185
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
void * palloc0(Size size)
Definition: mcxt.c:877
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1318
bool allowSystemTableMods
Definition: globals.c:112
#define InvalidOid
Definition: postgres_ext.h:36
bool initially_valid
Definition: parsenodes.h:2122
static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid, List **attnamelist, int16 *attnums, Oid *atttypids, Oid *opclasses)
Definition: tablecmds.c:7900
char fk_del_action
Definition: parsenodes.h:2115
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:681
#define ShareRowExclusiveLock
Definition: lockdefs.h:42
static CoercionPathType findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
Definition: tablecmds.c:8138
#define INDEX_MAX_KEYS
static int list_length(const List *l)
Definition: pg_list.h:89
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
static Oid transformFkeyCheckAttrs(Relation pkrel, int numattrs, int16 *attnums, Oid *opclasses)
Definition: tablecmds.c:7997
bool can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:526
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define ConstraintRelationId
Definition: pg_constraint.h:29
#define elog
Definition: elog.h:219
#define RELPERSISTENCE_TEMP
Definition: pg_class.h:172
RangeVar * pktable
Definition: parsenodes.h:2110
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2271
#define RELKIND_RELATION
Definition: pg_class.h:160
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:68
bool skip_validation
Definition: parsenodes.h:2121
#define RelationGetRelid(relation)
Definition: rel.h:416
Oid CreateConstraintEntry(const char *constraintName, Oid constraintNamespace, char constraintType, bool isDeferrable, bool isDeferred, bool isValidated, Oid relId, const int16 *constraintKey, int constraintNKeys, 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, const char *conSrc, bool conIsLocal, int conInhCount, bool conNoInherit, bool is_internal)
Definition: pg_constraint.c:49
List * fk_attrs
Definition: parsenodes.h:2111
#define BTEqualStrategyNumber
Definition: stratnum.h:31
char fk_upd_action
Definition: parsenodes.h:2114
#define lfirst_oid(lc)
Definition: pg_list.h:108
#define RelationGetNamespace(relation)
Definition: rel.h:443
static bool ATColumnChangeRequiresRewrite ( Node expr,
AttrNumber  varattno 
)
static

Definition at line 9021 of file tablecmds.c.

References arg, CoerceToDomain::arg, Assert, DomainHasConstraints(), IsA, and CoerceToDomain::resulttype.

Referenced by ATPrepAlterColumnType().

9022 {
9023  Assert(expr != NULL);
9024 
9025  for (;;)
9026  {
9027  /* only one varno, so no need to check that */
9028  if (IsA(expr, Var) &&((Var *) expr)->varattno == varattno)
9029  return false;
9030  else if (IsA(expr, RelabelType))
9031  expr = (Node *) ((RelabelType *) expr)->arg;
9032  else if (IsA(expr, CoerceToDomain))
9033  {
9034  CoerceToDomain *d = (CoerceToDomain *) expr;
9035 
9037  return true;
9038  expr = (Node *) d->arg;
9039  }
9040  else
9041  return true;
9042  }
9043 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
Definition: nodes.h:510
Definition: primnodes.h:163
bool DomainHasConstraints(Oid type_id)
Definition: typcache.c:1252
#define Assert(condition)
Definition: c.h:681
void * arg
static void ATController ( AlterTableStmt parsetree,
Relation  rel,
List cmds,
bool  recurse,
LOCKMODE  lockmode 
)
static

Definition at line 3458 of file tablecmds.c.

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

Referenced by AlterTable(), and AlterTableInternal().

3460 {
3461  List *wqueue = NIL;
3462  ListCell *lcmd;
3463 
3464  /* Phase 1: preliminary examination of commands, create work queue */
3465  foreach(lcmd, cmds)
3466  {
3467  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3468 
3469  ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode);
3470  }
3471 
3472  /* Close the relation, but keep lock until commit */
3473  relation_close(rel, NoLock);
3474 
3475  /* Phase 2: update system catalogs */
3476  ATRewriteCatalogs(&wqueue, lockmode);
3477 
3478  /* Phase 3: scan/rewrite tables as needed */
3479  ATRewriteTables(parsetree, &wqueue, lockmode);
3480 }
#define NIL
Definition: pg_list.h:69
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1266
#define NoLock
Definition: lockdefs.h:34
static void ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode)
Definition: tablecmds.c:4132
static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
Definition: tablecmds.c:3492
#define lfirst(lc)
Definition: pg_list.h:106
static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode)
Definition: tablecmds.c:3791
Definition: pg_list.h:45
void AtEOSubXact_on_commit_actions ( bool  isCommit,
SubTransactionId  mySubid,
SubTransactionId  parentSubid 
)

Definition at line 13022 of file tablecmds.c.

References OnCommitItem::creating_subid, OnCommitItem::deleting_subid, InvalidSubTransactionId, lfirst, list_delete_cell(), list_head(), lnext, and pfree().

Referenced by AbortSubTransaction(), and CommitSubTransaction().

13024 {
13025  ListCell *cur_item;
13026  ListCell *prev_item;
13027 
13028  prev_item = NULL;
13029  cur_item = list_head(on_commits);
13030 
13031  while (cur_item != NULL)
13032  {
13033  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
13034 
13035  if (!isCommit && oc->creating_subid == mySubid)
13036  {
13037  /* cur_item must be removed */
13038  on_commits = list_delete_cell(on_commits, cur_item, prev_item);
13039  pfree(oc);
13040  if (prev_item)
13041  cur_item = lnext(prev_item);
13042  else
13043  cur_item = list_head(on_commits);
13044  }
13045  else
13046  {
13047  /* cur_item must be preserved */
13048  if (oc->creating_subid == mySubid)
13049  oc->creating_subid = parentSubid;
13050  if (oc->deleting_subid == mySubid)
13051  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
13052  prev_item = cur_item;
13053  cur_item = lnext(prev_item);
13054  }
13055  }
13056 }
SubTransactionId creating_subid
Definition: tablecmds.c:120
void pfree(void *pointer)
Definition: mcxt.c:949
static List * on_commits
Definition: tablecmds.c:124
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
List * list_delete_cell(List *list, ListCell *cell, ListCell *prev)
Definition: list.c:528
SubTransactionId deleting_subid
Definition: tablecmds.c:121
#define lfirst(lc)
Definition: pg_list.h:106
#define InvalidSubTransactionId
Definition: c.h:397
void AtEOXact_on_commit_actions ( bool  isCommit)

Definition at line 12980 of file tablecmds.c.

References OnCommitItem::creating_subid, OnCommitItem::deleting_subid, InvalidSubTransactionId, lfirst, list_delete_cell(), list_head(), lnext, and pfree().

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

12981 {
12982  ListCell *cur_item;
12983  ListCell *prev_item;
12984 
12985  prev_item = NULL;
12986  cur_item = list_head(on_commits);
12987 
12988  while (cur_item != NULL)
12989  {
12990  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
12991 
12992  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
12994  {
12995  /* cur_item must be removed */
12996  on_commits = list_delete_cell(on_commits, cur_item, prev_item);
12997  pfree(oc);
12998  if (prev_item)
12999  cur_item = lnext(prev_item);
13000  else
13001  cur_item = list_head(on_commits);
13002  }
13003  else
13004  {
13005  /* cur_item must be preserved */
13008  prev_item = cur_item;
13009  cur_item = lnext(prev_item);
13010  }
13011  }
13012 }
SubTransactionId creating_subid
Definition: tablecmds.c:120
void pfree(void *pointer)
Definition: mcxt.c:949
static List * on_commits
Definition: tablecmds.c:124
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
List * list_delete_cell(List *list, ListCell *cell, ListCell *prev)
Definition: list.c:528
SubTransactionId deleting_subid
Definition: tablecmds.c:121
#define lfirst(lc)
Definition: pg_list.h:106
#define InvalidSubTransactionId
Definition: c.h:397
static ObjectAddress ATExecAddColumn ( List **  wqueue,
AlteredTableInfo tab,
Relation  rel,
ColumnDef colDef,
bool  isOid,
bool  recurse,
bool  recursing,
bool  if_not_exists,
LOCKMODE  lockmode 
)
static

Definition at line 5159 of file tablecmds.c.

References ACL_USAGE, aclcheck_error_type(), ACLCHECK_OK, add_column_collation_dependency(), add_column_datatype_dependency(), AddRelationNewConstraints(), TypeName::arrayBounds, AT_REWRITE_ALTER_OID, AT_REWRITE_DEFAULT_VAL, ATGetQueueEntry(), ATSimplePermissions(), ATT_FOREIGN_TABLE, ATT_TABLE, RawColumnDefault::attnum, NewColumnValue::attnum, AttributeRelationId, build_column_default(), CatalogTupleUpdate(), check_for_column_name_collision(), CheckAttributeType(), CheckTableNotInUse(), COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, ColumnDef::colname, CommandCounterIncrement(), copyObject, DomainHasConstraints(), elog, ereport, errcode(), errdetail(), errmsg(), ERROR, NewColumnValue::expr, expression_planner(), find_inheritance_children(), FormData_pg_attribute, get_collation_name(), get_typcollation(), getBaseTypeAndTypmod(), GetColumnDefCollation(), GETSTRUCT, GetUserId(), heap_close, heap_freetuple(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, ColumnDef::identity, ColumnDef::inhcount, InsertPgAttributeTuple(), InvalidObjectAddress, InvokeObjectPostCreateHook, ColumnDef::is_local, ColumnDef::is_not_null, lappend(), lfirst_oid, list_length(), list_make1, list_make1_oid, makeNullConst(), MaxHeapAttributeNumber, namestrcpy(), AlteredTableInfo::new_notnull, newval, AlteredTableInfo::newvals, NIL, NoLock, NOTICE, ObjectAddressSubSet, ObjectIdAttributeNumber, ObjectIdGetDatum, palloc(), palloc0(), pg_type_aclcheck(), RawColumnDefault::raw_default, ColumnDef::raw_default, RelationData::rd_rel, RelationGetRelationName, RelationGetRelid, RelationRelationId, ReleaseSysCache(), DropRelationCallbackState::relkind, RELKIND_COMPOSITE_TYPE, RELKIND_FOREIGN_TABLE, RELKIND_VIEW, RELOID, AlteredTableInfo::rewrite, RowExclusiveLock, SearchSysCacheCopy1, SearchSysCacheCopyAttName(), HeapTupleData::t_self, ColumnDef::typeName, typenameType(), and typenameTypeIdAndMod().

Referenced by ATExecCmd().

5163 {
5164  Oid myrelid = RelationGetRelid(rel);
5165  Relation pgclass,
5166  attrdesc;
5167  HeapTuple reltup;
5168  FormData_pg_attribute attribute;
5169  int newattnum;
5170  char relkind;
5171  HeapTuple typeTuple;
5172  Oid typeOid;
5173  int32 typmod;
5174  Oid collOid;
5175  Form_pg_type tform;
5176  Expr *defval;
5177  List *children;
5178  ListCell *child;
5179  AclResult aclresult;
5180  ObjectAddress address;
5181 
5182  /* At top level, permission check was done in ATPrepCmd, else do it */
5183  if (recursing)
5185 
5186  if (rel->rd_rel->relispartition && !recursing)
5187  ereport(ERROR,
5188  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5189  errmsg("cannot add column to a partition")));
5190 
5192 
5193  /*
5194  * Are we adding the column to a recursion child? If so, check whether to
5195  * merge with an existing definition for the column. If we do merge, we
5196  * must not recurse. Children will already have the column, and recursing
5197  * into them would mess up attinhcount.
5198  */
5199  if (colDef->inhcount > 0)
5200  {
5201  HeapTuple tuple;
5202 
5203  /* Does child already have a column by this name? */
5204  tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
5205  if (HeapTupleIsValid(tuple))
5206  {
5207  Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
5208  Oid ctypeId;
5209  int32 ctypmod;
5210  Oid ccollid;
5211 
5212  /* Child column must match on type, typmod, and collation */
5213  typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
5214  if (ctypeId != childatt->atttypid ||
5215  ctypmod != childatt->atttypmod)
5216  ereport(ERROR,
5217  (errcode(ERRCODE_DATATYPE_MISMATCH),
5218  errmsg("child table \"%s\" has different type for column \"%s\"",
5219  RelationGetRelationName(rel), colDef->colname)));
5220  ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
5221  if (ccollid != childatt->attcollation)
5222  ereport(ERROR,
5223  (errcode(ERRCODE_COLLATION_MISMATCH),
5224  errmsg("child table \"%s\" has different collation for column \"%s\"",
5225  RelationGetRelationName(rel), colDef->colname),
5226  errdetail("\"%s\" versus \"%s\"",
5227  get_collation_name(ccollid),
5228  get_collation_name(childatt->attcollation))));
5229 
5230  /* If it's OID, child column must actually be OID */
5231  if (isOid && childatt->attnum != ObjectIdAttributeNumber)
5232  ereport(ERROR,
5233  (errcode(ERRCODE_DATATYPE_MISMATCH),
5234  errmsg("child table \"%s\" has a conflicting \"%s\" column",
5235  RelationGetRelationName(rel), colDef->colname)));
5236 
5237  /* Bump the existing child att's inhcount */
5238  childatt->attinhcount++;
5239  CatalogTupleUpdate(attrdesc, &tuple->t_self, tuple);
5240 
5241  heap_freetuple(tuple);
5242 
5243  /* Inform the user about the merge */
5244  ereport(NOTICE,
5245  (errmsg("merging definition of column \"%s\" for child \"%s\"",
5246  colDef->colname, RelationGetRelationName(rel))));
5247 
5248  heap_close(attrdesc, RowExclusiveLock);
5249  return InvalidObjectAddress;
5250  }
5251  }
5252 
5254 
5255  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
5256  if (!HeapTupleIsValid(reltup))
5257  elog(ERROR, "cache lookup failed for relation %u", myrelid);
5258  relkind = ((Form_pg_class) GETSTRUCT(reltup))->relkind;
5259 
5260  /*
5261  * Cannot add identity column if table has children, because identity does
5262  * not inherit. (Adding column and identity separately will work.)
5263  */
5264  if (colDef->identity &&
5265  recurse &&
5266  find_inheritance_children(myrelid, NoLock) != NIL)
5267  ereport(ERROR,
5268  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5269  errmsg("cannot recursively add identity column to table that has child tables")));
5270 
5271  /* skip if the name already exists and if_not_exists is true */
5272  if (!check_for_column_name_collision(rel, colDef->colname, if_not_exists))
5273  {
5274  heap_close(attrdesc, RowExclusiveLock);
5275  heap_freetuple(reltup);
5276  heap_close(pgclass, RowExclusiveLock);
5277  return InvalidObjectAddress;
5278  }
5279 
5280  /* Determine the new attribute's number */
5281  if (isOid)
5282  newattnum = ObjectIdAttributeNumber;
5283  else
5284  {
5285  newattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts + 1;
5286  if (newattnum > MaxHeapAttributeNumber)
5287  ereport(ERROR,
5288  (errcode(ERRCODE_TOO_MANY_COLUMNS),
5289  errmsg("tables can have at most %d columns",
5291  }
5292 
5293  typeTuple = typenameType(NULL, colDef->typeName, &typmod);
5294  tform = (Form_pg_type) GETSTRUCT(typeTuple);
5295  typeOid = HeapTupleGetOid(typeTuple);
5296 
5297  aclresult = pg_type_aclcheck(typeOid, GetUserId(), ACL_USAGE);
5298  if (aclresult != ACLCHECK_OK)
5299  aclcheck_error_type(aclresult, typeOid);
5300 
5301  collOid = GetColumnDefCollation(NULL, colDef, typeOid);
5302 
5303  /* make sure datatype is legal for a column */
5304  CheckAttributeType(colDef->colname, typeOid, collOid,
5305  list_make1_oid(rel->rd_rel->reltype),
5306  false);
5307 
5308  /* construct new attribute's pg_attribute entry */
5309  attribute.attrelid = myrelid;
5310  namestrcpy(&(attribute.attname), colDef->colname);
5311  attribute.atttypid = typeOid;
5312  attribute.attstattarget = (newattnum > 0) ? -1 : 0;
5313  attribute.attlen = tform->typlen;
5314  attribute.attcacheoff = -1;
5315  attribute.atttypmod = typmod;
5316  attribute.attnum = newattnum;
5317  attribute.attbyval = tform->typbyval;
5318  attribute.attndims = list_length(colDef->typeName->arrayBounds);
5319  attribute.attstorage = tform->typstorage;
5320  attribute.attalign = tform->typalign;
5321  attribute.attnotnull = colDef->is_not_null;
5322  attribute.atthasdef = false;
5323  attribute.attidentity = colDef->identity;
5324  attribute.attisdropped = false;
5325  attribute.attislocal = colDef->is_local;
5326  attribute.attinhcount = colDef->inhcount;
5327  attribute.attcollation = collOid;
5328  /* attribute.attacl is handled by InsertPgAttributeTuple */
5329 
5330  ReleaseSysCache(typeTuple);
5331 
5332  InsertPgAttributeTuple(attrdesc, &attribute, NULL);
5333 
5334  heap_close(attrdesc, RowExclusiveLock);
5335 
5336  /*
5337  * Update pg_class tuple as appropriate
5338  */
5339  if (isOid)
5340  ((Form_pg_class) GETSTRUCT(reltup))->relhasoids = true;
5341  else
5342  ((Form_pg_class) GETSTRUCT(reltup))->relnatts = newattnum;
5343 
5344  CatalogTupleUpdate(pgclass, &reltup->t_self, reltup);
5345 
5346  heap_freetuple(reltup);
5347 
5348  /* Post creation hook for new attribute */
5349  InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
5350 
5351  heap_close(pgclass, RowExclusiveLock);
5352 
5353  /* Make the attribute's catalog entry visible */
5355 
5356  /*
5357  * Store the DEFAULT, if any, in the catalogs
5358  */
5359  if (colDef->raw_default)
5360  {
5361  RawColumnDefault *rawEnt;
5362 
5363  rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
5364  rawEnt->attnum = attribute.attnum;
5365  rawEnt->raw_default = copyObject(colDef->raw_default);
5366 
5367  /*
5368  * This function is intended for CREATE TABLE, so it processes a
5369  * _list_ of defaults, but we just do one.
5370  */
5372  false, true, false);
5373 
5374  /* Make the additional catalog changes visible */
5376  }
5377 
5378  /*
5379  * Tell Phase 3 to fill in the default expression, if there is one.
5380  *
5381  * If there is no default, Phase 3 doesn't have to do anything, because
5382  * that effectively means that the default is NULL. The heap tuple access
5383  * routines always check for attnum > # of attributes in tuple, and return
5384  * NULL if so, so without any modification of the tuple data we will get
5385  * the effect of NULL values in the new column.
5386  *
5387  * An exception occurs when the new column is of a domain type: the domain
5388  * might have a NOT NULL constraint, or a check constraint that indirectly
5389  * rejects nulls. If there are any domain constraints then we construct
5390  * an explicit NULL default value that will be passed through
5391  * CoerceToDomain processing. (This is a tad inefficient, since it causes
5392  * rewriting the table which we really don't have to do, but the present
5393  * design of domain processing doesn't offer any simple way of checking
5394  * the constraints more directly.)
5395  *
5396  * Note: we use build_column_default, and not just the cooked default
5397  * returned by AddRelationNewConstraints, so that the right thing happens
5398  * when a datatype's default applies.
5399  *
5400  * We skip this step completely for views and foreign tables. For a view,
5401  * we can only get here from CREATE OR REPLACE VIEW, which historically
5402  * doesn't set up defaults, not even for domain-typed columns. And in any
5403  * case we mustn't invoke Phase 3 on a view or foreign table, since they
5404  * have no storage.
5405  */
5406  if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE
5407  && relkind != RELKIND_FOREIGN_TABLE && attribute.attnum > 0)
5408  {
5409  defval = (Expr *) build_column_default(rel, attribute.attnum);
5410 
5411  if (!defval && DomainHasConstraints(typeOid))
5412  {
5413  Oid baseTypeId;
5414  int32 baseTypeMod;
5415  Oid baseTypeColl;
5416 
5417  baseTypeMod = typmod;
5418  baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
5419  baseTypeColl = get_typcollation(baseTypeId);
5420  defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
5421  defval = (Expr *) coerce_to_target_type(NULL,
5422  (Node *) defval,
5423  baseTypeId,
5424  typeOid,
5425  typmod,
5428  -1);
5429  if (defval == NULL) /* should not happen */
5430  elog(ERROR, "failed to coerce base type to domain");
5431  }
5432 
5433  if (defval)
5434  {
5436 
5437  newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
5438  newval->attnum = attribute.attnum;
5439  newval->expr = expression_planner(defval);
5440 
5441  tab->newvals = lappend(tab->newvals, newval);
5443  }
5444 
5445  /*
5446  * If the new column is NOT NULL, tell Phase 3 it needs to test that.
5447  * (Note we don't do this for an OID column. OID will be marked not
5448  * null, but since it's filled specially, there's no need to test
5449  * anything.)
5450  */
5451  tab->new_notnull |= colDef->is_not_null;
5452  }
5453 
5454  /*
5455  * If we are adding an OID column, we have to tell Phase 3 to rewrite the
5456  * table to fix that.
5457  */
5458  if (isOid)
5459  tab->rewrite |= AT_REWRITE_ALTER_OID;
5460 
5461  /*
5462  * Add needed dependency entries for the new column.
5463  */
5464  add_column_datatype_dependency(myrelid, newattnum, attribute.atttypid);
5465  add_column_collation_dependency(myrelid, newattnum, attribute.attcollation);
5466 
5467  /*
5468  * Propagate to children as appropriate. Unlike most other ALTER
5469  * routines, we have to do this one level of recursion at a time; we can't
5470  * use find_all_inheritors to do it in one pass.
5471  */
5472  children = find_inheritance_children(RelationGetRelid(rel), lockmode);
5473 
5474  /*
5475  * If we are told not to recurse, there had better not be any child
5476  * tables; else the addition would put them out of step.
5477  */
5478  if (children && !recurse)
5479  ereport(ERROR,
5480  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5481  errmsg("column must be added to child tables too")));
5482 
5483  /* Children should see column as singly inherited */
5484  if (!recursing)
5485  {
5486  colDef = copyObject(colDef);
5487  colDef->inhcount = 1;
5488  colDef->is_local = false;
5489  }
5490 
5491  foreach(child, children)
5492  {
5493  Oid childrelid = lfirst_oid(child);
5494  Relation childrel;
5495  AlteredTableInfo *childtab;
5496 
5497  /* find_inheritance_children already got lock */
5498  childrel = heap_open(childrelid, NoLock);
5499  CheckTableNotInUse(childrel, "ALTER TABLE");
5500 
5501  /* Find or create work queue entry for this table */
5502  childtab = ATGetQueueEntry(wqueue, childrel);
5503 
5504  /* Recurse to child; return value is ignored */
5505  ATExecAddColumn(wqueue, childtab, childrel,
5506  colDef, isOid, recurse, true,
5507  if_not_exists, lockmode);
5508 
5509  heap_close(childrel, NoLock);
5510  }
5511 
5512  ObjectAddressSubSet(address, RelationRelationId, myrelid, newattnum);
5513  return address;
5514 }
#define NIL
Definition: pg_list.h:69
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2288
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:247
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
AttrNumber attnum
Definition: heap.h:24
bool is_local
Definition: parsenodes.h:642
Oid GetUserId(void)
Definition: miscinit.c:284
#define ObjectIdAttributeNumber
Definition: sysattr.h:22
char identity
Definition: parsenodes.h:649
char * get_collation_name(Oid colloid)
Definition: lsyscache.c:967
#define RelationRelationId
Definition: pg_class.h:29
Expr * expression_planner(Expr *expr)
Definition: planner.c:5997
static ObjectAddress ATExecAddColumn(List **wqueue, AlteredTableInfo *tab, Relation rel, ColumnDef *colDef, bool isOid, bool recurse, bool recursing, bool if_not_exists, LOCKMODE lockmode)
Definition: tablecmds.c:5159
Definition: nodes.h:510
#define AttributeRelationId
Definition: pg_attribute.h:33
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
bool is_not_null
Definition: parsenodes.h:643
FormData_pg_type * Form_pg_type
Definition: pg_type.h:233
Form_pg_class rd_rel
Definition: rel.h:114
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
#define ATT_TABLE
Definition: tablecmds.c:281
int namestrcpy(Name name, const char *str)
Definition: name.c:216
#define RELKIND_COMPOSITE_TYPE
Definition: pg_class.h:166
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3457
signed int int32
Definition: c.h:246
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:334
bool DomainHasConstraints(Oid type_id)
Definition: typcache.c:1252
#define list_make1(x1)
Definition: pg_list.h:139
#define AT_REWRITE_DEFAULT_VAL
Definition: event_trigger.h:32
static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
Definition: tablecmds.c:5574
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
HeapTuple SearchSysCacheCopyAttName(Oid relid, const char *attname)
Definition: syscache.c:1271
ItemPointerData t_self
Definition: htup.h:65
static void add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
Definition: tablecmds.c:5592
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:436
static AlteredTableInfo * ATGetQueueEntry(List **wqueue, Relation rel)
Definition: tablecmds.c:4689
Node * raw_default
Definition: heap.h:25
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ACL_USAGE
Definition: parsenodes.h:80
#define AT_REWRITE_ALTER_OID
Definition: event_trigger.h:34
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3062
#define ereport(elevel, rest)
Definition: elog.h:122
Node * raw_default
Definition: parsenodes.h:647
List * lappend(List *list, void *datum)
Definition: list.c:128
void CheckAttributeType(const char *attname, Oid atttypid, Oid attcollation, List *containing_rowtypes, bool allow_system_table_mods)
Definition: heap.c:490
Oid GetColumnDefCollation(ParseState *pstate, ColumnDef *coldef, Oid typeOid)
Definition: parse_type.c:521
Node * build_column_default(Relation rel, int attrno)
void * palloc0(Size size)
Definition: mcxt.c:877
AclResult
Definition: acl.h:178
void CommandCounterIncrement(void)
Definition: xact.c:915
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define list_make1_oid(x1)
Definition: pg_list.h:151
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
void typenameTypeIdAndMod(ParseState *pstate, const TypeName *typeName, Oid *typeid_p, int32 *typmod_p)
Definition: parse_type.c:293
FormData_pg_attribute
Definition: pg_attribute.h:171
List * find_inheritance_children(Oid parentrelId, LOCKMODE lockmode)
Definition: pg_inherits.c:57
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2781
#define NOTICE
Definition: elog.h:37
#define MaxHeapAttributeNumber
Definition: htup_details.h:47
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
static int list_length(const List *l)
Definition: pg_list.h:89
#define newval
TypeName * typeName
Definition: parsenodes.h:640
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
List * arrayBounds
Definition: parsenodes.h:214
void InsertPgAttributeTuple(Relation pg_attribute_rel, Form_pg_attribute new_attribute, CatalogIndexState indstate)
Definition: heap.c:600
const ObjectAddress InvalidObjectAddress
void * palloc(Size size)
Definition: mcxt.c:848
int errmsg(const char *fmt,...)
Definition: elog.c:797
static bool check_for_column_name_collision(Relation rel, const char *colname, bool if_not_exists)
Definition: tablecmds.c:5521
#define RELKIND_VIEW
Definition: pg_class.h:164
int inhcount
Definition: parsenodes.h:641
static void ATSimplePermissions(Relation rel, int allowed_targets)
Definition: tablecmds.c:4726
char * colname
Definition: parsenodes.h:639
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
#define copyObject(obj)
Definition: nodes.h:623
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4534
Definition: pg_list.h:45
#define ATT_FOREIGN_TABLE
Definition: tablecmds.c:286
#define RelationGetRelid(relation)
Definition: rel.h:416
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal)
Definition: heap.c:2227
#define lfirst_oid(lc)
Definition: pg_list.h:108
AttrNumber attnum
Definition: tablecmds.c:202
static ObjectAddress ATExecAddConstraint ( List **  wqueue,
AlteredTableInfo tab,
Relation  rel,
Constraint newConstraint,
bool  recurse,
bool  is_readd,
LOCKMODE  lockmode 
)
static

Definition at line 6895 of file tablecmds.c.

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

Referenced by ATExecCmd().

6898 {
6900 
6901  Assert(IsA(newConstraint, Constraint));
6902 
6903  /*
6904  * Currently, we only expect to see CONSTR_CHECK and CONSTR_FOREIGN nodes
6905  * arriving here (see the preprocessing done in parse_utilcmd.c). Use a
6906  * switch anyway to make it easier to add more code later.
6907  */
6908  switch (newConstraint->contype)
6909  {
6910  case CONSTR_CHECK:
6911  address =
6912  ATAddCheckConstraint(wqueue, tab, rel,
6913  newConstraint, recurse, false, is_readd,
6914  lockmode);
6915  break;
6916 
6917  case CONSTR_FOREIGN:
6918 
6919  /*
6920  * Note that we currently never recurse for FK constraints, so the
6921  * "recurse" flag is silently ignored.
6922  *
6923  * Assign or validate constraint name
6924  */
6925  if (newConstraint->conname)
6926  {
6928  RelationGetRelid(rel),
6929  RelationGetNamespace(rel),
6930  newConstraint->conname))
6931  ereport(ERROR,
6933  errmsg("constraint \"%s\" for relation \"%s\" already exists",
6934  newConstraint->conname,
6935  RelationGetRelationName(rel))));
6936  }
6937  else
6938  newConstraint->conname =
6940  strVal(linitial(newConstraint->fk_attrs)),
6941  "fkey",
6942  RelationGetNamespace(rel),
6943  NIL);
6944 
6945  address = ATAddForeignKeyConstraint(tab, rel, newConstraint,
6946  lockmode);
6947  break;
6948 
6949  default:
6950  elog(ERROR, "unrecognized constraint type: %d",
6951  (int) newConstraint->contype);
6952  }
6953 
6954  return address;
6955 }
#define NIL
Definition: pg_list.h:69
char * ChooseConstraintName(const char *name1, const char *name2, const char *label, Oid namespaceid, List *others)
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
static ObjectAddress ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel, Constraint *fkconstraint, LOCKMODE lockmode)
Definition: tablecmds.c:7100
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
static ObjectAddress ATAddCheckConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel, Constraint *constr, bool recurse, bool recursing, bool is_readd, LOCKMODE lockmode)
Definition: tablecmds.c:6973
char * conname
Definition: parsenodes.h:2084
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:436
#define ereport(elevel, rest)
Definition: elog.h:122
#define Assert(condition)
Definition: c.h:681
bool ConstraintNameIsUsed(ConstraintCategory conCat, Oid objId, Oid objNamespace, const char *conname)
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:797
ConstrType contype
Definition: parsenodes.h:2081
#define elog
Definition: elog.h:219
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:30
#define RelationGetRelid(relation)
Definition: rel.h:416
List * fk_attrs
Definition: parsenodes.h:2111
#define RelationGetNamespace(relation)
Definition: rel.h:443
static ObjectAddress ATExecAddIdentity ( Relation  rel,
const char *  colName,
Node def,
LOCKMODE  lockmode 
)
static

Definition at line 5946 of file tablecmds.c.

References AttributeRelationId, castNode, CatalogTupleUpdate(), ereport, errcode(), errmsg(), ERROR, GETSTRUCT, heap_close, heap_freetuple(), heap_open(), HeapTupleIsValid, ColumnDef::identity, InvokeObjectPostAlterHook, ObjectAddressSubSet, RelationGetRelationName, RelationGetRelid, RelationRelationId, RowExclusiveLock, SearchSysCacheCopyAttName(), and HeapTupleData::t_self.

Referenced by ATExecCmd().

5948 {
5949  Relation attrelation;
5950  HeapTuple tuple;
5951  Form_pg_attribute attTup;
5952  AttrNumber attnum;
5953  ObjectAddress address;
5954  ColumnDef *cdef = castNode(ColumnDef, def);
5955 
5957 
5958  tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5959  if (!HeapTupleIsValid(tuple))
5960  ereport(ERROR,
5961  (errcode(ERRCODE_UNDEFINED_COLUMN),
5962  errmsg("column \"%s\" of relation \"%s\" does not exist",
5963  colName, RelationGetRelationName(rel))));
5964  attTup = (Form_pg_attribute) GETSTRUCT(tuple);
5965  attnum = attTup->attnum;
5966 
5967  /* Can't alter a system attribute */
5968  if (attnum <= 0)
5969  ereport(ERROR,
5970  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5971  errmsg("cannot alter system column \"%s\"",
5972  colName)));
5973 
5974  /*
5975  * Creating a column as identity implies NOT NULL, so adding the identity
5976  * to an existing column that is not NOT NULL would create a state that
5977  * cannot be reproduced without contortions.
5978  */
5979  if (!attTup->attnotnull)
5980  ereport(ERROR,
5981  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5982  errmsg("column \"%s\" of relation \"%s\" must be declared NOT NULL before identity can be added",
5983  colName, RelationGetRelationName(rel))));
5984 
5985  if (attTup->attidentity)
5986  ereport(ERROR,
5987  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5988  errmsg("column \"%s\" of relation \"%s\" is already an identity column",
5989  colName, RelationGetRelationName(rel))));
5990 
5991  if (attTup->atthasdef)
5992  ereport(ERROR,
5993  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5994  errmsg("column \"%s\" of relation \"%s\" already has a default value",
5995  colName, RelationGetRelationName(rel))));
5996 
5997  attTup->attidentity = cdef->identity;
5998  CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
5999 
6001  RelationGetRelid(rel),
6002  attTup->attnum);
6004  RelationGetRelid(rel), attnum);
6005  heap_freetuple(tuple);
6006 
6007  heap_close(attrelation, RowExclusiveLock);
6008 
6009  return address;
6010 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define castNode(_type_, nodeptr)
Definition: nodes.h:579
char identity
Definition: parsenodes.h:649
#define RelationRelationId
Definition: pg_class.h:29
#define AttributeRelationId
Definition: pg_attribute.h:33
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCacheCopyAttName(Oid relid, const char *attname)
Definition: syscache.c:1271
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:436
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
int errmsg(const char *fmt,...)
Definition: elog.c:797
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:416
static ObjectAddress ATExecAddIndex ( AlteredTableInfo tab,
Relation  rel,
IndexStmt stmt,
bool  is_rebuild,
LOCKMODE  lockmode 
)
static

Definition at line 6763 of file tablecmds.c.

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

Referenced by ATExecCmd().

6765 {
6766  bool check_rights;
6767  bool skip_build;
6768  bool quiet;
6769  ObjectAddress address;
6770 
6771  Assert(IsA(stmt, IndexStmt));
6772  Assert(!stmt->concurrent);
6773 
6774  /* The IndexStmt has already been through transformIndexStmt */
6775  Assert(stmt->transformed);
6776 
6777  /* suppress schema rights check when rebuilding existing index */
6778  check_rights = !is_rebuild;
6779  /* skip index build if phase 3 will do it or we're reusing an old one */
6780  skip_build = tab->rewrite > 0 || OidIsValid(stmt->oldNode);
6781  /* suppress notices when rebuilding existing index */
6782  quiet = is_rebuild;
6783 
6784  address = DefineIndex(RelationGetRelid(rel),
6785  stmt,
6786  InvalidOid, /* no predefined OID */
6787  true, /* is_alter_table */
6788  check_rights,
6789  false, /* check_not_in_use - we did it already */
6790  skip_build,
6791  quiet);
6792 
6793  /*
6794  * If TryReuseIndex() stashed a relfilenode for us, we used it for the new
6795  * index instead of building from scratch. The DROP of the old edition of
6796  * this index will have scheduled the storage for deletion at commit, so
6797  * cancel that pending deletion.
6798  */
6799  if (OidIsValid(stmt->oldNode))
6800  {
6801  Relation irel = index_open(address.objectId, NoLock);
6802 
6803  RelationPreserveStorage(irel->rd_node, true);
6804  index_close(irel, NoLock);
6805  }
6806 
6807  return address;
6808 }
void RelationPreserveStorage(RelFileNode rnode, bool atCommit)
Definition: storage.c:190
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
#define OidIsValid(objectId)
Definition: c.h:532
#define NoLock
Definition: lockdefs.h:34
bool transformed
Definition: parsenodes.h:2715
#define InvalidOid
Definition: postgres_ext.h:36
RelFileNode rd_node
Definition: rel.h:85
#define Assert(condition)
Definition: c.h:681
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
bool concurrent
Definition: parsenodes.h:2716
ObjectAddress DefineIndex(Oid relationId, IndexStmt *stmt, Oid indexRelationId, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
Definition: indexcmds.c:308
#define RelationGetRelid(relation)
Definition: rel.h:416
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
static ObjectAddress ATExecAddIndexConstraint ( AlteredTableInfo tab,
Relation  rel,
IndexStmt stmt,
LOCKMODE  lockmode 
)
static

Definition at line 6816 of file tablecmds.c.

References AccessShareLock, allowSystemTableMods, Assert, BuildIndexInfo(), CONSTRAINT_PRIMARY, CONSTRAINT_UNIQUE, IndexStmt::deferrable, elog, ereport, errmsg(), ERROR, IndexStmt::idxname, IndexInfo::ii_Unique, index_check_primary_key(), index_close(), index_constraint_create(), index_open(), IndexStmt::indexOid, IndexStmt::initdeferred, IsA, IndexStmt::isconstraint, NoLock, NOTICE, OidIsValid, IndexStmt::primary, pstrdup(), RelationGetRelationName, and RenameRelationInternal().

Referenced by ATExecCmd().

6818 {
6819  Oid index_oid = stmt->indexOid;
6820  Relation indexRel;
6821  char *indexName;
6822  IndexInfo *indexInfo;
6823  char *constraintName;
6824  char constraintType;
6825  ObjectAddress address;
6826 
6827  Assert(IsA(stmt, IndexStmt));
6828  Assert(OidIsValid(index_oid));
6829  Assert(stmt->isconstraint);
6830 
6831  indexRel = index_open(index_oid, AccessShareLock);
6832 
6833  indexName = pstrdup(RelationGetRelationName(indexRel));
6834 
6835  indexInfo = BuildIndexInfo(indexRel);
6836 
6837  /* this should have been checked at parse time */
6838  if (!indexInfo->ii_Unique)
6839  elog(ERROR, "index \"%s\" is not unique", indexName);
6840 
6841  /*
6842  * Determine name to assign to constraint. We require a constraint to
6843  * have the same name as the underlying index; therefore, use the index's
6844  * existing name as the default constraint name, and if the user
6845  * explicitly gives some other name for the constraint, rename the index
6846  * to match.
6847  */
6848  constraintName = stmt->idxname;
6849  if (constraintName == NULL)
6850  constraintName = indexName;
6851  else if (strcmp(constraintName, indexName) != 0)
6852  {
6853  ereport(NOTICE,
6854  (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
6855  indexName, constraintName)));
6856  RenameRelationInternal(index_oid, constraintName, false);
6857  }
6858 
6859  /* Extra checks needed if making primary key */
6860  if (stmt->primary)
6861  index_check_primary_key(rel, indexInfo, true);
6862 
6863  /* Note we currently don't support EXCLUSION constraints here */
6864  if (stmt->primary)
6865  constraintType = CONSTRAINT_PRIMARY;
6866  else
6867  constraintType = CONSTRAINT_UNIQUE;
6868 
6869  /* Create the catalog entries for the constraint */
6870  address = index_constraint_create(rel,
6871  index_oid,
6872  indexInfo,
6873  constraintName,
6874  constraintType,
6875  stmt->deferrable,
6876  stmt->initdeferred,
6877  stmt->primary,
6878  true, /* update pg_index */
6879  true, /* remove old dependencies */
6881  false); /* is_internal */
6882 
6883  index_close(indexRel, NoLock);
6884 
6885  return address;
6886 }
bool deferrable
Definition: parsenodes.h:2713
bool primary
Definition: parsenodes.h:2711
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal)
Definition: tablecmds.c:2966
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
char * pstrdup(const char *in)
Definition: mcxt.c:1076
#define AccessShareLock
Definition: lockdefs.h:36
void index_check_primary_key(Relation heapRel, IndexInfo *indexInfo, bool is_alter_table)
Definition: index.c:195
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:1642
unsigned int Oid
Definition: postgres_ext.h:31
#define CONSTRAINT_UNIQUE
#define OidIsValid(objectId)
Definition: c.h:532
#define CONSTRAINT_PRIMARY
Oid indexOid
Definition: parsenodes.h:2708
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:436
#define ereport(elevel, rest)
Definition: elog.h:122
char * idxname
Definition: parsenodes.h:2699
bool allowSystemTableMods
Definition: globals.c:112
#define NOTICE
Definition: elog.h:37
bool ii_Unique
Definition: execnodes.h:146
#define Assert(condition)
Definition: c.h:681
bool initdeferred
Definition: parsenodes.h:2714
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
bool isconstraint
Definition: parsenodes.h:2712
int errmsg(const char *fmt,...)
Definition: elog.c:797
ObjectAddress index_constraint_create(Relation heapRelation, Oid indexRelationId, IndexInfo *indexInfo, const char *constraintName, char constraintType, bool deferrable, bool initdeferred, bool mark_as_primary, bool update_pgindex, bool remove_old_dependencies, bool allow_system_table_mods, bool is_internal)
Definition: index.c:1150
#define elog
Definition: elog.h:219
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
static ObjectAddress ATExecAddInherit ( Relation  child_rel,
RangeVar parent,
LOCKMODE  lockmode 
)
static

Definition at line 11043 of file tablecmds.c.

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

Referenced by ATExecCmd().

11044 {
11045  Relation parent_rel;
11046  List *children;
11047  ObjectAddress address;
11048  const char *trigger_name;
11049 
11050  /*
11051  * A self-exclusive lock is needed here. See the similar case in
11052  * MergeAttributes() for a full explanation.
11053  */
11054  parent_rel = heap_openrv(parent, ShareUpdateExclusiveLock);
11055 
11056  /*
11057  * Must be owner of both parent and child -- child was checked by
11058  * ATSimplePermissions call in ATPrepCmd
11059  */
11061 
11062  /* Permanent rels cannot inherit from temporary ones */
11063  if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
11064  child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
11065  ereport(ERROR,
11066  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11067  errmsg("cannot inherit from temporary relation \"%s\"",
11068  RelationGetRelationName(parent_rel))));
11069 
11070  /* If parent rel is temp, it must belong to this session */
11071  if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
11072  !parent_rel->rd_islocaltemp)
11073  ereport(ERROR,
11074  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11075  errmsg("cannot inherit from temporary relation of another session")));
11076 
11077  /* Ditto for the child */
11078  if (child_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
11079  !child_rel->rd_islocaltemp)
11080  ereport(ERROR,
11081  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11082  errmsg("cannot inherit to temporary relation of another session")));
11083 
11084  /* Prevent partitioned tables from becoming inheritance parents */
11085  if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
11086  ereport(ERROR,
11087  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11088  errmsg("cannot inherit from partitioned table \"%s\"",
11089  parent->relname)));
11090 
11091  /* Likewise for partitions */
11092  if (parent_rel->rd_rel->relispartition)
11093  ereport(ERROR,
11094  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11095  errmsg("cannot inherit from a partition")));
11096 
11097  /*
11098  * Prevent circularity by seeing if proposed parent inherits from child.
11099  * (In particular, this disallows making a rel inherit from itself.)
11100  *
11101  * This is not completely bulletproof because of race conditions: in
11102  * multi-level inheritance trees, someone else could concurrently be
11103  * making another inheritance link that closes the loop but does not join
11104  * either of the rels we have locked. Preventing that seems to require
11105  * exclusive locks on the entire inheritance tree, which is a cure worse
11106  * than the disease. find_all_inheritors() will cope with circularity
11107  * anyway, so don't sweat it too much.
11108  *
11109  * We use weakest lock we can on child's children, namely AccessShareLock.
11110  */
11111  children = find_all_inheritors(RelationGetRelid(child_rel),
11112  AccessShareLock, NULL);
11113 
11114  if (list_member_oid(children, RelationGetRelid(parent_rel)))
11115  ereport(ERROR,
11116  (errcode(ERRCODE_DUPLICATE_TABLE),
11117  errmsg("circular inheritance not allowed"),
11118  errdetail("\"%s\" is already a child of \"%s\".",
11119  parent->relname,
11120  RelationGetRelationName(child_rel))));
11121 
11122  /* If parent has OIDs then child must have OIDs */
11123  if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
11124  ereport(ERROR,
11125  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11126  errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
11127  RelationGetRelationName(child_rel),
11128  RelationGetRelationName(parent_rel))));
11129 
11130  /*
11131  * If child_rel has row-level triggers with transition tables, we
11132  * currently don't allow it to become an inheritance child. See also
11133  * prohibitions in ATExecAttachPartition() and CreateTrigger().
11134  */
11135  trigger_name = FindTriggerIncompatibleWithInheritance(child_rel->trigdesc);
11136  if (trigger_name != NULL)
11137  ereport(ERROR,
11138  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
11139  errmsg("trigger \"%s\" prevents table \"%s\" from becoming an inheritance child",
11140  trigger_name, RelationGetRelationName(child_rel)),
11141  errdetail("ROW triggers with transition tables are not supported in inheritance hierarchies")));
11142 
11143  /* OK to create inheritance */
11144  CreateInheritance(child_rel, parent_rel);
11145 
11147  RelationGetRelid(parent_rel));
11148 
11149  /* keep our lock on the parent relation until commit */
11150  heap_close(parent_rel, NoLock);
11151 
11152  return address;
11153 }
#define RelationRelationId
Definition: pg_class.h:29
bool rd_islocaltemp
Definition: rel.h:90
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:114
#define ATT_TABLE
Definition: tablecmds.c:281
static void CreateInheritance(Relation child_rel, Relation parent_rel)
Definition: tablecmds.c:11163
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:43
TriggerDesc * trigdesc
Definition: rel.h:120
#define NoLock
Definition: lockdefs.h:34
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:436
#define ereport(elevel, rest)
Definition: elog.h:122
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1318
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:167
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void ATSimplePermissions(Relation rel, int allowed_targets)
Definition: tablecmds.c:4726
#define RELPERSISTENCE_TEMP
Definition: pg_class.h:172
Definition: pg_list.h:45
#define ATT_FOREIGN_TABLE
Definition: tablecmds.c:286
#define RelationGetRelid(relation)
Definition: rel.h:416
const char * FindTriggerIncompatibleWithInheritance(TriggerDesc *trigdesc)
Definition: trigger.c:2096
static ObjectAddress ATExecAddOf ( Relation  rel,
const TypeName ofTypename,
LOCKMODE  lockmode 
)
static

Definition at line 11867 of file tablecmds.c.

References AccessShareLock, Anum_pg_inherits_inhrelid, BTEqualStrategyNumber, CatalogTupleUpdate(), check_of_type(), ObjectAddress::classId, DecrTupleDescRefCount(), DEPENDENCY_NORMAL, drop_parent_dependency(), elog, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, heap_close, heap_freetuple(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, InheritsRelationId, InheritsRelidSeqnoIndexId, InvokeObjectPostAlterHook, lookup_rowtype_tupdesc(), NAMEDATALEN, NameStr, tupleDesc::natts, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, RelationData::rd_rel, recordDependencyOn(), RelationGetDescr, RelationGetRelationName, RelationGetRelid, RelationRelationId, ReleaseSysCache(), RELOID, RowExclusiveLock, ScanKeyInit(), SearchSysCacheCopy1, systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, TupleDescAttr, typenameType(), and TypeRelationId.

Referenced by ATExecCmd().

11868 {
11869  Oid relid = RelationGetRelid(rel);
11870  Type typetuple;
11871  Oid typeid;
11872  Relation inheritsRelation,
11873  relationRelation;
11874  SysScanDesc scan;
11875  ScanKeyData key;
11876  AttrNumber table_attno,
11877  type_attno;
11878  TupleDesc typeTupleDesc,
11879  tableTupleDesc;
11880  ObjectAddress tableobj,
11881  typeobj;
11882  HeapTuple classtuple;
11883 
11884  /* Validate the type. */
11885  typetuple = typenameType(NULL, ofTypename, NULL);
11886  check_of_type(typetuple);
11887  typeid = HeapTupleGetOid(typetuple);
11888 
11889  /* Fail if the table has any inheritance parents. */
11890  inheritsRelation = heap_open(InheritsRelationId, AccessShareLock);
11891  ScanKeyInit(&key,
11893  BTEqualStrategyNumber, F_OIDEQ,
11894  ObjectIdGetDatum(relid));
11895  scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
11896  true, NULL, 1, &key);
11898  ereport(ERROR,
11899  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11900  errmsg("typed tables cannot inherit")));
11901  systable_endscan(scan);
11902  heap_close(inheritsRelation, AccessShareLock);
11903 
11904  /*
11905  * Check the tuple descriptors for compatibility. Unlike inheritance, we
11906  * require that the order also match. However, attnotnull need not match.
11907  * Also unlike inheritance, we do not require matching relhasoids.
11908  */
11909  typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
11910  tableTupleDesc = RelationGetDescr(rel);
11911  table_attno = 1;
11912  for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
11913  {
11914  Form_pg_attribute type_attr,
11915  table_attr;
11916  const char *type_attname,
11917  *table_attname;
11918 
11919  /* Get the next non-dropped type attribute. */
11920  type_attr = TupleDescAttr(typeTupleDesc, type_attno - 1);
11921  if (type_attr->attisdropped)
11922  continue;
11923  type_attname = NameStr(type_attr->attname);
11924 
11925  /* Get the next non-dropped table attribute. */
11926  do
11927  {
11928  if (table_attno > tableTupleDesc->natts)
11929  ereport(ERROR,
11930  (errcode(ERRCODE_DATATYPE_MISMATCH),
11931  errmsg("table is missing column \"%s\"",
11932  type_attname)));
11933  table_attr = TupleDescAttr(tableTupleDesc, table_attno - 1);
11934  table_attno++;
11935  } while (table_attr->attisdropped);
11936  table_attname = NameStr(table_attr->attname);
11937 
11938  /* Compare name. */
11939  if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
11940  ereport(ERROR,
11941  (errcode(ERRCODE_DATATYPE_MISMATCH),
11942  errmsg("table has column \"%s\" where type requires \"%s\"",
11943  table_attname, type_attname)));
11944 
11945  /* Compare type. */
11946  if (table_attr->atttypid != type_attr->atttypid ||
11947  table_attr->atttypmod != type_attr->atttypmod ||
11948  table_attr->attcollation != type_attr->attcollation)
11949  ereport(ERROR,
11950  (errcode(ERRCODE_DATATYPE_MISMATCH),
11951  errmsg("table \"%s\" has different type for column \"%s\"",
11952  RelationGetRelationName(rel), type_attname)));
11953  }
11954  DecrTupleDescRefCount(typeTupleDesc);
11955 
11956  /* Any remaining columns at the end of the table had better be dropped. */
11957  for (; table_attno <= tableTupleDesc->natts; table_attno++)
11958  {
11959  Form_pg_attribute table_attr = TupleDescAttr(tableTupleDesc,
11960  table_attno - 1);
11961 
11962  if (!table_attr->attisdropped)
11963  ereport(ERROR,
11964  (errcode(ERRCODE_DATATYPE_MISMATCH),
11965  errmsg("table has extra column \"%s\"",
11966  NameStr(table_attr->attname))));
11967  }
11968 
11969  /* If the table was already typed, drop the existing dependency. */
11970  if (rel->rd_rel->reloftype)
11971  drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
11973 
11974  /* Record a dependency on the new type. */
11975  tableobj.classId = RelationRelationId;
11976  tableobj.objectId = relid;
11977  tableobj.objectSubId = 0;
11978  typeobj.classId = TypeRelationId;
11979  typeobj.objectId = typeid;
11980  typeobj.objectSubId = 0;
11981  recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
11982 
11983  /* Update pg_class.reloftype */
11984  relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
11985  classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
11986  if (!HeapTupleIsValid(classtuple))
11987  elog(ERROR, "cache lookup failed for relation %u", relid);
11988  ((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
11989  CatalogTupleUpdate(relationRelation, &classtuple->t_self, classtuple);
11990 
11992 
11993  heap_freetuple(classtuple);
11994  heap_close(relationRelation, RowExclusiveLock);
11995 
11996  ReleaseSysCache(typetuple);
11997 
11998  return typeobj;
11999 }
#define Anum_pg_inherits_inhrelid
Definition: pg_inherits.h:50
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:247
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1579
#define RelationGetDescr(relation)
Definition: rel.h:428
static void drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid, DependencyType deptype)
Definition: tablecmds.c:11815
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
#define RelationRelationId
Definition: pg_class.h:29
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:575
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:114
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
#define TypeRelationId
Definition: pg_type.h:34
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:328
int natts
Definition: tupdesc.h:73
#define NAMEDATALEN
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:416
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
void check_of_type(HeapTuple typetuple)
Definition: tablecmds.c:5096
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:436
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void DecrTupleDescRefCount(TupleDesc tupdesc)
Definition: tupdesc.c:319
#define InheritsRelidSeqnoIndexId
Definition: indexing.h:167
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define InheritsRelationId
Definition: pg_inherits.h:29
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:493
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:416
#define BTEqualStrategyNumber
Definition: stratnum.h:31
static ObjectAddress ATExecAlterColumnGenericOptions ( Relation  rel,
const char *  colName,
List options,
LOCKMODE  lockmode 
)
static

Definition at line 9473 of file tablecmds.c.

References AccessShareLock, Anum_pg_attribute_attfdwoptions, ATTNAME, AttributeRelationId, CatalogTupleUpdate(), DatumGetPointer, ereport, errcode(), errmsg(), ERROR, ForeignServer::fdwid, ForeignDataWrapper::fdwvalidator, FOREIGNTABLEREL, ForeignTableRelationId, GetForeignDataWrapper(), GetForeignServer(), GETSTRUCT, heap_close, heap_freetuple(), heap_modify_tuple(), heap_open(), HeapTupleIsValid, InvalidObjectAddress, InvokeObjectPostAlterHook, Natts_pg_attribute, NIL, ObjectAddressSubSet, PointerGetDatum, PointerIsValid, RelationData::rd_id, RelationGetDescr, RelationGetRelationName, RelationGetRelid, RelationRelationId, ReleaseSysCache(), RowExclusiveLock, SearchSysCache1(), SearchSysCacheAttName(), SysCacheGetAttr(), HeapTupleData::t_self, and transformGenericOptions().

Referenced by ATExecCmd().

9477 {
9478  Relation ftrel;
9479  Relation attrel;
9480  ForeignServer *server;
9481  ForeignDataWrapper *fdw;
9482  HeapTuple tuple;
9483  HeapTuple newtuple;
9484  bool isnull;
9485  Datum repl_val[Natts_pg_attribute];
9486  bool repl_null[Natts_pg_attribute];
9487  bool repl_repl[Natts_pg_attribute];
9488  Datum datum;
9489  Form_pg_foreign_table fttableform;
9490  Form_pg_attribute atttableform;
9491  AttrNumber attnum;
9492  ObjectAddress address;
9493 
9494  if (options == NIL)
9495  return InvalidObjectAddress;
9496 
9497  /* First, determine FDW validator associated to the foreign table. */
9499  tuple = SearchSysCache1(FOREIGNTABLEREL, rel->rd_id);
9500  if (!HeapTupleIsValid(tuple))
9501  ereport(ERROR,
9502  (errcode(ERRCODE_UNDEFINED_OBJECT),
9503  errmsg("foreign table \"%s\" does not exist",
9504  RelationGetRelationName(rel))));
9505  fttableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
9506  server = GetForeignServer(fttableform->ftserver);
9507  fdw = GetForeignDataWrapper(server->fdwid);
9508 
9509  heap_close(ftrel, AccessShareLock);
9510  ReleaseSysCache(tuple);
9511 
9513  tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9514  if (!HeapTupleIsValid(tuple))
9515  ereport(ERROR,
9516  (errcode(ERRCODE_UNDEFINED_COLUMN),
9517  errmsg("column \"%s\" of relation \"%s\" does not exist",
9518  colName, RelationGetRelationName(rel))));
9519 
9520  /* Prevent them from altering a system attribute */
9521  atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
9522  attnum = atttableform->attnum;
9523  if (attnum <= 0)
9524  ereport(ERROR,
9525  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9526  errmsg("cannot alter system column \"%s\"", colName)));
9527 
9528 
9529  /* Initialize buffers for new tuple values */
9530  memset(repl_val, 0, sizeof(repl_val));
9531  memset(repl_null, false, sizeof(repl_null));
9532  memset(repl_repl, false, sizeof(repl_repl));
9533 
9534  /* Extract the current options */
9535  datum = SysCacheGetAttr(ATTNAME,
9536  tuple,
9538  &isnull);
9539  if (isnull)
9540  datum = PointerGetDatum(NULL);
9541 
9542  /* Transform the options */
9544  datum,
9545  options,
9546  fdw->fdwvalidator);
9547 
9548  if (PointerIsValid(DatumGetPointer(datum)))
9549  repl_val[Anum_pg_attribute_attfdwoptions - 1] = datum;
9550  else
9551  repl_null[Anum_pg_attribute_attfdwoptions - 1] = true;
9552 
9553  repl_repl[Anum_pg_attribute_attfdwoptions - 1] = true;
9554 
9555  /* Everything looks good - update the tuple */
9556 
9557  newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrel),
9558  repl_val, repl_null, repl_repl);
9559 
9560  CatalogTupleUpdate(attrel, &newtuple->t_self, newtuple);
9561 
9563  RelationGetRelid(rel),
9564  atttableform->attnum);
9566  RelationGetRelid(rel), attnum);
9567 
9568  ReleaseSysCache(tuple);
9569 
9570  heap_close(attrel, RowExclusiveLock);
9571 
9572  heap_freetuple(newtuple);
9573 
9574  return address;
9575 }
#define NIL
Definition: pg_list.h:69
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define RelationGetDescr(relation)
Definition: rel.h:428
Datum transformGenericOptions(Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
Definition: foreigncmds.c:109
#define PointerGetDatum(X)
Definition: postgres.h:562
#define RelationRelationId
Definition: pg_class.h:29
#define AccessShareLock
Definition: lockdefs.h:36
#define AttributeRelationId
Definition: pg_attribute.h:33
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
ForeignDataWrapper * GetForeignDataWrapper(Oid fdwid)
Definition: foreign.c:35
FormData_pg_foreign_table * Form_pg_foreign_table
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:436
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
Oid rd_id
Definition: rel.h:116
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
ForeignServer * GetForeignServer(Oid serverid)
Definition: foreign.c:93
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
HeapTuple SearchSysCacheAttName(Oid relid, const char *attname)
Definition: syscache.c:1248
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
#define Anum_pg_attribute_attfdwoptions
Definition: pg_attribute.h:216
#define DatumGetPointer(X)
Definition: postgres.h:555
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define ForeignTableRelationId
#define Natts_pg_attribute
Definition: pg_attribute.h:194
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:794
#define PointerIsValid(pointer)
Definition: c.h:520
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:416
static ObjectAddress ATExecAlterColumnType ( AlteredTableInfo tab,
Relation  rel,
AlterTableCmd cmd,
LOCKMODE  lockmode 
)
static

Definition at line 9051 of file tablecmds.c.

References add_column_collation_dependency(), add_column_datatype_dependency(), Anum_pg_depend_classid, Anum_pg_depend_objid, Anum_pg_depend_objsubid, Anum_pg_depend_refclassid, Anum_pg_depend_refobjid, Anum_pg_depend_refobjsubid, Assert, AttributeRelationId, BTEqualStrategyNumber, build_column_default(), CatalogTupleDelete(), CatalogTupleUpdate(), AlteredTableInfo::changedConstraintDefs, AlteredTableInfo::changedConstraintOids, AlteredTableInfo::changedIndexDefs, AlteredTableInfo::changedIndexOids, ObjectAddress::classId, COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, CollationRelationId, CommandCounterIncrement(), AlterTableCmd::def, DependDependerIndexId, DEPENDENCY_NORMAL, DEPENDENCY_PIN, DependReferenceIndexId, DependRelationId, DROP_RESTRICT, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, exprType(), format_type_be(), get_rel_relkind(), GetColumnDefCollation(), getObjectClass(), getObjectDescription(), GETSTRUCT, heap_close, heap_freetuple(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, Int32GetDatum, InvokeObjectPostAlterHook, lappend(), lappend_oid(), lcons(), lcons_oid(), list_length(), list_member_oid(), AlterTableCmd::name, ObjectAddressSubSet, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, OCLASS_AM, OCLASS_AMOP, OCLASS_AMPROC, OCLASS_CAST, OCLASS_CLASS, OCLASS_COLLATION, OCLASS_CONSTRAINT, OCLASS_CONVERSION, OCLASS_DATABASE, OCLASS_DEFACL, OCLASS_DEFAULT, OCLASS_EVENT_TRIGGER, OCLASS_EXTENSION, OCLASS_FDW, OCLASS_FOREIGN_SERVER, OCLASS_LANGUAGE, OCLASS_LARGEOBJECT, OCLASS_OPCLASS, OCLASS_OPERATOR, OCLASS_OPFAMILY, OCLASS_POLICY, OCLASS_PROC, OCLASS_PUBLICATION, OCLASS_PUBLICATION_REL, OCLASS_REWRITE, OCLASS_ROLE, OCLASS_SCHEMA, OCLASS_STATISTIC_EXT, OCLASS_SUBSCRIPTION, OCLASS_TBLSPACE, OCLASS_TRANSFORM, OCLASS_TRIGGER, OCLASS_TSCONFIG, OCLASS_TSDICT, OCLASS_TSPARSER, OCLASS_TSTEMPLATE, OCLASS_TYPE, OCLASS_USER_MAPPING, AlteredTableInfo::oldDesc, pg_get_constraintdef_command(), pg_get_indexdef_string(), RelationGetRelationName, RelationGetRelid, RelationRelationId, ReleaseSysCache(), RELKIND_INDEX, RELKIND_SEQUENCE, RemoveAttrDefault(), RemoveStatistics(), RowExclusiveLock, ScanKeyInit(), SearchSysCacheCopyAttName(), StoreAttrDefault(), strip_implicit_coercions(), systable_beginscan(), systable_endscan(), systable_getnext(), TupleDescAttr, ColumnDef::typeName, typenameType(), TypeRelationId, and UpdateStatisticsForTypeChange().

Referenced by ATExecCmd().

9053 {
9054  char *colName = cmd->name;
9055  ColumnDef *def = (ColumnDef *) cmd->def;
9056  TypeName *typeName = def->typeName;
9057  HeapTuple heapTup;
9058  Form_pg_attribute attTup,
9059  attOldTup;
9060  AttrNumber attnum;
9061  HeapTuple typeTuple;
9062  Form_pg_type tform;
9063  Oid targettype;
9064  int32 targettypmod;
9065  Oid targetcollid;
9066  Node *defaultexpr;
9067  Relation attrelation;
9068  Relation depRel;
9069  ScanKeyData key[3];
9070  SysScanDesc scan;
9071  HeapTuple depTup;
9072  ObjectAddress address;
9073 
9075 
9076  /* Look up the target column */
9077  heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
9078  if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
9079  ereport(ERROR,
9080  (errcode(ERRCODE_UNDEFINED_COLUMN),
9081  errmsg("column \"%s\" of relation \"%s\" does not exist",
9082  colName, RelationGetRelationName(rel))));
9083  attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
9084  attnum = attTup->attnum;
9085  attOldTup = TupleDescAttr(tab->oldDesc, attnum - 1);
9086 
9087  /* Check for multiple ALTER TYPE on same column --- can't cope */
9088  if (attTup->atttypid != attOldTup->atttypid ||
9089  attTup->atttypmod != attOldTup->atttypmod)
9090  ereport(ERROR,
9091  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9092  errmsg("cannot alter type of column \"%s\" twice",
9093  colName)));
9094 
9095  /* Look up the target type (should not fail, since prep found it) */
9096  typeTuple = typenameType(NULL, typeName, &targettypmod);
9097  tform = (Form_pg_type) GETSTRUCT(typeTuple);
9098  targettype = HeapTupleGetOid(typeTuple);
9099  /* And the collation */
9100  targetcollid = GetColumnDefCollation(NULL, def, targettype);
9101 
9102  /*
9103  * If there is a default expression for the column, get it and ensure we
9104  * can coerce it to the new datatype. (We must do this before changing
9105  * the column type, because build_column_default itself will try to
9106  * coerce, and will not issue the error message we want if it fails.)
9107  *
9108  * We remove any implicit coercion steps at the top level of the old
9109  * default expression; this has been agreed to satisfy the principle of
9110  * least surprise. (The conversion to the new column type should act like
9111  * it started from what the user sees as the stored expression, and the
9112  * implicit coercions aren't going to be shown.)
9113  */
9114  if (attTup->atthasdef)
9115  {
9116  defaultexpr = build_column_default(rel, attnum);
9117  Assert(defaultexpr);
9118  defaultexpr = strip_implicit_coercions(defaultexpr);
9119  defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
9120  defaultexpr, exprType(defaultexpr),
9121  targettype, targettypmod,
9124  -1);
9125  if (defaultexpr == NULL)
9126  ereport(ERROR,
9127  (errcode(ERRCODE_DATATYPE_MISMATCH),
9128  errmsg("default for column \"%s\" cannot be cast automatically to type %s",
9129  colName, format_type_be(targettype))));
9130  }
9131  else
9132  defaultexpr = NULL;
9133 
9134  /*
9135  * Find everything that depends on the column (constraints, indexes, etc),
9136  * and record enough information to let us recreate the objects.
9137  *
9138  * The actual recreation does not happen here, but only after we have
9139  * performed all the individual ALTER TYPE operations. We have to save
9140  * the info before executing ALTER TYPE, though, else the deparser will
9141  * get confused.
9142  *
9143  * There could be multiple entries for the same object, so we must check
9144  * to ensure we process each one only once. Note: we assume that an index
9145  * that implements a constraint will not show a direct dependency on the
9146  * column.
9147  */
9149 
9150  ScanKeyInit(&key[0],
9152  BTEqualStrategyNumber, F_OIDEQ,
9154  ScanKeyInit(&key[1],
9156  BTEqualStrategyNumber, F_OIDEQ,
9158  ScanKeyInit(&key[2],
9160  BTEqualStrategyNumber, F_INT4EQ,
9161  Int32GetDatum((int32) attnum));
9162 
9163  scan = systable_beginscan(depRel, DependReferenceIndexId, true,
9164  NULL, 3, key);
9165 
9166  while (HeapTupleIsValid(depTup = systable_getnext(scan)))
9167  {
9168  Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
9169  ObjectAddress foundObject;
9170 
9171  /* We don't expect any PIN dependencies on columns */
9172  if (foundDep->deptype == DEPENDENCY_PIN)
9173  elog(ERROR, "cannot alter type of a pinned column");
9174 
9175  foundObject.classId = foundDep->classid;
9176  foundObject.objectId = foundDep->objid;
9177  foundObject.objectSubId = foundDep->objsubid;
9178 
9179  switch (getObjectClass(&foundObject))
9180  {
9181  case OCLASS_CLASS:
9182  {
9183  char relKind = get_rel_relkind(foundObject.objectId);
9184 
9185  if (relKind == RELKIND_INDEX)
9186  {
9187  Assert(foundObject.objectSubId == 0);
9188  if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
9189  {
9191  foundObject.objectId);
9193  pg_get_indexdef_string(foundObject.objectId));
9194  }
9195  }
9196  else if (relKind == RELKIND_SEQUENCE)
9197  {
9198  /*
9199  * This must be a SERIAL column's sequence. We need
9200  * not do anything to it.
9201  */
9202  Assert(foundObject.objectSubId == 0);
9203  }
9204  else
9205  {
9206  /* Not expecting any other direct dependencies... */
9207  elog(ERROR, "unexpected object depending on column: %s",
9208  getObjectDescription(&foundObject));
9209  }
9210  break;
9211  }
9212 
9213  case OCLASS_CONSTRAINT:
9214  Assert(foundObject.objectSubId == 0);
9216  foundObject.objectId))
9217  {
9218  char *defstring = pg_get_constraintdef_command(foundObject.objectId);
9219 
9220  /*
9221  * Put NORMAL dependencies at the front of the list and
9222  * AUTO dependencies at the back. This makes sure that
9223  * foreign-key constraints depending on this column will
9224  * be dropped before unique or primary-key constraints of
9225  * the column; which we must have because the FK
9226  * constraints depend on the indexes belonging to the
9227  * unique constraints.
9228  */
9229  if (foundDep->deptype == DEPENDENCY_NORMAL)
9230  {
9231  tab->changedConstraintOids =
9232  lcons_oid(foundObject.objectId,
9233  tab->changedConstraintOids);
9234  tab->changedConstraintDefs =
9235  lcons(defstring,
9236  tab->changedConstraintDefs);
9237  }
9238  else
9239  {
9240  tab->changedConstraintOids =
9242  foundObject.objectId);
9243  tab->changedConstraintDefs =
9245  defstring);
9246  }
9247  }
9248  break;
9249 
9250  case OCLASS_REWRITE:
9251  /* XXX someday see if we can cope with revising views */
9252  ereport(ERROR,
9253  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9254  errmsg("cannot alter type of a column used by a view or rule"),
9255  errdetail("%s depends on column \"%s\"",
9256  getObjectDescription(&foundObject),
9257  colName)));
9258  break;
9259 
9260  case OCLASS_TRIGGER:
9261 
9262  /*
9263  * A trigger can depend on a column because the column is
9264  * specified as an update target, or because the column is
9265  * used in the trigger's WHEN condition. The first case would
9266  * not require any extra work, but the second case would
9267  * require updating the WHEN expression, which will take a
9268  * significant amount of new code. Since we can't easily tell
9269  * which case applies, we punt for both. FIXME someday.
9270  */
9271  ereport(ERROR,
9272  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9273  errmsg("cannot alter type of a column used in a trigger definition"),
9274  errdetail("%s depends on column \"%s\"",
9275  getObjectDescription(&foundObject),
9276  colName)));
9277  break;
9278 
9279  case OCLASS_POLICY:
9280 
9281  /*
9282  * A policy can depend on a column because the column is
9283  * specified in the policy's USING or WITH CHECK qual
9284  * expressions. It might be possible to rewrite and recheck
9285  * the policy expression, but punt for now. It's certainly
9286  * easy enough to remove and recreate the policy; still, FIXME
9287  * someday.
9288  */
9289  ereport(ERROR,
9290  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9291  errmsg("cannot alter type of a column used in a policy definition"),
9292  errdetail("%s depends on column \"%s\"",
9293  getObjectDescription(&foundObject),
9294  colName)));
9295  break;
9296 
9297  case OCLASS_DEFAULT:
9298 
9299  /*
9300  * Ignore the column's default expression, since we will fix
9301  * it below.
9302  */
9303  Assert(defaultexpr);
9304  break;
9305 
9306  case OCLASS_STATISTIC_EXT:
9307 
9308  /*
9309  * Give the extended-stats machinery a chance to fix anything
9310  * that this column type change would break.
9311  */
9313  RelationGetRelid(rel), attnum,
9314  attTup->atttypid, targettype);
9315  break;
9316 
9317  case OCLASS_PROC:
9318  case OCLASS_TYPE:
9319  case OCLASS_CAST:
9320  case OCLASS_COLLATION:
9321  case OCLASS_CONVERSION:
9322  case OCLASS_LANGUAGE:
9323  case OCLASS_LARGEOBJECT:
9324  case OCLASS_OPERATOR:
9325  case OCLASS_OPCLASS:
9326  case OCLASS_OPFAMILY:
9327  case OCLASS_AM:
9328  case OCLASS_AMOP:
9329  case OCLASS_AMPROC:
9330  case OCLASS_SCHEMA:
9331  case OCLASS_TSPARSER:
9332  case OCLASS_TSDICT:
9333  case OCLASS_TSTEMPLATE:
9334  case OCLASS_TSCONFIG:
9335  case OCLASS_ROLE: