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
 

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)
 
static void StoreCatalogInheritance1 (Oid relationId, Oid parentOid, int16 seqNumber, Relation inhRelation)
 
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 void ATPrepSetStatistics (Relation rel, const char *colName, Node *newValue, LOCKMODE lockmode)
 
static ObjectAddress ATExecSetStatistics (Relation rel, const char *colName, 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)
 
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 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)
 

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.

#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 282 of file tablecmds.c.

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

#define ATT_INDEX   0x0008

Definition at line 281 of file tablecmds.c.

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

#define ATT_MATVIEW   0x0004

Definition at line 280 of file tablecmds.c.

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

#define ATT_VIEW   0x0002

Definition at line 279 of file tablecmds.c.

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

Typedef Documentation

Function Documentation

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

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

5426 {
5427  ObjectAddress myself,
5428  referenced;
5429 
5430  /* We know the default collation is pinned, so don't bother recording it */
5431  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
5432  {
5433  myself.classId = RelationRelationId;
5434  myself.objectId = relid;
5435  myself.objectSubId = attnum;
5436  referenced.classId = CollationRelationId;
5437  referenced.objectId = collid;
5438  referenced.objectSubId = 0;
5439  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
5440  }
5441 }
#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:534
#define DEFAULT_COLLATION_OID
Definition: pg_collation.h:68
#define CollationRelationId
Definition: pg_collation.h:30
static void add_column_datatype_dependency ( Oid  relid,
int32  attnum,
Oid  typid 
)
static

Definition at line 5407 of file tablecmds.c.

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

Referenced by ATExecAddColumn(), and ATExecAlterColumnType().

5408 {
5409  ObjectAddress myself,
5410  referenced;
5411 
5412  myself.classId = RelationRelationId;
5413  myself.objectId = relid;
5414  myself.objectSubId = attnum;
5415  referenced.classId = TypeRelationId;
5416  referenced.objectId = typid;
5417  referenced.objectSubId = 0;
5418  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
5419 }
#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 12243 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().

12245 {
12246  List *indexList;
12247  ListCell *l;
12248 
12249  indexList = RelationGetIndexList(rel);
12250 
12251  foreach(l, indexList)
12252  {
12253  Oid indexOid = lfirst_oid(l);
12254  ObjectAddress thisobj;
12255 
12256  thisobj.classId = RelationRelationId;
12257  thisobj.objectId = indexOid;
12258  thisobj.objectSubId = 0;
12259 
12260  /*
12261  * Note: currently, the index will not have its own dependency on the
12262  * namespace, so we don't need to do changeDependencyFor(). There's no
12263  * row type in pg_type, either.
12264  *
12265  * XXX this objsMoved test may be pointless -- surely we have a single
12266  * dependency link from a relation to each index?
12267  */
12268  if (!object_address_present(&thisobj, objsMoved))
12269  {
12270  AlterRelationNamespaceInternal(classRel, indexOid,
12271  oldNspOid, newNspOid,
12272  false, objsMoved);
12273  add_exact_object_address(&thisobj, objsMoved);
12274  }
12275  }
12276 
12277  list_free(indexList);
12278 }
#define RelationRelationId
Definition: pg_class.h:29
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2141
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2081
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:12173
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4336
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 12173 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().

12177 {
12178  HeapTuple classTup;
12179  Form_pg_class classForm;
12180  ObjectAddress thisobj;
12181  bool already_done = false;
12182 
12183  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
12184  if (!HeapTupleIsValid(classTup))
12185  elog(ERROR, "cache lookup failed for relation %u", relOid);
12186  classForm = (Form_pg_class) GETSTRUCT(classTup);
12187 
12188  Assert(classForm->relnamespace == oldNspOid);
12189 
12190  thisobj.classId = RelationRelationId;
12191  thisobj.objectId = relOid;
12192  thisobj.objectSubId = 0;
12193 
12194  /*
12195  * If the object has already been moved, don't move it again. If it's
12196  * already in the right place, don't move it, but still fire the object
12197  * access hook.
12198  */
12199  already_done = object_address_present(&thisobj, objsMoved);
12200  if (!already_done && oldNspOid != newNspOid)
12201  {
12202  /* check for duplicate name (more friendly than unique-index failure) */
12203  if (get_relname_relid(NameStr(classForm->relname),
12204  newNspOid) != InvalidOid)
12205  ereport(ERROR,
12206  (errcode(ERRCODE_DUPLICATE_TABLE),
12207  errmsg("relation \"%s\" already exists in schema \"%s\"",
12208  NameStr(classForm->relname),
12209  get_namespace_name(newNspOid))));
12210 
12211  /* classTup is a copy, so OK to scribble on */
12212  classForm->relnamespace = newNspOid;
12213 
12214  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
12215 
12216  /* Update dependency on schema if caller said so */
12217  if (hasDependEntry &&
12219  relOid,
12221  oldNspOid,
12222  newNspOid) != 1)
12223  elog(ERROR, "failed to change schema dependency for relation \"%s\"",
12224  NameStr(classForm->relname));
12225  }
12226  if (!already_done)
12227  {
12228  add_exact_object_address(&thisobj, objsMoved);
12229 
12231  }
12232 
12233  heap_freetuple(classTup);
12234 }
#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:2141
int errcode(int sqlerrcode)
Definition: elog.c:575
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2081
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#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:1651
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3006
#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:671
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:158
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:495
#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 12288 of file tablecmds.c.

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

Referenced by AlterTableNamespaceInternal().

12291 {
12292  Relation depRel;
12293  SysScanDesc scan;
12294  ScanKeyData key[2];
12295  HeapTuple tup;
12296 
12297  /*
12298  * SERIAL sequences are those having an auto dependency on one of the
12299  * table's columns (we don't care *which* column, exactly).
12300  */
12302 
12303  ScanKeyInit(&key[0],
12305  BTEqualStrategyNumber, F_OIDEQ,
12307  ScanKeyInit(&key[1],
12309  BTEqualStrategyNumber, F_OIDEQ,
12311  /* we leave refobjsubid unspecified */
12312 
12313  scan = systable_beginscan(depRel, DependReferenceIndexId, true,
12314  NULL, 2, key);
12315 
12316  while (HeapTupleIsValid(tup = systable_getnext(scan)))
12317  {
12318  Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
12319  Relation seqRel;
12320 
12321  /* skip dependencies other than auto dependencies on columns */
12322  if (depForm->refobjsubid == 0 ||
12323  depForm->classid != RelationRelationId ||
12324  depForm->objsubid != 0 ||
12325  depForm->deptype != DEPENDENCY_AUTO)
12326  continue;
12327 
12328  /* Use relation_open just in case it's an index */
12329  seqRel = relation_open(depForm->objid, lockmode);
12330 
12331  /* skip non-sequence relations */
12332  if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
12333  {
12334  /* No need to keep the lock */
12335  relation_close(seqRel, lockmode);
12336  continue;
12337  }
12338 
12339  /* Fix the pg_class and pg_depend entries */
12340  AlterRelationNamespaceInternal(classRel, depForm->objid,
12341  oldNspOid, newNspOid,
12342  true, objsMoved);
12343 
12344  /*
12345  * Sequences have entries in pg_type. We need to be careful to move
12346  * them to the new namespace, too.
12347  */
12349  newNspOid, false, false, objsMoved);
12350 
12351  /* Now we can close it. Keep the lock till end of transaction. */
12352  relation_close(seqRel, NoLock);
12353  }
12354 
12355  systable_endscan(scan);
12356 
12358 }
#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:493
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define RelationGetForm(relation)
Definition: rel.h:407
#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:3491
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1263
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:322
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:410
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#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:1287
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:12173
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:1117
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
#define RelationGetRelid(relation)
Definition: rel.h:413
#define BTEqualStrategyNumber
Definition: stratnum.h:31
void AlterTable ( Oid  relid,
LOCKMODE  lockmode,
AlterTableStmt stmt 
)

Definition at line 3029 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3030 {
3031  Relation rel;
3032 
3033  /* Caller is required to provide an adequate lock. */
3034  rel = relation_open(relid, NoLock);
3035 
3036  CheckTableNotInUse(rel, "ALTER TABLE");
3037 
3038  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode);
3039 }
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
Definition: tablecmds.c:3344
#define NoLock
Definition: lockdefs.h:34
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:2950
bool inh
Definition: primnodes.h:68
RangeVar * relation
Definition: parsenodes.h:1601
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1117
LOCKMODE AlterTableGetLockLevel ( List cmds)

Definition at line 3098 of file tablecmds.c.

References AccessExclusiveLock, AlterTableGetRelOptionsLockLevel(), AT_AddColumn, AT_AddColumnToView, AT_AddConstraint, AT_AddConstraintRecurse, 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_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_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().

3099 {
3100  /*
3101  * This only works if we read catalog tables using MVCC snapshots.
3102  */
3103  ListCell *lcmd;
3105 
3106  foreach(lcmd, cmds)
3107  {
3108  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3109  LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
3110 
3111  switch (cmd->subtype)
3112  {
3113  /*
3114  * These subcommands rewrite the heap, so require full locks.
3115  */
3116  case AT_AddColumn: /* may rewrite heap, in some cases and visible
3117  * to SELECT */
3118  case AT_SetTableSpace: /* must rewrite heap */
3119  case AT_AlterColumnType: /* must rewrite heap */
3120  case AT_AddOids: /* must rewrite heap */
3121  cmd_lockmode = AccessExclusiveLock;
3122  break;
3123 
3124  /*
3125  * These subcommands may require addition of toast tables. If
3126  * we add a toast table to a table currently being scanned, we
3127  * might miss data added to the new toast table by concurrent
3128  * insert transactions.
3129  */
3130  case AT_SetStorage:/* may add toast tables, see
3131  * ATRewriteCatalogs() */
3132  cmd_lockmode = AccessExclusiveLock;
3133  break;
3134 
3135  /*
3136  * Removing constraints can affect SELECTs that have been
3137  * optimised assuming the constraint holds true.
3138  */
3139  case AT_DropConstraint: /* as DROP INDEX */
3140  case AT_DropNotNull: /* may change some SQL plans */
3141  cmd_lockmode = AccessExclusiveLock;
3142  break;
3143 
3144  /*
3145  * Subcommands that may be visible to concurrent SELECTs
3146  */
3147  case AT_DropColumn: /* change visible to SELECT */
3148  case AT_AddColumnToView: /* CREATE VIEW */
3149  case AT_DropOids: /* calls AT_DropColumn */
3150  case AT_EnableAlwaysRule: /* may change SELECT rules */
3151  case AT_EnableReplicaRule: /* may change SELECT rules */
3152  case AT_EnableRule: /* may change SELECT rules */
3153  case AT_DisableRule: /* may change SELECT rules */
3154  cmd_lockmode = AccessExclusiveLock;
3155  break;
3156 
3157  /*
3158  * Changing owner may remove implicit SELECT privileges
3159  */
3160  case AT_ChangeOwner: /* change visible to SELECT */
3161  cmd_lockmode = AccessExclusiveLock;
3162  break;
3163 
3164  /*
3165  * Changing foreign table options may affect optimisation.
3166  */
3167  case AT_GenericOptions:
3169  cmd_lockmode = AccessExclusiveLock;
3170  break;
3171 
3172  /*
3173  * These subcommands affect write operations only.
3174  */
3175  case AT_EnableTrig:
3176  case AT_EnableAlwaysTrig:
3177  case AT_EnableReplicaTrig:
3178  case AT_EnableTrigAll:
3179  case AT_EnableTrigUser:
3180  case AT_DisableTrig:
3181  case AT_DisableTrigAll:
3182  case AT_DisableTrigUser:
3183  cmd_lockmode = ShareRowExclusiveLock;
3184  break;
3185 
3186  /*
3187  * These subcommands affect write operations only. XXX
3188  * Theoretically, these could be ShareRowExclusiveLock.
3189  */
3190  case AT_ColumnDefault:
3191  case AT_AlterConstraint:
3192  case AT_AddIndex: /* from ADD CONSTRAINT */
3193  case AT_AddIndexConstraint:
3194  case AT_ReplicaIdentity:
3195  case AT_SetNotNull:
3196  case AT_EnableRowSecurity:
3197  case AT_DisableRowSecurity:
3198  case AT_ForceRowSecurity:
3199  case AT_NoForceRowSecurity:
3200  cmd_lockmode = AccessExclusiveLock;
3201  break;
3202 
3203  case AT_AddConstraint:
3204  case AT_ProcessedConstraint: /* becomes AT_AddConstraint */
3205  case AT_AddConstraintRecurse: /* becomes AT_AddConstraint */
3206  case AT_ReAddConstraint: /* becomes AT_AddConstraint */
3207  if (IsA(cmd->def, Constraint))
3208  {
3209  Constraint *con = (Constraint *) cmd->def;
3210 
3211  switch (con->contype)
3212  {
3213  case CONSTR_EXCLUSION:
3214  case CONSTR_PRIMARY:
3215  case CONSTR_UNIQUE:
3216 
3217  /*
3218  * Cases essentially the same as CREATE INDEX. We
3219  * could reduce the lock strength to ShareLock if
3220  * we can work out how to allow concurrent catalog
3221  * updates. XXX Might be set down to
3222  * ShareRowExclusiveLock but requires further
3223  * analysis.
3224  */
3225  cmd_lockmode = AccessExclusiveLock;
3226  break;
3227  case CONSTR_FOREIGN:
3228 
3229  /*
3230  * We add triggers to both tables when we add a
3231  * Foreign Key, so the lock level must be at least
3232  * as strong as CREATE TRIGGER.
3233  */
3234  cmd_lockmode = ShareRowExclusiveLock;
3235  break;
3236 
3237  default:
3238  cmd_lockmode = AccessExclusiveLock;
3239  }
3240  }
3241  break;
3242 
3243  /*
3244  * These subcommands affect inheritance behaviour. Queries
3245  * started before us will continue to see the old inheritance
3246  * behaviour, while queries started after we commit will see
3247  * new behaviour. No need to prevent reads or writes to the
3248  * subtable while we hook it up though. Changing the TupDesc
3249  * may be a problem, so keep highest lock.
3250  */
3251  case AT_AddInherit:
3252  case AT_DropInherit:
3253  cmd_lockmode = AccessExclusiveLock;
3254  break;
3255 
3256  /*
3257  * These subcommands affect implicit row type conversion. They
3258  * have affects similar to CREATE/DROP CAST on queries. don't
3259  * provide for invalidating parse trees as a result of such
3260  * changes, so we keep these at AccessExclusiveLock.
3261  */
3262  case AT_AddOf:
3263  case AT_DropOf:
3264  cmd_lockmode = AccessExclusiveLock;
3265  break;
3266 
3267  /*
3268  * Only used by CREATE OR REPLACE VIEW which must conflict
3269  * with an SELECTs currently using the view.
3270  */
3271  case AT_ReplaceRelOptions:
3272  cmd_lockmode = AccessExclusiveLock;
3273  break;
3274 
3275  /*
3276  * These subcommands affect general strategies for performance
3277  * and maintenance, though don't change the semantic results
3278  * from normal data reads and writes. Delaying an ALTER TABLE
3279  * behind currently active writes only delays the point where
3280  * the new strategy begins to take effect, so there is no
3281  * benefit in waiting. In this case the minimum restriction
3282  * applies: we don't currently allow concurrent catalog
3283  * updates.
3284  */
3285  case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
3286  case AT_ClusterOn: /* Uses MVCC in getIndexes() */
3287  case AT_DropCluster: /* Uses MVCC in getIndexes() */
3288  case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
3289  case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
3290  cmd_lockmode = ShareUpdateExclusiveLock;
3291  break;
3292 
3293  case AT_SetLogged:
3294  case AT_SetUnLogged:
3295  cmd_lockmode = AccessExclusiveLock;
3296  break;
3297 
3298  case AT_ValidateConstraint: /* Uses MVCC in
3299  * getConstraints() */
3300  cmd_lockmode = ShareUpdateExclusiveLock;
3301  break;
3302 
3303  /*
3304  * Rel options are more complex than first appears. Options
3305  * are set here for tables, views and indexes; for historical
3306  * reasons these can all be used with ALTER TABLE, so we can't
3307  * decide between them using the basic grammar.
3308  */
3309  case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
3310  * getTables() */
3311  case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
3312  * getTables() */
3313  cmd_lockmode = AlterTableGetRelOptionsLockLevel((List *) cmd->def);
3314  break;
3315 
3316  case AT_AttachPartition:
3317  case AT_DetachPartition:
3318  cmd_lockmode = AccessExclusiveLock;
3319  break;
3320 
3321  default: /* oops */
3322  elog(ERROR, "unrecognized alter table type: %d",
3323  (int) cmd->subtype);
3324  break;
3325  }
3326 
3327  /*
3328  * Take the greatest lockmode from any subcommand
3329  */
3330  if (cmd_lockmode > lockmode)
3331  lockmode = cmd_lockmode;
3332  }
3333 
3334  return lockmode;
3335 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
int LOCKMODE
Definition: lockdefs.h:26
AlterTableType subtype
Definition: parsenodes.h:1685
#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:1485
#define AccessExclusiveLock
Definition: lockdefs.h:46
ConstrType contype
Definition: parsenodes.h:1971
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
void AlterTableInternal ( Oid  relid,
List cmds,
bool  recurse 
)

Definition at line 3053 of file tablecmds.c.

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

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

3054 {
3055  Relation rel;
3056  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
3057 
3058  rel = relation_open(relid, lockmode);
3059 
3061 
3062  ATController(NULL, rel, cmds, recurse, lockmode);
3063 }
int LOCKMODE
Definition: lockdefs.h:26
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
Definition: tablecmds.c:3344
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:3098
#define NULL
Definition: c.h:226
void EventTriggerAlterTableRelid(Oid objectId)
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1117
Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 2979 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

2980 {
2981  return RangeVarGetRelidExtended(stmt->relation, lockmode, stmt->missing_ok, false,
2983  (void *) stmt);
2984 }
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:217
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:12650
RangeVar * relation
Definition: parsenodes.h:1601
Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

Definition at line 10275 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, NULL, 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().

10276 {
10277  List *relations = NIL;
10278  ListCell *l;
10279  ScanKeyData key[1];
10280  Relation rel;
10281  HeapScanDesc scan;
10282  HeapTuple tuple;
10283  Oid orig_tablespaceoid;
10284  Oid new_tablespaceoid;
10285  List *role_oids = roleSpecsToIds(stmt->roles);
10286 
10287  /* Ensure we were not asked to move something we can't */
10288  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
10289  stmt->objtype != OBJECT_MATVIEW)
10290  ereport(ERROR,
10291  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
10292  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
10293 
10294  /* Get the orig and new tablespace OIDs */
10295  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
10296  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
10297 
10298  /* Can't move shared relations in to or out of pg_global */
10299  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
10300  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
10301  new_tablespaceoid == GLOBALTABLESPACE_OID)
10302  ereport(ERROR,
10303  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
10304  errmsg("cannot move relations in to or out of pg_global tablespace")));
10305 
10306  /*
10307  * Must have CREATE rights on the new tablespace, unless it is the
10308  * database default tablespace (which all users implicitly have CREATE
10309  * rights on).
10310  */
10311  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
10312  {
10313  AclResult aclresult;
10314 
10315  aclresult = pg_tablespace_aclcheck(new_tablespaceoid, GetUserId(),
10316  ACL_CREATE);
10317  if (aclresult != ACLCHECK_OK)
10319  get_tablespace_name(new_tablespaceoid));
10320  }
10321 
10322  /*
10323  * Now that the checks are done, check if we should set either to
10324  * InvalidOid because it is our database's default tablespace.
10325  */
10326  if (orig_tablespaceoid == MyDatabaseTableSpace)
10327  orig_tablespaceoid = InvalidOid;
10328 
10329  if (new_tablespaceoid == MyDatabaseTableSpace)
10330  new_tablespaceoid = InvalidOid;
10331 
10332  /* no-op */
10333  if (orig_tablespaceoid == new_tablespaceoid)
10334  return new_tablespaceoid;
10335 
10336  /*
10337  * Walk the list of objects in the tablespace and move them. This will
10338  * only find objects in our database, of course.
10339  */
10340  ScanKeyInit(&key[0],
10342  BTEqualStrategyNumber, F_OIDEQ,
10343  ObjectIdGetDatum(orig_tablespaceoid));
10344 
10346  scan = heap_beginscan_catalog(rel, 1, key);
10347  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
10348  {
10349  Oid relOid = HeapTupleGetOid(tuple);
10350  Form_pg_class relForm;
10351 
10352  relForm = (Form_pg_class) GETSTRUCT(tuple);
10353 
10354  /*
10355  * Do not move objects in pg_catalog as part of this, if an admin
10356  * really wishes to do so, they can issue the individual ALTER
10357  * commands directly.
10358  *
10359  * Also, explicitly avoid any shared tables, temp tables, or TOAST
10360  * (TOAST will be moved with the main table).
10361  */
10362  if (IsSystemNamespace(relForm->relnamespace) || relForm->relisshared ||
10363  isAnyTempNamespace(relForm->relnamespace) ||
10364  relForm->relnamespace == PG_TOAST_NAMESPACE)
10365  continue;
10366 
10367  /* Only move the object type requested */
10368  if ((stmt->objtype == OBJECT_TABLE &&
10369  relForm->relkind != RELKIND_RELATION &&
10370  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
10371  (stmt->objtype == OBJECT_INDEX &&
10372  relForm->relkind != RELKIND_INDEX) ||
10373  (stmt->objtype == OBJECT_MATVIEW &&
10374  relForm->relkind != RELKIND_MATVIEW))
10375  continue;
10376 
10377  /* Check if we are only moving objects owned by certain roles */
10378  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
10379  continue;
10380 
10381  /*
10382  * Handle permissions-checking here since we are locking the tables
10383  * and also to avoid doing a bunch of work only to fail part-way. Note
10384  * that permissions will also be checked by AlterTableInternal().
10385  *
10386  * Caller must be considered an owner on the table to move it.
10387  */
10388  if (!pg_class_ownercheck(relOid, GetUserId()))
10390  NameStr(relForm->relname));
10391 
10392  if (stmt->nowait &&
10394  ereport(ERROR,
10395  (errcode(ERRCODE_OBJECT_IN_USE),
10396  errmsg("aborting because lock on relation \"%s.%s\" is not available",
10397  get_namespace_name(relForm->relnamespace),
10398  NameStr(relForm->relname))));
10399  else
10401 
10402  /* Add to our list of objects to move */
10403  relations = lappend_oid(relations, relOid);
10404  }
10405 
10406  heap_endscan(scan);
10408 
10409  if (relations == NIL)
10410  ereport(NOTICE,
10411  (errcode(ERRCODE_NO_DATA_FOUND),
10412  errmsg("no matching relations in tablespace \"%s\" found",
10413  orig_tablespaceoid == InvalidOid ? "(database default)" :
10414  get_tablespace_name(orig_tablespaceoid))));
10415 
10416  /* Everything is locked, loop through and move all of the relations. */
10417  foreach(l, relations)
10418  {
10419  List *cmds = NIL;
10421 
10422  cmd->subtype = AT_SetTableSpace;
10423  cmd->name = stmt->new_tablespacename;
10424 
10425  cmds = lappend(cmds, cmd);
10426 
10428  /* OID is set by AlterTableInternal */
10429  AlterTableInternal(lfirst_oid(l), cmds, false);
10431  }
10432 
10433  return new_tablespaceoid;
10434 }
#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:1381
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4471
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1581
Oid GetUserId(void)
Definition: miscinit.c:283
#define RelationRelationId
Definition: pg_class.h:29
#define Anum_pg_class_reltablespace
Definition: pg_class.h:110
#define RELKIND_MATVIEW
Definition: pg_class.h:167
#define AccessShareLock
Definition: lockdefs.h:36
#define GLOBALTABLESPACE_OID
Definition: pg_tablespace.h:64
Definition: nodes.h:508
int errcode(int sqlerrcode)
Definition: elog.c:575
AlterTableType subtype
Definition: parsenodes.h:1685
#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:534
Oid MyDatabaseTableSpace
Definition: globals.c:78
void EventTriggerAlterTableStart(Node *parsetree)
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:75
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3006
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3378
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1402
#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:170
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1781
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
bool IsSystemNamespace(Oid namespaceId)
Definition: catalog.c:162
#define InvalidOid
Definition: postgres_ext.h:36
#define NOTICE
Definition: elog.h:37
#define makeNode(_type_)
Definition: nodes.h:556
List * roleSpecsToIds(List *memberNames)
Definition: user.c:1374
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505
#define NULL
Definition: c.h:226
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4521
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:3053
#define AccessExclusiveLock
Definition: lockdefs.h:46
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1427
#define NameStr(name)
Definition: c.h:495
#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:2990
#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 12065 of file tablecmds.c.

References AccessExclusiveLock, AlterTableNamespaceInternal(), CheckSetNamespace(), ereport, errcode(), errdetail(), errmsg(), ERROR, free_object_addresses(), get_rel_name(), InvalidObjectAddress, makeRangeVar(), AlterObjectSchemaStmt::missing_ok, new_object_addresses(), AlterObjectSchemaStmt::newschema, NoLock, NOTICE, NULL, 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().

12066 {
12067  Relation rel;
12068  Oid relid;
12069  Oid oldNspOid;
12070  Oid nspOid;
12071  RangeVar *newrv;
12072  ObjectAddresses *objsMoved;
12073  ObjectAddress myself;
12074 
12076  stmt->missing_ok, false,
12078  (void *) stmt);
12079 
12080  if (!OidIsValid(relid))
12081  {
12082  ereport(NOTICE,
12083  (errmsg("relation \"%s\" does not exist, skipping",
12084  stmt->relation->relname)));
12085  return InvalidObjectAddress;
12086  }
12087 
12088  rel = relation_open(relid, NoLock);
12089 
12090  oldNspOid = RelationGetNamespace(rel);
12091 
12092  /* If it's an owned sequence, disallow moving it by itself. */
12093  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
12094  {
12095  Oid tableId;
12096  int32 colId;
12097 
12098  if (sequenceIsOwned(relid, &tableId, &colId))
12099  ereport(ERROR,
12100  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
12101  errmsg("cannot move an owned sequence into another schema"),
12102  errdetail("Sequence \"%s\" is linked to table \"%s\".",
12104  get_rel_name(tableId))));
12105  }
12106 
12107  /* Get and lock schema OID and check its permissions. */
12108  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
12110 
12111  /* common checks on switching namespaces */
12112  CheckSetNamespace(oldNspOid, nspOid);
12113 
12114  objsMoved = new_object_addresses();
12115  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
12116  free_object_addresses(objsMoved);
12117 
12118  ObjectAddressSet(myself, RelationRelationId, relid);
12119 
12120  if (oldschema)
12121  *oldschema = oldNspOid;
12122 
12123  /* close rel, but keep lock until commit */
12124  relation_close(rel, NoLock);
12125 
12126  return myself;
12127 }
bool sequenceIsOwned(Oid seqId, 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:217
#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:1263
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2026
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2297
Form_pg_class rd_rel
Definition: rel.h:113
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:534
signed int int32
Definition: c.h:253
char * relname
Definition: primnodes.h:67
#define ERROR
Definition: elog.h:43
void AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:12135
#define NoLock
Definition: lockdefs.h:34
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:12650
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:433
#define ereport(elevel, rest)
Definition: elog.h:122
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition: namespace.c:2762
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:507
#define NOTICE
Definition: elog.h:37
#define NULL
Definition: c.h:226
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define AccessExclusiveLock
Definition: lockdefs.h:46
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:797
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1117
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1694
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:419
#define RelationGetNamespace(relation)
Definition: rel.h:440
void AlterTableNamespaceInternal ( Relation  rel,
Oid  oldNspOid,
Oid  nspOid,
ObjectAddresses objsMoved 
)

Definition at line 12135 of file tablecmds.c.

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

Referenced by AlterObjectNamespace_oid(), and AlterTableNamespace().

12137 {
12138  Relation classRel;
12139 
12140  Assert(objsMoved != NULL);
12141 
12142  /* OK, modify the pg_class row and pg_depend entry */
12144 
12145  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
12146  nspOid, true, objsMoved);
12147 
12148  /* Fix the table's row type too */
12149  AlterTypeNamespaceInternal(rel->rd_rel->reltype,
12150  nspOid, false, false, objsMoved);
12151 
12152  /* Fix other dependent stuff */
12153  if (rel->rd_rel->relkind == RELKIND_RELATION ||
12154  rel->rd_rel->relkind == RELKIND_MATVIEW ||
12155  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
12156  {
12157  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
12158  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
12159  objsMoved, AccessExclusiveLock);
12160  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
12161  false, objsMoved);
12162  }
12163 
12164  heap_close(classRel, RowExclusiveLock);
12165 }
#define RelationRelationId
Definition: pg_class.h:29
#define RELKIND_MATVIEW
Definition: pg_class.h:167
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:3491
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:113
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:12243
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:12288
#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:1287
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:12173
#define AccessExclusiveLock
Definition: lockdefs.h:46
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RelationGetRelid(relation)
Definition: rel.h:413
static ObjectAddress ATAddCheckConstraint ( List **  wqueue,
AlteredTableInfo tab,
Relation  rel,
Constraint constr,
bool  recurse,
bool  recursing,
bool  is_readd,
LOCKMODE  lockmode 
)
static

Definition at line 6544 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, make_ands_implicit(), CookedConstraint::name, NewConstraint::name, NIL, NoLock, NULL, ObjectAddressSet, palloc0(), NewConstraint::qual, RelationGetRelid, and CookedConstraint::skip_validation.

Referenced by ATExecAddConstraint().

6547 {
6548  List *newcons;
6549  ListCell *lcon;
6550  List *children;
6551  ListCell *child;
6553 
6554  /* At top level, permission check was done in ATPrepCmd, else do it */
6555  if (recursing)
6557 
6558  /*
6559  * Call AddRelationNewConstraints to do the work, making sure it works on
6560  * a copy of the Constraint so transformExpr can't modify the original. It
6561  * returns a list of cooked constraints.
6562  *
6563  * If the constraint ends up getting merged with a pre-existing one, it's
6564  * omitted from the returned list, which is what we want: we do not need
6565  * to do any validation work. That can only happen at child tables,
6566  * though, since we disallow merging at the top level.
6567  */
6568  newcons = AddRelationNewConstraints(rel, NIL,
6569  list_make1(copyObject(constr)),
6570  recursing | is_readd, /* allow_merge */
6571  !recursing, /* is_local */
6572  is_readd); /* is_internal */
6573 
6574  /* we don't expect more than one constraint here */
6575  Assert(list_length(newcons) <= 1);
6576 
6577  /* Add each to-be-validated constraint to Phase 3's queue */
6578  foreach(lcon, newcons)
6579  {
6580  CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
6581 
6582  if (!ccon->skip_validation)
6583  {
6584  NewConstraint *newcon;
6585 
6586  newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
6587  newcon->name = ccon->name;
6588  newcon->contype = ccon->contype;
6589  /* ExecQual wants implicit-AND format */
6590  newcon->qual = (Node *) make_ands_implicit((Expr *) ccon->expr);
6591 
6592  tab->constraints = lappend(tab->constraints, newcon);
6593  }
6594 
6595  /* Save the actually assigned name if it was defaulted */
6596  if (constr->conname == NULL)
6597  constr->conname = ccon->name;
6598 
6599  ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
6600  }
6601 
6602  /* At this point we must have a locked-down name to use */
6603  Assert(constr->conname != NULL);
6604 
6605  /* Advance command counter in case same table is visited multiple times */
6607 
6608  /*
6609  * If the constraint got merged with an existing constraint, we're done.
6610  * We mustn't recurse to child tables in this case, because they've
6611  * already got the constraint, and visiting them again would lead to an
6612  * incorrect value for coninhcount.
6613  */
6614  if (newcons == NIL)
6615  return address;
6616 
6617  /*
6618  * If adding a NO INHERIT constraint, no need to find our children.
6619  */
6620  if (constr->is_no_inherit)
6621  return address;
6622 
6623  /*
6624  * Propagate to children as appropriate. Unlike most other ALTER
6625  * routines, we have to do this one level of recursion at a time; we can't
6626  * use find_all_inheritors to do it in one pass.
6627  */
6628  children = find_inheritance_children(RelationGetRelid(rel), lockmode);
6629 
6630  /*
6631  * Check if ONLY was specified with ALTER TABLE. If so, allow the
6632  * constraint creation only if there are no children currently. Error out
6633  * otherwise.
6634  */
6635  if (!recurse && children != NIL)
6636  ereport(ERROR,
6637  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6638  errmsg("constraint must be added to child tables too")));
6639 
6640  foreach(child, children)
6641  {
6642  Oid childrelid = lfirst_oid(child);
6643  Relation childrel;
6644  AlteredTableInfo *childtab;
6645 
6646  /* find_inheritance_children already got lock */
6647  childrel = heap_open(childrelid, NoLock);
6648  CheckTableNotInUse(childrel, "ALTER TABLE");
6649 
6650  /* Find or create work queue entry for this table */
6651  childtab = ATGetQueueEntry(wqueue, childrel);
6652 
6653  /* Recurse to child */
6654  ATAddCheckConstraint(wqueue, childtab, childrel,
6655  constr, recurse, true, is_readd, lockmode);
6656 
6657  heap_close(childrel, NoLock);
6658  }
6659 
6660  return address;
6661 }
#define NIL
Definition: pg_list.h:69
char * name
Definition: tablecmds.c:182
Node * qual
Definition: tablecmds.c:187
Definition: nodes.h:508
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:6544
#define heap_close(r, l)
Definition: heapam.h:97
char * conname
Definition: parsenodes.h:1974
unsigned int Oid
Definition: postgres_ext.h:31
#define ATT_TABLE
Definition: tablecmds.c:278
List * constraints
Definition: tablecmds.c:163
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
#define list_make1(x1)
Definition: pg_list.h:133
List * make_ands_implicit(Expr *clause)
Definition: clauses.c:377
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
static AlteredTableInfo * ATGetQueueEntry(List **wqueue, Relation rel)
Definition: tablecmds.c:4547
bool skip_validation
Definition: heap.h:35
ConstrType contype
Definition: heap.h:30
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:2950
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
ConstrType contype
Definition: tablecmds.c:183
void * palloc0(Size size)
Definition: mcxt.c:920
void CommandCounterIncrement(void)
Definition: xact.c:921
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
bool is_no_inherit
Definition: parsenodes.h:1980
List * find_inheritance_children(Oid parentrelId, LOCKMODE lockmode)
Definition: pg_inherits.c:49
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#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:4584
#define ConstraintRelationId
Definition: pg_constraint.h:29
Definition: pg_list.h:45
#define ATT_FOREIGN_TABLE
Definition: tablecmds.c:283
char * name
Definition: heap.h:32
#define RelationGetRelid(relation)
Definition: rel.h:413
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal)
Definition: heap.c:2186
#define lfirst_oid(lc)
Definition: pg_list.h:108
static ObjectAddress ATAddForeignKeyConstraint ( AlteredTableInfo tab,
Relation  rel,
Constraint fkconstraint,
LOCKMODE  lockmode 
)
static

Definition at line 6672 of file tablecmds.c.

References allowSystemTableMods, Assert, tupleDesc::attrs, 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, NULL, 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(), and transformFkeyGetPrimaryKey().

Referenced by ATExecAddConstraint().

6674 {
6675  Relation pkrel;
6676  int16 pkattnum[INDEX_MAX_KEYS];
6677  int16 fkattnum[INDEX_MAX_KEYS];
6678  Oid pktypoid[INDEX_MAX_KEYS];
6679  Oid fktypoid[INDEX_MAX_KEYS];
6680  Oid opclasses[INDEX_MAX_KEYS];
6681  Oid pfeqoperators[INDEX_MAX_KEYS];
6682  Oid ppeqoperators[INDEX_MAX_KEYS];
6683  Oid ffeqoperators[INDEX_MAX_KEYS];
6684  int i;
6685  int numfks,
6686  numpks;
6687  Oid indexOid;
6688  Oid constrOid;
6689  bool old_check_ok;
6690  ObjectAddress address;
6691  ListCell *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
6692 
6693  /*
6694  * Grab ShareRowExclusiveLock on the pk table, so that someone doesn't
6695  * delete rows out from under us.
6696  */
6697  if (OidIsValid(fkconstraint->old_pktable_oid))
6698  pkrel = heap_open(fkconstraint->old_pktable_oid, ShareRowExclusiveLock);
6699  else
6700  pkrel = heap_openrv(fkconstraint->pktable, ShareRowExclusiveLock);
6701 
6702  /*
6703  * Validity checks (permission checks wait till we have the column
6704  * numbers)
6705  */
6706  if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
6707  ereport(ERROR,
6708  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6709  errmsg("cannot reference partitioned table \"%s\"",
6710  RelationGetRelationName(pkrel))));
6711 
6712  if (pkrel->rd_rel->relkind != RELKIND_RELATION)
6713  ereport(ERROR,
6714  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6715  errmsg("referenced relation \"%s\" is not a table",
6716  RelationGetRelationName(pkrel))));
6717 
6718  if (!allowSystemTableMods && IsSystemRelation(pkrel))
6719  ereport(ERROR,
6720  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6721  errmsg("permission denied: \"%s\" is a system catalog",
6722  RelationGetRelationName(pkrel))));
6723 
6724  /*
6725  * References from permanent or unlogged tables to temp tables, and from
6726  * permanent tables to unlogged tables, are disallowed because the
6727  * referenced data can vanish out from under us. References from temp
6728  * tables to any other table type are also disallowed, because other
6729  * backends might need to run the RI triggers on the perm table, but they
6730  * can't reliably see tuples in the local buffers of other backends.
6731  */
6732  switch (rel->rd_rel->relpersistence)
6733  {
6735  if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT)
6736  ereport(ERROR,
6737  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6738  errmsg("constraints on permanent tables may reference only permanent tables")));
6739  break;
6741  if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT
6742  && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
6743  ereport(ERROR,
6744  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6745  errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
6746  break;
6747  case RELPERSISTENCE_TEMP:
6748  if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
6749  ereport(ERROR,
6750  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6751  errmsg("constraints on temporary tables may reference only temporary tables")));
6752  if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
6753  ereport(ERROR,
6754  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6755  errmsg("constraints on temporary tables must involve temporary tables of this session")));
6756  break;
6757  }
6758 
6759  /*
6760  * Look up the referencing attributes to make sure they exist, and record
6761  * their attnums and type OIDs.
6762  */
6763  MemSet(pkattnum, 0, sizeof(pkattnum));
6764  MemSet(fkattnum, 0, sizeof(fkattnum));
6765  MemSet(pktypoid, 0, sizeof(pktypoid));
6766  MemSet(fktypoid, 0, sizeof(fktypoid));
6767  MemSet(opclasses, 0, sizeof(opclasses));
6768  MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
6769  MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
6770  MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
6771 
6773  fkconstraint->fk_attrs,
6774  fkattnum, fktypoid);
6775 
6776  /*
6777  * If the attribute list for the referenced table was omitted, lookup the
6778  * definition of the primary key and use it. Otherwise, validate the
6779  * supplied attribute list. In either case, discover the index OID and
6780  * index opclasses, and the attnums and type OIDs of the attributes.
6781  */
6782  if (fkconstraint->pk_attrs == NIL)
6783  {
6784  numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
6785  &fkconstraint->pk_attrs,
6786  pkattnum, pktypoid,
6787  opclasses);
6788  }
6789  else
6790  {
6791  numpks = transformColumnNameList(RelationGetRelid(pkrel),
6792  fkconstraint->pk_attrs,
6793  pkattnum, pktypoid);
6794  /* Look for an index matching the column list */
6795  indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
6796  opclasses);
6797  }
6798 
6799  /*
6800  * Now we can check permissions.
6801  */
6802  checkFkeyPermissions(pkrel, pkattnum, numpks);
6803  checkFkeyPermissions(rel, fkattnum, numfks);
6804 
6805  /*
6806  * Look up the equality operators to use in the constraint.
6807  *
6808  * Note that we have to be careful about the difference between the actual
6809  * PK column type and the opclass' declared input type, which might be
6810  * only binary-compatible with it. The declared opcintype is the right
6811  * thing to probe pg_amop with.
6812  */
6813  if (numfks != numpks)
6814  ereport(ERROR,
6815  (errcode(ERRCODE_INVALID_FOREIGN_KEY),
6816  errmsg("number of referencing and referenced columns for foreign key disagree")));
6817 
6818  /*
6819  * On the strength of a previous constraint, we might avoid scanning
6820  * tables to validate this one. See below.
6821  */
6822  old_check_ok = (fkconstraint->old_conpfeqop != NIL);
6823  Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
6824 
6825  for (i = 0; i < numpks; i++)
6826  {
6827  Oid pktype = pktypoid[i];
6828  Oid fktype = fktypoid[i];
6829  Oid fktyped;
6830  HeapTuple cla_ht;
6831  Form_pg_opclass cla_tup;
6832  Oid amid;
6833  Oid opfamily;
6834  Oid opcintype;
6835  Oid pfeqop;
6836  Oid ppeqop;
6837  Oid ffeqop;
6838  int16 eqstrategy;
6839  Oid pfeqop_right;
6840 
6841  /* We need several fields out of the pg_opclass entry */
6842  cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
6843  if (!HeapTupleIsValid(cla_ht))
6844  elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
6845  cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
6846  amid = cla_tup->opcmethod;
6847  opfamily = cla_tup->opcfamily;
6848  opcintype = cla_tup->opcintype;
6849  ReleaseSysCache(cla_ht);
6850 
6851  /*
6852  * Check it's a btree; currently this can never fail since no other
6853  * index AMs support unique indexes. If we ever did have other types
6854  * of unique indexes, we'd need a way to determine which operator
6855  * strategy number is equality. (Is it reasonable to insist that
6856  * every such index AM use btree's number for equality?)
6857  */
6858  if (amid != BTREE_AM_OID)
6859  elog(ERROR, "only b-tree indexes are supported for foreign keys");
6860  eqstrategy = BTEqualStrategyNumber;
6861 
6862  /*
6863  * There had better be a primary equality operator for the index.
6864  * We'll use it for PK = PK comparisons.
6865  */
6866  ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
6867  eqstrategy);
6868 
6869  if (!OidIsValid(ppeqop))
6870  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
6871  eqstrategy, opcintype, opcintype, opfamily);
6872 
6873  /*
6874  * Are there equality operators that take exactly the FK type? Assume
6875  * we should look through any domain here.
6876  */
6877  fktyped = getBaseType(fktype);
6878 
6879  pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
6880  eqstrategy);
6881  if (OidIsValid(pfeqop))
6882  {
6883  pfeqop_right = fktyped;
6884  ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
6885  eqstrategy);
6886  }
6887  else
6888  {
6889  /* keep compiler quiet */
6890  pfeqop_right = InvalidOid;
6891  ffeqop = InvalidOid;
6892  }
6893 
6894  if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
6895  {
6896  /*
6897  * Otherwise, look for an implicit cast from the FK type to the
6898  * opcintype, and if found, use the primary equality operator.
6899  * This is a bit tricky because opcintype might be a polymorphic
6900  * type such as ANYARRAY or ANYENUM; so what we have to test is
6901  * whether the two actual column types can be concurrently cast to
6902  * that type. (Otherwise, we'd fail to reject combinations such
6903  * as int[] and point[].)
6904  */
6905  Oid input_typeids[2];
6906  Oid target_typeids[2];
6907 
6908  input_typeids[0] = pktype;
6909  input_typeids[1] = fktype;
6910  target_typeids[0] = opcintype;
6911  target_typeids[1] = opcintype;
6912  if (can_coerce_type(2, input_typeids, target_typeids,
6914  {
6915  pfeqop = ffeqop = ppeqop;
6916  pfeqop_right = opcintype;
6917  }
6918  }
6919 
6920  if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
6921  ereport(ERROR,
6922  (errcode(ERRCODE_DATATYPE_MISMATCH),
6923  errmsg("foreign key constraint \"%s\" "
6924  "cannot be implemented",
6925  fkconstraint->conname),
6926  errdetail("Key columns \"%s\" and \"%s\" "
6927  "are of incompatible types: %s and %s.",
6928  strVal(list_nth(fkconstraint->fk_attrs, i)),
6929  strVal(list_nth(fkconstraint->pk_attrs, i)),
6930  format_type_be(fktype),
6931  format_type_be(pktype))));
6932 
6933  if (old_check_ok)
6934  {
6935  /*
6936  * When a pfeqop changes, revalidate the constraint. We could
6937  * permit intra-opfamily changes, but that adds subtle complexity
6938  * without any concrete benefit for core types. We need not
6939  * assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
6940  */
6941  old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
6942  old_pfeqop_item = lnext(old_pfeqop_item);
6943  }
6944  if (old_check_ok)
6945  {
6946  Oid old_fktype;
6947  Oid new_fktype;
6948  CoercionPathType old_pathtype;
6949  CoercionPathType new_pathtype;
6950  Oid old_castfunc;
6951  Oid new_castfunc;
6952 
6953  /*
6954  * Identify coercion pathways from each of the old and new FK-side
6955  * column types to the right (foreign) operand type of the pfeqop.
6956  * We may assume that pg_constraint.conkey is not changing.
6957  */
6958  old_fktype = tab->oldDesc->attrs[fkattnum[i] - 1]->atttypid;
6959  new_fktype = fktype;
6960  old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
6961  &old_castfunc);
6962  new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
6963  &new_castfunc);
6964 
6965  /*
6966  * Upon a change to the cast from the FK column to its pfeqop
6967  * operand, revalidate the constraint. For this evaluation, a
6968  * binary coercion cast is equivalent to no cast at all. While
6969  * type implementors should design implicit casts with an eye
6970  * toward consistency of operations like equality, we cannot
6971  * assume here that they have done so.
6972  *
6973  * A function with a polymorphic argument could change behavior
6974  * arbitrarily in response to get_fn_expr_argtype(). Therefore,
6975  * when the cast destination is polymorphic, we only avoid
6976  * revalidation if the input type has not changed at all. Given
6977  * just the core data types and operator classes, this requirement
6978  * prevents no would-be optimizations.
6979  *
6980  * If the cast converts from a base type to a domain thereon, then
6981  * that domain type must be the opcintype of the unique index.
6982  * Necessarily, the primary key column must then be of the domain
6983  * type. Since the constraint was previously valid, all values on
6984  * the foreign side necessarily exist on the primary side and in
6985  * turn conform to the domain. Consequently, we need not treat
6986  * domains specially here.
6987  *
6988  * Since we require that all collations share the same notion of
6989  * equality (which they do, because texteq reduces to bitwise
6990  * equality), we don't compare collation here.
6991  *
6992  * We need not directly consider the PK type. It's necessarily
6993  * binary coercible to the opcintype of the unique index column,
6994  * and ri_triggers.c will only deal with PK datums in terms of
6995  * that opcintype. Changing the opcintype also changes pfeqop.
6996  */
6997  old_check_ok = (new_pathtype == old_pathtype &&
6998  new_castfunc == old_castfunc &&
6999  (!IsPolymorphicType(pfeqop_right) ||
7000  new_fktype == old_fktype));
7001 
7002  }
7003 
7004  pfeqoperators[i] = pfeqop;
7005  ppeqoperators[i] = ppeqop;
7006  ffeqoperators[i] = ffeqop;
7007  }
7008 
7009  /*
7010  * Record the FK constraint in pg_constraint.
7011  */
7012  constrOid = CreateConstraintEntry(fkconstraint->conname,
7013  RelationGetNamespace(rel),
7015  fkconstraint->deferrable,
7016  fkconstraint->initdeferred,
7017  fkconstraint->initially_valid,
7018  RelationGetRelid(rel),
7019  fkattnum,
7020  numfks,
7021  InvalidOid, /* not a domain
7022  * constraint */
7023  indexOid,
7024  RelationGetRelid(pkrel),
7025  pkattnum,
7026  pfeqoperators,
7027  ppeqoperators,
7028  ffeqoperators,
7029  numpks,
7030  fkconstraint->fk_upd_action,
7031  fkconstraint->fk_del_action,
7032  fkconstraint->fk_matchtype,
7033  NULL, /* no exclusion constraint */
7034  NULL, /* no check constraint */
7035  NULL,
7036  NULL,
7037  true, /* islocal */
7038  0, /* inhcount */
7039  true, /* isnoinherit */
7040  false); /* is_internal */
7041  ObjectAddressSet(address, ConstraintRelationId, constrOid);
7042 
7043  /*
7044  * Create the triggers that will enforce the constraint.
7045  */
7046  createForeignKeyTriggers(rel, RelationGetRelid(pkrel), fkconstraint,
7047  constrOid, indexOid);
7048 
7049  /*
7050  * Tell Phase 3 to check that the constraint is satisfied by existing
7051  * rows. We can skip this during table creation, when requested explicitly
7052  * by specifying NOT VALID in an ADD FOREIGN KEY command, and when we're
7053  * recreating a constraint following a SET DATA TYPE operation that did
7054  * not impugn its validity.
7055  */
7056  if (!old_check_ok && !fkconstraint->skip_validation)
7057  {
7058  NewConstraint *newcon;
7059 
7060  newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
7061  newcon->name = fkconstraint->conname;
7062  newcon->contype = CONSTR_FOREIGN;
7063  newcon->refrelid = RelationGetRelid(pkrel);
7064  newcon->refindid = indexOid;
7065  newcon->conid = constrOid;
7066  newcon->qual = (Node *) fkconstraint;
7067 
7068  tab->constraints = lappend(tab->constraints, newcon);
7069  }
7070 
7071  /*
7072  * Close pk table, but keep lock until we've committed.
7073  */
7074  heap_close(pkrel, NoLock);
7075 
7076  return address;
7077 }
signed short int16
Definition: c.h:252
#define NIL
Definition: pg_list.h:69
#define CONSTRAINT_FOREIGN
char * name
Definition: tablecmds.c:182
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
List * old_conpfeqop
Definition: parsenodes.h:2005
bool IsSystemRelation(Relation relation)
Definition: catalog.c:62
#define RELPERSISTENCE_UNLOGGED
Definition: pg_class.h:171
char fk_matchtype
Definition: parsenodes.h:2002
static int transformColumnNameList(Oid relId, List *colList, int16 *attnums, Oid *atttypids)
Definition: tablecmds.c:7426
#define BTREE_AM_OID
Definition: pg_am.h:70
bool rd_islocaltemp
Definition: rel.h:90
Form_pg_attribute * attrs
Definition: tupdesc.h:74
Node * qual
Definition: tablecmds.c:187
Definition: nodes.h:508
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
bool initdeferred
Definition: parsenodes.h:1976
#define MemSet(start, val, len)
Definition: c.h:853
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:2001
char * conname
Definition: parsenodes.h:1974
Form_pg_class rd_rel
Definition: rel.h:113
unsigned int Oid
Definition: postgres_ext.h:31
static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
Definition: tablecmds.c:7733
#define OidIsValid(objectId)
Definition: c.h:534
CoercionPathType
Definition: parse_coerce.h:24
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:149
List * constraints
Definition: tablecmds.c:163
#define RELPERSISTENCE_PERMANENT
Definition: pg_class.h:170
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
#define IsPolymorphicType(typid)
Definition: pg_type.h:733
bool deferrable
Definition: parsenodes.h:1975
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:433
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
static void createForeignKeyTriggers(Relation rel, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid)
Definition: tablecmds.c:7977
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
Oid old_pktable_oid
Definition: parsenodes.h:2006
List * lappend(List *list, void *datum)
Definition: list.c:128
ConstrType contype
Definition: tablecmds.c:183
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
void * palloc0(Size size)
Definition: mcxt.c:920
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1083
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1315
bool allowSystemTableMods
Definition: globals.c:111
#define InvalidOid
Definition: postgres_ext.h:36
bool initially_valid
Definition: parsenodes.h:2010
static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid, List **attnamelist, int16 *attnums, Oid *atttypids, Oid *opclasses)
Definition: tablecmds.c:7471
char fk_del_action
Definition: parsenodes.h:2004
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define ShareRowExclusiveLock
Definition: lockdefs.h:42
static CoercionPathType findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
Definition: tablecmds.c:7709
#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:7568
bool can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:527
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:1999
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2239
#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:2009
#define RelationGetRelid(relation)
Definition: rel.h:413
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:2000
#define BTEqualStrategyNumber
Definition: stratnum.h:31
char fk_upd_action
Definition: parsenodes.h:2003
#define lfirst_oid(lc)
Definition: pg_list.h:108
#define RelationGetNamespace(relation)
Definition: rel.h:440
static bool ATColumnChangeRequiresRewrite ( Node expr,
AttrNumber  varattno 
)
static

Definition at line 8582 of file tablecmds.c.

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

Referenced by ATPrepAlterColumnType().

8583 {
8584  Assert(expr != NULL);
8585 
8586  for (;;)
8587  {
8588  /* only one varno, so no need to check that */
8589  if (IsA(expr, Var) &&((Var *) expr)->varattno == varattno)
8590  return false;
8591  else if (IsA(expr, RelabelType))
8592  expr = (Node *) ((RelabelType *) expr)->arg;
8593  else if (IsA(expr, CoerceToDomain))
8594  {
8595  CoerceToDomain *d = (CoerceToDomain *) expr;
8596 
8598  return true;
8599  expr = (Node *) d->arg;
8600  }
8601  else
8602  return true;
8603  }
8604 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
Definition: nodes.h:508
Definition: primnodes.h:141
bool DomainHasConstraints(Oid type_id)
Definition: typcache.c:1047
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
void * arg
static void ATController ( AlterTableStmt parsetree,
Relation  rel,
List cmds,
bool  recurse,
LOCKMODE  lockmode 
)
static

Definition at line 3344 of file tablecmds.c.

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

Referenced by AlterTable(), and AlterTableInternal().

3346 {
3347  List *wqueue = NIL;
3348  ListCell *lcmd;
3349 
3350  /* Phase 1: preliminary examination of commands, create work queue */
3351  foreach(lcmd, cmds)
3352  {
3353  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3354 
3355  ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode);
3356  }
3357 
3358  /* Close the relation, but keep lock until commit */
3359  relation_close(rel, NoLock);
3360 
3361  /* Phase 2: update system catalogs */
3362  ATRewriteCatalogs(&wqueue, lockmode);
3363 
3364  /* Phase 3: scan/rewrite tables as needed */
3365  ATRewriteTables(parsetree, &wqueue, lockmode);
3366 }
#define NIL
Definition: pg_list.h:69
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1263
#define NoLock
Definition: lockdefs.h:34
static void ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode)
Definition: tablecmds.c:4000
static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
Definition: tablecmds.c:3378
#define lfirst(lc)
Definition: pg_list.h:106
static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode)
Definition: tablecmds.c:3666
Definition: pg_list.h:45
void AtEOSubXact_on_commit_actions ( bool  isCommit,
SubTransactionId  mySubid,
SubTransactionId  parentSubid 
)

Definition at line 12540 of file tablecmds.c.

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

12542 {
12543  ListCell *cur_item;
12544  ListCell *prev_item;
12545 
12546  prev_item = NULL;
12547  cur_item = list_head(on_commits);
12548 
12549  while (cur_item != NULL)
12550  {
12551  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
12552 
12553  if (!isCommit && oc->creating_subid == mySubid)
12554  {
12555  /* cur_item must be removed */
12556  on_commits = list_delete_cell(on_commits, cur_item, prev_item);
12557  pfree(oc);
12558  if (prev_item)
12559  cur_item = lnext(prev_item);
12560  else
12561  cur_item = list_head(on_commits);
12562  }
12563  else
12564  {
12565  /* cur_item must be preserved */
12566  if (oc->creating_subid == mySubid)
12567  oc->creating_subid = parentSubid;
12568  if (oc->deleting_subid == mySubid)
12569  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
12570  prev_item = cur_item;
12571  cur_item = lnext(prev_item);
12572  }
12573  }
12574 }
SubTransactionId creating_subid
Definition: tablecmds.c:120
void pfree(void *pointer)
Definition: mcxt.c:992
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 NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
#define InvalidSubTransactionId
Definition: c.h:400
void AtEOXact_on_commit_actions ( bool  isCommit)

Definition at line 12498 of file tablecmds.c.

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

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

12499 {
12500  ListCell *cur_item;
12501  ListCell *prev_item;
12502 
12503  prev_item = NULL;
12504  cur_item = list_head(on_commits);
12505 
12506  while (cur_item != NULL)
12507  {
12508  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
12509 
12510  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
12512  {
12513  /* cur_item must be removed */
12514  on_commits = list_delete_cell(on_commits, cur_item, prev_item);
12515  pfree(oc);
12516  if (prev_item)
12517  cur_item = lnext(prev_item);
12518  else
12519  cur_item = list_head(on_commits);
12520  }
12521  else
12522  {
12523  /* cur_item must be preserved */
12526  prev_item = cur_item;
12527  cur_item = lnext(prev_item);
12528  }
12529  }
12530 }
SubTransactionId creating_subid
Definition: tablecmds.c:120
void pfree(void *pointer)
Definition: mcxt.c:992
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 NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
#define InvalidSubTransactionId
Definition: c.h:400
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 5004 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::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, NULL, 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().

5008 {
5009  Oid myrelid = RelationGetRelid(rel);
5010  Relation pgclass,
5011  attrdesc;
5012  HeapTuple reltup;
5013  FormData_pg_attribute attribute;
5014  int newattnum;
5015  char relkind;
5016  HeapTuple typeTuple;
5017  Oid typeOid;
5018  int32 typmod;
5019  Oid collOid;
5020  Form_pg_type tform;
5021  Expr *defval;
5022  List *children;
5023  ListCell *child;
5024  AclResult aclresult;
5025  ObjectAddress address;
5026 
5027  /* At top level, permission check was done in ATPrepCmd, else do it */
5028  if (recursing)
5030 
5031  if (rel->rd_rel->relispartition && !recursing)
5032  ereport(ERROR,
5033  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5034  errmsg("cannot add column to a partition")));
5035 
5037 
5038  /*
5039  * Are we adding the column to a recursion child? If so, check whether to
5040  * merge with an existing definition for the column. If we do merge, we
5041  * must not recurse. Children will already have the column, and recursing
5042  * into them would mess up attinhcount.
5043  */
5044  if (colDef->inhcount > 0)
5045  {
5046  HeapTuple tuple;
5047 
5048  /* Does child already have a column by this name? */
5049  tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
5050  if (HeapTupleIsValid(tuple))
5051  {
5052  Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
5053  Oid ctypeId;
5054  int32 ctypmod;
5055  Oid ccollid;
5056 
5057  /* Child column must match on type, typmod, and collation */
5058  typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
5059  if (ctypeId != childatt->atttypid ||
5060  ctypmod != childatt->atttypmod)
5061  ereport(ERROR,
5062  (errcode(ERRCODE_DATATYPE_MISMATCH),
5063  errmsg("child table \"%s\" has different type for column \"%s\"",
5064  RelationGetRelationName(rel), colDef->colname)));
5065  ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
5066  if (ccollid != childatt->attcollation)
5067  ereport(ERROR,
5068  (errcode(ERRCODE_COLLATION_MISMATCH),
5069  errmsg("child table \"%s\" has different collation for column \"%s\"",
5070  RelationGetRelationName(rel), colDef->colname),
5071  errdetail("\"%s\" versus \"%s\"",
5072  get_collation_name(ccollid),
5073  get_collation_name(childatt->attcollation))));
5074 
5075  /* If it's OID, child column must actually be OID */
5076  if (isOid && childatt->attnum != ObjectIdAttributeNumber)
5077  ereport(ERROR,
5078  (errcode(ERRCODE_DATATYPE_MISMATCH),
5079  errmsg("child table \"%s\" has a conflicting \"%s\" column",
5080  RelationGetRelationName(rel), colDef->colname)));
5081 
5082  /* Bump the existing child att's inhcount */
5083  childatt->attinhcount++;
5084  CatalogTupleUpdate(attrdesc, &tuple->t_self, tuple);
5085 
5086  heap_freetuple(tuple);
5087 
5088  /* Inform the user about the merge */
5089  ereport(NOTICE,
5090  (errmsg("merging definition of column \"%s\" for child \"%s\"",
5091  colDef->colname, RelationGetRelationName(rel))));
5092 
5093  heap_close(attrdesc, RowExclusiveLock);
5094  return InvalidObjectAddress;
5095  }
5096  }
5097 
5099 
5100  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
5101  if (!HeapTupleIsValid(reltup))
5102  elog(ERROR, "cache lookup failed for relation %u", myrelid);
5103  relkind = ((Form_pg_class) GETSTRUCT(reltup))->relkind;
5104 
5105  /* skip if the name already exists and if_not_exists is true */
5106  if (!check_for_column_name_collision(rel, colDef->colname, if_not_exists))
5107  {
5108  heap_close(attrdesc, RowExclusiveLock);
5109  heap_freetuple(reltup);
5110  heap_close(pgclass, RowExclusiveLock);
5111  return InvalidObjectAddress;
5112  }
5113 
5114  /* Determine the new attribute's number */
5115  if (isOid)
5116  newattnum = ObjectIdAttributeNumber;
5117  else
5118  {
5119  newattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts + 1;
5120  if (newattnum > MaxHeapAttributeNumber)
5121  ereport(ERROR,
5122  (errcode(ERRCODE_TOO_MANY_COLUMNS),
5123  errmsg("tables can have at most %d columns",
5125  }
5126 
5127  typeTuple = typenameType(NULL, colDef->typeName, &typmod);
5128  tform = (Form_pg_type) GETSTRUCT(typeTuple);
5129  typeOid = HeapTupleGetOid(typeTuple);
5130 
5131  aclresult = pg_type_aclcheck(typeOid, GetUserId(), ACL_USAGE);
5132  if (aclresult != ACLCHECK_OK)
5133  aclcheck_error_type(aclresult, typeOid);
5134 
5135  collOid = GetColumnDefCollation(NULL, colDef, typeOid);
5136 
5137  /* make sure datatype is legal for a column */
5138  CheckAttributeType(colDef->colname, typeOid, collOid,
5139  list_make1_oid(rel->rd_rel->reltype),
5140  false);
5141 
5142  /* construct new attribute's pg_attribute entry */
5143  attribute.attrelid = myrelid;
5144  namestrcpy(&(attribute.attname), colDef->colname);
5145  attribute.atttypid = typeOid;
5146  attribute.attstattarget = (newattnum > 0) ? -1 : 0;
5147  attribute.attlen = tform->typlen;
5148  attribute.attcacheoff = -1;
5149  attribute.atttypmod = typmod;
5150  attribute.attnum = newattnum;
5151  attribute.attbyval = tform->typbyval;
5152  attribute.attndims = list_length(colDef->typeName->arrayBounds);
5153  attribute.attstorage = tform->typstorage;
5154  attribute.attalign = tform->typalign;
5155  attribute.attnotnull = colDef->is_not_null;
5156  attribute.atthasdef = false;
5157  attribute.attisdropped = false;
5158  attribute.attislocal = colDef->is_local;
5159  attribute.attinhcount = colDef->inhcount;
5160  attribute.attcollation = collOid;
5161  /* attribute.attacl is handled by InsertPgAttributeTuple */
5162 
5163  ReleaseSysCache(typeTuple);
5164 
5165  InsertPgAttributeTuple(attrdesc, &attribute, NULL);
5166 
5167  heap_close(attrdesc, RowExclusiveLock);
5168 
5169  /*
5170  * Update pg_class tuple as appropriate
5171  */
5172  if (isOid)
5173  ((Form_pg_class) GETSTRUCT(reltup))->relhasoids = true;
5174  else
5175  ((Form_pg_class) GETSTRUCT(reltup))->relnatts = newattnum;
5176 
5177  CatalogTupleUpdate(pgclass, &reltup->t_self, reltup);
5178 
5179  heap_freetuple(reltup);
5180 
5181  /* Post creation hook for new attribute */
5182  InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
5183 
5184  heap_close(pgclass, RowExclusiveLock);
5185 
5186  /* Make the attribute's catalog entry visible */
5188 
5189  /*
5190  * Store the DEFAULT, if any, in the catalogs
5191  */
5192  if (colDef->raw_default)
5193  {
5194  RawColumnDefault *rawEnt;
5195 
5196  rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
5197  rawEnt->attnum = attribute.attnum;
5198  rawEnt->raw_default = copyObject(colDef->raw_default);
5199 
5200  /*
5201  * This function is intended for CREATE TABLE, so it processes a
5202  * _list_ of defaults, but we just do one.
5203  */
5205  false, true, false);
5206 
5207  /* Make the additional catalog changes visible */
5209  }
5210 
5211  /*
5212  * Tell Phase 3 to fill in the default expression, if there is one.
5213  *
5214  * If there is no default, Phase 3 doesn't have to do anything, because
5215  * that effectively means that the default is NULL. The heap tuple access
5216  * routines always check for attnum > # of attributes in tuple, and return
5217  * NULL if so, so without any modification of the tuple data we will get
5218  * the effect of NULL values in the new column.
5219  *
5220  * An exception occurs when the new column is of a domain type: the domain
5221  * might have a NOT NULL constraint, or a check constraint that indirectly
5222  * rejects nulls. If there are any domain constraints then we construct
5223  * an explicit NULL default value that will be passed through
5224  * CoerceToDomain processing. (This is a tad inefficient, since it causes
5225  * rewriting the table which we really don't have to do, but the present
5226  * design of domain processing doesn't offer any simple way of checking
5227  * the constraints more directly.)
5228  *
5229  * Note: we use build_column_default, and not just the cooked default
5230  * returned by AddRelationNewConstraints, so that the right thing happens
5231  * when a datatype's default applies.
5232  *
5233  * We skip this step completely for views and foreign tables. For a view,
5234  * we can only get here from CREATE OR REPLACE VIEW, which historically
5235  * doesn't set up defaults, not even for domain-typed columns. And in any
5236  * case we mustn't invoke Phase 3 on a view or foreign table, since they
5237  * have no storage.
5238  */
5239  if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE
5240  && relkind != RELKIND_FOREIGN_TABLE && attribute.attnum > 0)
5241  {
5242  defval = (Expr *) build_column_default(rel, attribute.attnum);
5243 
5244  if (!defval && DomainHasConstraints(typeOid))
5245  {
5246  Oid baseTypeId;
5247  int32 baseTypeMod;
5248  Oid baseTypeColl;
5249 
5250  baseTypeMod = typmod;
5251  baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
5252  baseTypeColl = get_typcollation(baseTypeId);
5253  defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
5254  defval = (Expr *) coerce_to_target_type(NULL,
5255  (Node *) defval,
5256  baseTypeId,
5257  typeOid,
5258  typmod,
5261  -1);
5262  if (defval == NULL) /* should not happen */
5263  elog(ERROR, "failed to coerce base type to domain");
5264  }
5265 
5266  if (defval)
5267  {
5269 
5270  newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
5271  newval->attnum = attribute.attnum;
5272  newval->expr = expression_planner(defval);
5273 
5274  tab->newvals = lappend(tab->newvals, newval);
5276  }
5277 
5278  /*
5279  * If the new column is NOT NULL, tell Phase 3 it needs to test that.
5280  * (Note we don't do this for an OID column. OID will be marked not
5281  * null, but since it's filled specially, there's no need to test
5282  * anything.)
5283  */
5284  tab->new_notnull |= colDef->is_not_null;
5285  }
5286 
5287  /*
5288  * If we are adding an OID column, we have to tell Phase 3 to rewrite the
5289  * table to fix that.
5290  */
5291  if (isOid)
5292  tab->rewrite |= AT_REWRITE_ALTER_OID;
5293 
5294  /*
5295  * Add needed dependency entries for the new column.
5296  */
5297  add_column_datatype_dependency(myrelid, newattnum, attribute.atttypid);
5298  add_column_collation_dependency(myrelid, newattnum, attribute.attcollation);
5299 
5300  /*
5301  * Propagate to children as appropriate. Unlike most other ALTER
5302  * routines, we have to do this one level of recursion at a time; we can't
5303  * use find_all_inheritors to do it in one pass.
5304  */
5305  children = find_inheritance_children(RelationGetRelid(rel), lockmode);
5306 
5307  /*
5308  * If we are told not to recurse, there had better not be any child
5309  * tables; else the addition would put them out of step.
5310  */
5311  if (children && !recurse)
5312  ereport(ERROR,
5313  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5314  errmsg("column must be added to child tables too")));
5315 
5316  /* Children should see column as singly inherited */
5317  if (!recursing)
5318  {
5319  colDef = copyObject(colDef);
5320  colDef->inhcount = 1;
5321  colDef->is_local = false;
5322  }
5323 
5324  foreach(child, children)
5325  {
5326  Oid childrelid = lfirst_oid(child);
5327  Relation childrel;
5328  AlteredTableInfo *childtab;
5329 
5330  /* find_inheritance_children already got lock */
5331  childrel = heap_open(childrelid, NoLock);
5332  CheckTableNotInUse(childrel, "ALTER TABLE");
5333 
5334  /* Find or create work queue entry for this table */
5335  childtab = ATGetQueueEntry(wqueue, childrel);
5336 
5337  /* Recurse to child; return value is ignored */
5338  ATExecAddColumn(wqueue, childtab, childrel,
5339  colDef, isOid, recurse, true,
5340  if_not_exists, lockmode);
5341 
5342  heap_close(childrel, NoLock);
5343  }
5344 
5345  ObjectAddressSubSet(address, RelationRelationId, myrelid, newattnum);
5346  return address;
5347 }
#define NIL
Definition: pg_list.h:69
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2256
#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:601
Oid GetUserId(void)
Definition: miscinit.c:283
#define ObjectIdAttributeNumber
Definition: sysattr.h:22
char * get_collation_name(Oid colloid)
Definition: lsyscache.c:935
#define RelationRelationId
Definition: pg_class.h:29
Expr * expression_planner(Expr *expr)
Definition: planner.c:5211
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:5004
Definition: nodes.h:508
#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:602
FormData_pg_type * Form_pg_type
Definition: pg_type.h:233
Form_pg_class rd_rel
Definition: rel.h:113
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
unsigned int Oid
Definition: postgres_ext.h:31
#define ATT_TABLE
Definition: tablecmds.c:278
int namestrcpy(Name name, const char *str)
Definition: name.c:217
#define RELKIND_COMPOSITE_TYPE
Definition: pg_class.h:165
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3436
signed int int32
Definition: c.h:253
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:334
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
bool DomainHasConstraints(Oid type_id)
Definition: typcache.c:1047
#define list_make1(x1)
Definition: pg_list.h:133
#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:5407
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:77
HeapTuple SearchSysCacheCopyAttName(Oid relid, const char *attname)
Definition: syscache.c:1194
ItemPointerData t_self
Definition: htup.h:65
static void add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
Definition: tablecmds.c:5425
#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:433
static AlteredTableInfo * ATGetQueueEntry(List **wqueue, Relation rel)
Definition: tablecmds.c:4547
Node * raw_default
Definition: heap.h:25
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
#define ACL_USAGE
Definition: parsenodes.h:73
#define AT_REWRITE_ALTER_OID
Definition: event_trigger.h:34
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:166
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:2950
#define ereport(elevel, rest)
Definition: elog.h:122
Node * raw_default
Definition: parsenodes.h:605
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:485
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:920
AclResult
Definition: acl.h:170
void CommandCounterIncrement(void)
Definition: xact.c:921
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1083
#define list_make1_oid(x1)
Definition: pg_list.h:145
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
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:168
List * find_inheritance_children(Oid parentrelId, LOCKMODE lockmode)
Definition: pg_inherits.c:49
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2749
#define NOTICE
Definition: elog.h:37
#define MaxHeapAttributeNumber
Definition: htup_details.h:47
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
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:599
#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:158
List * arrayBounds
Definition: parsenodes.h:206
void InsertPgAttributeTuple(Relation pg_attribute_rel, Form_pg_attribute new_attribute, CatalogIndexState indstate)
Definition: heap.c:595
const ObjectAddress InvalidObjectAddress
void * palloc(Size size)
Definition: mcxt.c:891
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:5354
#define RELKIND_VIEW
Definition: pg_class.h:164
int inhcount
Definition: parsenodes.h:600
static void ATSimplePermissions(Relation rel, int allowed_targets)
Definition: tablecmds.c:4584
char * colname
Definition: parsenodes.h:598
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4509
Definition: pg_list.h:45
#define ATT_FOREIGN_TABLE
Definition: tablecmds.c:283
#define RelationGetRelid(relation)
Definition: rel.h:413
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal)
Definition: heap.c:2186
#define lfirst_oid(lc)
Definition: pg_list.h:108
AttrNumber attnum
Definition: tablecmds.c:200
static ObjectAddress ATExecAddConstraint ( List **  wqueue,
AlteredTableInfo tab,
Relation  rel,
Constraint newConstraint,
bool  recurse,
bool  is_readd,
LOCKMODE  lockmode 
)
static

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

6469 {
6471 
6472  Assert(IsA(newConstraint, Constraint));
6473 
6474  /*
6475  * Currently, we only expect to see CONSTR_CHECK and CONSTR_FOREIGN nodes
6476  * arriving here (see the preprocessing done in parse_utilcmd.c). Use a
6477  * switch anyway to make it easier to add more code later.
6478  */
6479  switch (newConstraint->contype)
6480  {
6481  case CONSTR_CHECK:
6482  address =
6483  ATAddCheckConstraint(wqueue, tab, rel,
6484  newConstraint, recurse, false, is_readd,
6485  lockmode);
6486  break;
6487 
6488  case CONSTR_FOREIGN:
6489 
6490  /*
6491  * Note that we currently never recurse for FK constraints, so the
6492  * "recurse" flag is silently ignored.
6493  *
6494  * Assign or validate constraint name
6495  */
6496  if (newConstraint->conname)
6497  {
6499  RelationGetRelid(rel),
6500  RelationGetNamespace(rel),
6501  newConstraint->conname))
6502  ereport(ERROR,
6504  errmsg("constraint \"%s\" for relation \"%s\" already exists",
6505  newConstraint->conname,
6506  RelationGetRelationName(rel))));
6507  }
6508  else
6509  newConstraint->conname =
6511  strVal(linitial(newConstraint->fk_attrs)),
6512  "fkey",
6513  RelationGetNamespace(rel),
6514  NIL);
6515 
6516  address = ATAddForeignKeyConstraint(tab, rel, newConstraint,
6517  lockmode);
6518  break;
6519 
6520  default:
6521  elog(ERROR, "unrecognized constraint type: %d",
6522  (int) newConstraint->contype);
6523  }
6524 
6525  return address;
6526 }
#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:559
static ObjectAddress ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel, Constraint *fkconstraint, LOCKMODE lockmode)
Definition: tablecmds.c:6672
#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:6544
char * conname
Definition: parsenodes.h:1974
#define linitial(l)
Definition: pg_list.h:110
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:433
#define ereport(elevel, rest)
Definition: elog.h:122
#define Assert(condition)
Definition: c.h:671
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:1971
#define elog
Definition: elog.h:219
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:34
#define RelationGetRelid(relation)
Definition: rel.h:413
List * fk_attrs
Definition: parsenodes.h:2000
#define RelationGetNamespace(relation)
Definition: rel.h:440
static ObjectAddress ATExecAddIndex ( AlteredTableInfo tab,
Relation  rel,
IndexStmt stmt,
bool  is_rebuild,
LOCKMODE  lockmode 
)
static

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

6337 {
6338  bool check_rights;
6339  bool skip_build;
6340  bool quiet;
6341  ObjectAddress address;
6342 
6343  Assert(IsA(stmt, IndexStmt));
6344  Assert(!stmt->concurrent);
6345 
6346  /* The IndexStmt has already been through transformIndexStmt */
6347  Assert(stmt->transformed);
6348 
6349  /* suppress schema rights check when rebuilding existing index */
6350  check_rights = !is_rebuild;
6351  /* skip index build if phase 3 will do it or we're reusing an old one */
6352  skip_build = tab->rewrite > 0 || OidIsValid(stmt->oldNode);
6353  /* suppress notices when rebuilding existing index */
6354  quiet = is_rebuild;
6355 
6356  address = DefineIndex(RelationGetRelid(rel),
6357  stmt,
6358  InvalidOid, /* no predefined OID */
6359  true, /* is_alter_table */
6360  check_rights,
6361  skip_build,
6362  quiet);
6363 
6364  /*
6365  * If TryReuseIndex() stashed a relfilenode for us, we used it for the new
6366  * index instead of building from scratch. The DROP of the old edition of
6367  * this index will have scheduled the storage for deletion at commit, so
6368  * cancel that pending deletion.
6369  */
6370  if (OidIsValid(stmt->oldNode))
6371  {
6372  Relation irel = index_open(address.objectId, NoLock);
6373 
6374  RelationPreserveStorage(irel->rd_node, true);
6375  index_close(irel, NoLock);
6376  }
6377 
6378  return address;
6379 }
void RelationPreserveStorage(RelFileNode rnode, bool atCommit)
Definition: storage.c:190
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
#define OidIsValid(objectId)
Definition: c.h:534
#define NoLock
Definition: lockdefs.h:34
bool transformed
Definition: parsenodes.h:2604
#define InvalidOid
Definition: postgres_ext.h:36
RelFileNode rd_node
Definition: rel.h:85
#define Assert(condition)
Definition: c.h:671
ObjectAddress DefineIndex(Oid relationId, IndexStmt *stmt, Oid indexRelationId, bool is_alter_table, bool check_rights, bool skip_build, bool quiet)
Definition: indexcmds.c:305
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
bool concurrent
Definition: parsenodes.h:2605
#define RelationGetRelid(relation)
Definition: rel.h:413
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 6387 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, NULL, OidIsValid, IndexStmt::primary, pstrdup(), RelationGetRelationName, and RenameRelationInternal().

Referenced by ATExecCmd().

6389 {
6390  Oid index_oid = stmt->indexOid;
6391  Relation indexRel;
6392  char *indexName;
6393  IndexInfo *indexInfo;
6394  char *constraintName;
6395  char constraintType;
6396  ObjectAddress address;
6397 
6398  Assert(IsA(stmt, IndexStmt));
6399  Assert(OidIsValid(index_oid));
6400  Assert(stmt->isconstraint);
6401 
6402  indexRel = index_open(index_oid, AccessShareLock);
6403 
6404  indexName = pstrdup(RelationGetRelationName(indexRel));
6405 
6406  indexInfo = BuildIndexInfo(indexRel);
6407 
6408  /* this should have been checked at parse time */
6409  if (!indexInfo->ii_Unique)
6410  elog(ERROR, "index \"%s\" is not unique", indexName);
6411 
6412  /*
6413  * Determine name to assign to constraint. We require a constraint to
6414  * have the same name as the underlying index; therefore, use the index's
6415  * existing name as the default constraint name, and if the user
6416  * explicitly gives some other name for the constraint, rename the index
6417  * to match.
6418  */
6419  constraintName = stmt->idxname;
6420  if (constraintName == NULL)
6421  constraintName = indexName;
6422  else if (strcmp(constraintName, indexName) != 0)
6423  {
6424  ereport(NOTICE,
6425  (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
6426  indexName, constraintName)));
6427  RenameRelationInternal(index_oid, constraintName, false);
6428  }
6429 
6430  /* Extra checks needed if making primary key */
6431  if (stmt->primary)
6432  index_check_primary_key(rel, indexInfo, true);
6433 
6434  /* Note we currently don't support EXCLUSION constraints here */
6435  if (stmt->primary)
6436  constraintType = CONSTRAINT_PRIMARY;
6437  else
6438  constraintType = CONSTRAINT_UNIQUE;
6439 
6440  /* Create the catalog entries for the constraint */
6441  address = index_constraint_create(rel,
6442  index_oid,
6443  indexInfo,
6444  constraintName,
6445  constraintType,
6446  stmt->deferrable,
6447  stmt->initdeferred,
6448  stmt->primary,
6449  true, /* update pg_index */
6450  true, /* remove old dependencies */
6452  false); /* is_internal */
6453 
6454  index_close(indexRel, NoLock);
6455 
6456  return address;
6457 }
bool deferrable
Definition: parsenodes.h:2602
bool primary
Definition: parsenodes.h:2600
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal)
Definition: tablecmds.c:2854
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
char * pstrdup(const char *in)
Definition: mcxt.c:1165
#define AccessShareLock
Definition: lockdefs.h:36
void index_check_primary_key(Relation heapRel, IndexInfo *indexInfo, bool is_alter_table)
Definition: index.c:192
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:1639
unsigned int Oid
Definition: postgres_ext.h:31
#define CONSTRAINT_UNIQUE
#define OidIsValid(objectId)
Definition: c.h:534
#define CONSTRAINT_PRIMARY
Oid indexOid
Definition: parsenodes.h:2597
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:433
#define ereport(elevel, rest)
Definition: elog.h:122
char * idxname
Definition: parsenodes.h:2588
bool allowSystemTableMods
Definition: globals.c:111
#define NOTICE
Definition: elog.h:37
bool ii_Unique
Definition: execnodes.h:77
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
bool initdeferred
Definition: parsenodes.h:2603
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
bool isconstraint
Definition: parsenodes.h:2601
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:1147
#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 10585 of file tablecmds.c.

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

Referenced by ATExecCmd().

10586 {
10587  Relation parent_rel;
10588  List *children;
10589  ObjectAddress address;
10590 
10591  /*
10592  * A self-exclusive lock is needed here. See the similar case in
10593  * MergeAttributes() for a full explanation.
10594  */
10595  parent_rel = heap_openrv(parent, ShareUpdateExclusiveLock);
10596 
10597  /*
10598  * Must be owner of both parent and child -- child was checked by
10599  * ATSimplePermissions call in ATPrepCmd
10600  */
10602 
10603  /* Permanent rels cannot inherit from temporary ones */
10604  if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
10605  child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
10606  ereport(ERROR,
10607  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10608  errmsg("cannot inherit from temporary relation \"%s\"",
10609  RelationGetRelationName(parent_rel))));
10610 
10611  /* If parent rel is temp, it must belong to this session */
10612  if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
10613  !parent_rel->rd_islocaltemp)
10614  ereport(ERROR,
10615  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10616  errmsg("cannot inherit from temporary relation of another session")));
10617 
10618  /* Ditto for the child */
10619  if (child_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
10620  !child_rel->rd_islocaltemp)
10621  ereport(ERROR,
10622  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10623  errmsg("cannot inherit to temporary relation of another session")));
10624 
10625  /* Prevent partitioned tables from becoming inheritance parents */
10626  if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
10627  ereport(ERROR,
10628  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10629  errmsg("cannot inherit from partitioned table \"%s\"",
10630  parent->relname)));
10631 
10632  /* Likewise for partitions */
10633  if (parent_rel->rd_rel->relispartition)
10634  ereport(ERROR,
10635  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10636  errmsg("cannot inherit from a partition")));
10637 
10638  /*
10639  * Prevent circularity by seeing if proposed parent inherits from child.
10640  * (In particular, this disallows making a rel inherit from itself.)
10641  *
10642  * This is not completely bulletproof because of race conditions: in
10643  * multi-level inheritance trees, someone else could concurrently be
10644  * making another inheritance link that closes the loop but does not join
10645  * either of the rels we have locked. Preventing that seems to require
10646  * exclusive locks on the entire inheritance tree, which is a cure worse
10647  * than the disease. find_all_inheritors() will cope with circularity
10648  * anyway, so don't sweat it too much.
10649  *
10650  * We use weakest lock we can on child's children, namely AccessShareLock.
10651  */
10652  children = find_all_inheritors(RelationGetRelid(child_rel),
10654 
10655  if (list_member_oid(children, RelationGetRelid(parent_rel)))
10656  ereport(ERROR,
10657  (errcode(ERRCODE_DUPLICATE_TABLE),
10658  errmsg("circular inheritance not allowed"),
10659  errdetail("\"%s\" is already a child of \"%s\".",
10660  parent->relname,
10661  RelationGetRelationName(child_rel))));
10662 
10663  /* If parent has OIDs then child must have OIDs */
10664  if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
10665  ereport(ERROR,
10666  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10667  errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
10668  RelationGetRelationName(child_rel),
10669  RelationGetRelationName(parent_rel))));
10670 
10671  /* OK to create inheritance */
10672  CreateInheritance(child_rel, parent_rel);
10673 
10675  RelationGetRelid(parent_rel));
10676 
10677  /* keep our lock on the parent relation until commit */
10678  heap_close(parent_rel, NoLock);
10679 
10680  return address;
10681 }
#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:113
#define ATT_TABLE
Definition: tablecmds.c:278
static void CreateInheritance(Relation child_rel, Relation parent_rel)
Definition: tablecmds.c:10691
char * relname
Definition: primnodes.h:67
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:433
#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:1315
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505
#define NULL
Definition: c.h:226
#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:159
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void ATSimplePermissions(Relation rel, int allowed_targets)
Definition: tablecmds.c:4584
#define RELPERSISTENCE_TEMP
Definition: pg_class.h:172
Definition: pg_list.h:45
#define ATT_FOREIGN_TABLE
Definition: tablecmds.c:283
#define RelationGetRelid(relation)
Definition: rel.h:413
static ObjectAddress ATExecAddOf ( Relation  rel,
const TypeName ofTypename,
LOCKMODE  lockmode 
)
static

Definition at line 11390 of file tablecmds.c.

References AccessShareLock, Anum_pg_inherits_inhrelid, tupleDesc::attrs, 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, NULL, 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, typenameType(), and TypeRelationId.

Referenced by ATExecCmd().

11391 {
11392  Oid relid = RelationGetRelid(rel);
11393  Type typetuple;
11394  Oid typeid;
11395  Relation inheritsRelation,
11396  relationRelation;
11397  SysScanDesc scan;
11398  ScanKeyData key;
11399  AttrNumber table_attno,
11400  type_attno;
11401  TupleDesc typeTupleDesc,
11402  tableTupleDesc;
11403  ObjectAddress tableobj,
11404  typeobj;
11405  HeapTuple classtuple;
11406 
11407  /* Validate the type. */
11408  typetuple = typenameType(NULL, ofTypename, NULL);
11409  check_of_type(typetuple);
11410  typeid = HeapTupleGetOid(typetuple);
11411 
11412  /* Fail if the table has any inheritance parents. */
11413  inheritsRelation = heap_open(InheritsRelationId, AccessShareLock);
11414  ScanKeyInit(&key,
11416  BTEqualStrategyNumber, F_OIDEQ,
11417  ObjectIdGetDatum(relid));
11418  scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
11419  true, NULL, 1, &key);
11421  ereport(ERROR,
11422  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11423  errmsg("typed tables cannot inherit")));
11424  systable_endscan(scan);
11425  heap_close(inheritsRelation, AccessShareLock);
11426 
11427  /*
11428  * Check the tuple descriptors for compatibility. Unlike inheritance, we
11429  * require that the order also match. However, attnotnull need not match.
11430  * Also unlike inheritance, we do not require matching relhasoids.
11431  */
11432  typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
11433  tableTupleDesc = RelationGetDescr(rel);
11434  table_attno = 1;
11435  for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
11436  {
11437  Form_pg_attribute type_attr,
11438  table_attr;
11439  const char *type_attname,
11440  *table_attname;
11441 
11442  /* Get the next non-dropped type attribute. */
11443  type_attr = typeTupleDesc->attrs[type_attno - 1];
11444  if (type_attr->attisdropped)
11445  continue;
11446  type_attname = NameStr(type_attr->attname);
11447 
11448  /* Get the next non-dropped table attribute. */
11449  do
11450  {
11451  if (table_attno > tableTupleDesc->natts)
11452  ereport(ERROR,
11453  (errcode(ERRCODE_DATATYPE_MISMATCH),
11454  errmsg("table is missing column \"%s\"",
11455  type_attname)));
11456  table_attr = tableTupleDesc->attrs[table_attno++ - 1];
11457  } while (table_attr->attisdropped);
11458  table_attname = NameStr(table_attr->attname);
11459 
11460  /* Compare name. */
11461  if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
11462  ereport(ERROR,
11463  (errcode(ERRCODE_DATATYPE_MISMATCH),
11464  errmsg("table has column \"%s\" where type requires \"%s\"",
11465  table_attname, type_attname)));
11466 
11467  /* Compare type. */
11468  if (table_attr->atttypid != type_attr->atttypid ||
11469  table_attr->atttypmod != type_attr->atttypmod ||
11470  table_attr->attcollation != type_attr->attcollation)
11471  ereport(ERROR,
11472  (errcode(ERRCODE_DATATYPE_MISMATCH),
11473  errmsg("table \"%s\" has different type for column \"%s\"",
11474  RelationGetRelationName(rel), type_attname)));
11475  }
11476  DecrTupleDescRefCount(typeTupleDesc);
11477 
11478  /* Any remaining columns at the end of the table had better be dropped. */
11479  for (; table_attno <= tableTupleDesc->natts; table_attno++)
11480  {
11481  Form_pg_attribute table_attr = tableTupleDesc->attrs[table_attno - 1];
11482 
11483  if (!table_attr->attisdropped)
11484  ereport(ERROR,
11485  (errcode(ERRCODE_DATATYPE_MISMATCH),
11486  errmsg("table has extra column \"%s\"",
11487  NameStr(table_attr->attname))));
11488  }
11489 
11490  /* If the table was already typed, drop the existing dependency. */
11491  if (rel->rd_rel->reloftype)
11492  drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype);
11493 
11494  /* Record a dependency on the new type. */
11495  tableobj.classId = RelationRelationId;
11496  tableobj.objectId = relid;
11497  tableobj.objectSubId = 0;
11498  typeobj.classId = TypeRelationId;
11499  typeobj.objectId = typeid;
11500  typeobj.objectSubId = 0;
11501  recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
11502 
11503  /* Update pg_class.reloftype */
11504  relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
11505  classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
11506  if (!HeapTupleIsValid(classtuple))
11507  elog(ERROR, "cache lookup failed for relation %u", relid);
11508  ((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
11509  CatalogTupleUpdate(relationRelation, &classtuple->t_self, classtuple);
11510 
11512 
11513  heap_freetuple(classtuple);
11514  heap_close(relationRelation, RowExclusiveLock);
11515 
11516  ReleaseSysCache(typetuple);
11517 
11518  return typeobj;
11519 }
#define Anum_pg_inherits_inhrelid
Definition: pg_inherits.h:50
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:493
#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:1245
#define RelationGetDescr(relation)
Definition: rel.h:425
#define RelationRelationId
Definition: pg_class.h:29
Form_pg_attribute * attrs
Definition: tupdesc.h:74
#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:113
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
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:322
int natts
Definition: tupdesc.h:73
#define NAMEDATALEN
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:410
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
void check_of_type(HeapTuple typetuple)
Definition: tablecmds.c:4941
static void drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid)
Definition: tablecmds.c:11339
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:433
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1083
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
void DecrTupleDescRefCount(TupleDesc tupdesc)
Definition: tupdesc.c:334
#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:158
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:495
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:413
#define BTEqualStrategyNumber
Definition: stratnum.h:31
static ObjectAddress ATExecAlterColumnGenericOptions ( Relation  rel,
const char *  colName,
List options,
LOCKMODE  lockmode 
)
static

Definition at line 9014 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, NULL, ObjectAddressSubSet, PointerGetDatum, PointerIsValid, RelationData::rd_id, RelationGetDescr, RelationGetRelationName, RelationGetRelid, RelationRelationId, ReleaseSysCache(), RowExclusiveLock, SearchSysCache1, SearchSysCacheAttName(), SysCacheGetAttr(), HeapTupleData::t_self, and transformGenericOptions().

Referenced by ATExecCmd().

9018 {
9019  Relation ftrel;
9020  Relation attrel;
9021  ForeignServer *server;
9022  ForeignDataWrapper *fdw;
9023  HeapTuple tuple;
9024  HeapTuple newtuple;
9025  bool isnull;
9026  Datum repl_val[Natts_pg_attribute];
9027  bool repl_null[Natts_pg_attribute];
9028  bool repl_repl[Natts_pg_attribute];
9029  Datum datum;
9030  Form_pg_foreign_table fttableform;
9031  Form_pg_attribute atttableform;
9032  AttrNumber attnum;
9033  ObjectAddress address;
9034 
9035  if (options == NIL)
9036  return InvalidObjectAddress;
9037 
9038  /* First, determine FDW validator associated to the foreign table. */
9040  tuple = SearchSysCache1(FOREIGNTABLEREL, rel->rd_id);
9041  if (!HeapTupleIsValid(tuple))
9042  ereport(ERROR,
9043  (errcode(ERRCODE_UNDEFINED_OBJECT),
9044  errmsg("foreign table \"%s\" does not exist",
9045  RelationGetRelationName(rel))));
9046  fttableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
9047  server = GetForeignServer(fttableform->ftserver);
9048  fdw = GetForeignDataWrapper(server->fdwid);
9049 
9050  heap_close(ftrel, AccessShareLock);
9051  ReleaseSysCache(tuple);
9052 
9054  tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9055  if (!HeapTupleIsValid(tuple))
9056  ereport(ERROR,
9057  (errcode(ERRCODE_UNDEFINED_COLUMN),
9058  errmsg("column \"%s\" of relation \"%s\" does not exist",
9059  colName, RelationGetRelationName(rel))));
9060 
9061  /* Prevent them from altering a system attribute */
9062  atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
9063  attnum = atttableform->attnum;
9064  if (attnum <= 0)
9065  ereport(ERROR,
9066  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9067  errmsg("cannot alter system column \"%s\"", colName)));
9068 
9069 
9070  /* Initialize buffers for new tuple values */
9071  memset(repl_val, 0, sizeof(repl_val));
9072  memset(repl_null, false, sizeof(repl_null));
9073  memset(repl_repl, false, sizeof(repl_repl));
9074 
9075  /* Extract the current options */
9076  datum = SysCacheGetAttr(ATTNAME,
9077  tuple,
9079  &isnull);
9080  if (isnull)
9081  datum = PointerGetDatum(NULL);
9082 
9083  /* Transform the options */
9085  datum,
9086  options,
9087  fdw->fdwvalidator);
9088 
9089  if (PointerIsValid(DatumGetPointer(datum)))
9090  repl_val[Anum_pg_attribute_attfdwoptions - 1] = datum;
9091  else
9092  repl_null[Anum_pg_attribute_attfdwoptions - 1] = true;
9093 
9094  repl_repl[Anum_pg_attribute_attfdwoptions - 1] = true;
9095 
9096  /* Everything looks good - update the tuple */
9097 
9098  newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrel),
9099  repl_val, repl_null, repl_repl);
9100 
9101  CatalogTupleUpdate(attrel, &newtuple->t_self, newtuple);
9102 
9104  RelationGetRelid(rel),
9105  atttableform->attnum);
9107  RelationGetRelid(rel), attnum);
9108 
9109  ReleaseSysCache(tuple);
9110 
9111  heap_close(attrel, RowExclusiveLock);
9112 
9113  heap_freetuple(newtuple);
9114 
9115  return address;
9116 }
#define NIL
Definition: pg_list.h:69
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define RelationGetDescr(relation)
Definition: rel.h:425
Datum transformGenericOptions(Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
Definition: foreigncmds.c:109
#define PointerGetDatum(X)
Definition: postgres.h:564
#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:1374
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:149
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:433
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
Oid rd_id
Definition: rel.h:115
ForeignServer * GetForeignServer(Oid serverid)
Definition: foreign.c:93
uintptr_t Datum
Definition: postgres.h:374
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1083
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1245
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
HeapTuple SearchSysCacheAttName(Oid relid, const char *attname)
Definition: syscache.c:1171
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
#define Anum_pg_attribute_attfdwoptions
Definition: pg_attribute.h:212
#define DatumGetPointer(X)
Definition: postgres.h:557
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define ForeignTableRelationId
#define Natts_pg_attribute
Definition: pg_attribute.h:191
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:793
#define PointerIsValid(pointer)
Definition: c.h:522
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:413
static ObjectAddress ATExecAlterColumnType ( AlteredTableInfo tab,
Relation  rel,
AlterTableCmd cmd,
LOCKMODE  lockmode 
)
static

Definition at line 8612 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, tupleDesc::attrs, 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, NULL, ObjectAddressSubSet, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, OCLASS_AMOP, OCLASS_AMPROC, OCLASS_CAST, OCLASS_CLASS, OCLASS_COLLATION, OCLASS_CONSTRAINT, OCLASS_CONVERSION, OCLASS_DATABASE, OCLASS_DEFACL, OCLASS_DEFAULT, OCLASS_EXTENSION, OCLASS_FDW, OCLASS_FOREIGN_SERVER, OCLASS_LANGUAGE, OCLASS_LARGEOBJECT, OCLASS_OPCLASS, OCLASS_OPERATOR, OCLASS_OPFAMILY, OCLASS_POLICY, OCLASS_PROC, OCLASS_REWRITE, OCLASS_ROLE, OCLASS_SCHEMA, OCLASS_TBLSPACE, 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(), ColumnDef::typeName, typenameType(), and TypeRelationId.

Referenced by ATExecCmd().

8614 {
8615  char *colName = cmd->name;
8616  ColumnDef *def = (ColumnDef *) cmd->def;
8617  TypeName *typeName = def->typeName;
8618  HeapTuple heapTup;
8619  Form_pg_attribute attTup;
8620  AttrNumber attnum;
8621  HeapTuple typeTuple;
8622  Form_pg_type tform;
8623  Oid targettype;
8624  int32 targettypmod;
8625  Oid targetcollid;
8626  Node *defaultexpr;
8627  Relation attrelation;
8628  Relation depRel;
8629  ScanKeyData key[3];
8630  SysScanDesc scan;
8631  HeapTuple depTup;
8632  ObjectAddress address;
8633 
8635 
8636  /* Look up the target column */
8637  heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
8638  if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
8639  ereport(ERROR,
8640  (errcode(ERRCODE_UNDEFINED_COLUMN),
8641  errmsg("column \"%s\" of relation \"%s\" does not exist",
8642  colName, RelationGetRelationName(rel))));
8643  attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
8644  attnum = attTup->attnum;
8645 
8646  /* Check for multiple ALTER TYPE on same column --- can't cope */
8647  if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
8648  attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
8649  ereport(ERROR,
8650  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8651  errmsg("cannot alter type of column \"%s\" twice",
8652  colName)));
8653 
8654  /* Look up the target type (should not fail, since prep found it) */
8655  typeTuple = typenameType(NULL, typeName, &targettypmod);
8656  tform = (Form_pg_type) GETSTRUCT(typeTuple);
8657  targettype = HeapTupleGetOid(typeTuple);
8658  /* And the collation */
8659  targetcollid = GetColumnDefCollation(NULL, def, targettype);
8660 
8661  /*
8662  * If there is a default expression for the column, get it and ensure we
8663  * can coerce it to the new datatype. (We must do this before changing
8664  * the column type, because build_column_default itself will try to
8665  * coerce, and will not issue the error message we want if it fails.)
8666  *
8667  * We remove any implicit coercion steps at the top level of the old
8668  * default expression; this has been agreed to satisfy the principle of
8669  * least surprise. (The conversion to the new column type should act like
8670  * it started from what the user sees as the stored expression, and the
8671  * implicit coercions aren't going to be shown.)
8672  */
8673  if (attTup->atthasdef)
8674  {
8675  defaultexpr = build_column_default(rel, attnum);
8676  Assert(defaultexpr);
8677  defaultexpr = strip_implicit_coercions(defaultexpr);
8678  defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
8679  defaultexpr, exprType(defaultexpr),
8680  targettype, targettypmod,
8683  -1);
8684  if (defaultexpr == NULL)
8685  ereport(ERROR,
8686  (errcode(ERRCODE_DATATYPE_MISMATCH),
8687  errmsg("default for column \"%s\" cannot be cast automatically to type %s",
8688  colName, format_type_be(targettype))));
8689  }
8690  else
8691  defaultexpr = NULL;
8692 
8693  /*
8694  * Find everything that depends on the column (constraints, indexes, etc),
8695  * and record enough information to let us recreate the objects.
8696  *
8697  * The actual recreation does not happen here, but only after we have
8698  * performed all the individual ALTER TYPE operations. We have to save
8699  * the info before executing ALTER TYPE, though, else the deparser will
8700  * get confused.
8701  *
8702  * There could be multiple entries for the same object, so we must check
8703  * to ensure we process each one only once. Note: we assume that an index
8704  * that implements a constraint will not show a direct dependency on the
8705  * column.
8706  */
8708 
8709  ScanKeyInit(&key[0],
8711  BTEqualStrategyNumber, F_OIDEQ,
8713  ScanKeyInit(&key[1],
8715  BTEqualStrategyNumber, F_OIDEQ,
8717  ScanKeyInit(&key[2],
8719  BTEqualStrategyNumber, F_INT4EQ,
8720  Int32GetDatum((int32) attnum));
8721 
8722  scan = systable_beginscan(depRel, DependReferenceIndexId, true,
8723  NULL, 3, key);
8724 
8725  while (HeapTupleIsValid(depTup = systable_getnext(scan)))
8726  {
8727  Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
8728  ObjectAddress foundObject;
8729 
8730  /* We don't expect any PIN dependencies on columns */
8731  if (foundDep->deptype == DEPENDENCY_PIN)
8732  elog(ERROR, "cannot alter type of a pinned column");
8733 
8734  foundObject.classId = foundDep->classid;
8735  foundObject.objectId = foundDep->objid;
8736  foundObject.objectSubId = foundDep->objsubid;
8737 
8738  switch (getObjectClass(&foundObject))
8739  {
8740  case OCLASS_CLASS:
8741  {
8742  char relKind = get_rel_relkind(foundObject.objectId);
8743 
8744  if (relKind == RELKIND_INDEX)
8745  {
8746  Assert(foundObject.objectSubId == 0);
8747  if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
8748  {
8750  foundObject.objectId);
8752  pg_get_indexdef_string(foundObject.objectId));
8753  }
8754  }
8755  else if (relKind == RELKIND_SEQUENCE)
8756  {
8757  /*
8758  * This must be a SERIAL column's sequence. We need
8759  * not do anything to it.
8760  */
8761  Assert(foundObject.objectSubId == 0);
8762  }
8763  else
8764  {
8765  /* Not expecting any other direct dependencies... */
8766  elog(ERROR, "unexpected object depending on column: %s",
8767  getObjectDescription(&foundObject));
8768  }
8769  break;
8770  }
8771 
8772  case OCLASS_CONSTRAINT:
8773  Assert(foundObject.objectSubId == 0);
8775  foundObject.objectId))
8776  {
8777  char *defstring = pg_get_constraintdef_command(foundObject.objectId);
8778 
8779  /*
8780  * Put NORMAL dependencies at the front of the list and
8781  * AUTO dependencies at the back. This makes sure that
8782  * foreign-key constraints depending on this column will
8783  * be dropped before unique or primary-key constraints of
8784  * the column; which we must have because the FK
8785  * constraints depend on the indexes belonging to the
8786  * unique constraints.
8787  */
8788  if (foundDep->deptype == DEPENDENCY_NORMAL)
8789  {
8790  tab->changedConstraintOids =
8791  lcons_oid(foundObject.objectId,
8792  tab->changedConstraintOids);
8793  tab->changedConstraintDefs =
8794  lcons(defstring,
8795  tab->changedConstraintDefs);
8796  }
8797  else
8798  {
8799  tab->changedConstraintOids =
8801  foundObject.objectId);
8802  tab->changedConstraintDefs =
8804  defstring);
8805  }
8806  }
8807  break;
8808 
8809  case OCLASS_REWRITE:
8810  /* XXX someday see if we can cope with revising views */
8811  ereport(ERROR,
8812  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8813  errmsg("cannot alter type of a column used by a view or rule"),
8814  errdetail("%s depends on column \"%s\"",
8815  getObjectDescription(&foundObject),
8816  colName)));
8817  break;
8818 
8819  case OCLASS_TRIGGER:
8820 
8821  /*
8822  * A trigger can depend on a column because the column is
8823  * specified as an update target, or because the column is
8824  * used in the trigger's WHEN condition. The first case would
8825  * not require any extra work, but the second case would
8826  * require updating the WHEN expression, which will take a
8827  * significant amount of new code. Since we can't easily tell
8828  * which case applies, we punt for both. FIXME someday.
8829  */
8830  ereport(ERROR,
8831  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8832  errmsg("cannot alter type of a column used in a trigger definition"),
8833  errdetail("%s depends on column \"%s\"",
8834  getObjectDescription(&foundObject),
8835  colName)));
8836  break;
8837 
8838  case OCLASS_POLICY:
8839 
8840  /*
8841  * A policy can depend on a column because the column is
8842  * specified in the policy's USING or WITH CHECK qual
8843  * expressions. It might be possible to rewrite and recheck
8844  * the policy expression, but punt for now. It's certainly
8845  * easy enough to remove and recreate the policy; still, FIXME
8846  * someday.
8847  */
8848  ereport(ERROR,
8849  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8850  errmsg("cannot alter type of a column used in a policy definition"),
8851  errdetail("%s depends on column \"%s\"",
8852  getObjectDescription(&foundObject),
8853  colName)));
8854  break;
8855 
8856  case OCLASS_DEFAULT:
8857 
8858  /*
8859  * Ignore the column's default expression, since we will fix
8860  * it below.
8861  */
8862  Assert(defaultexpr);
8863  break;
8864 
8865  case OCLASS_PROC:
8866  case OCLASS_TYPE:
8867  case OCLASS_CAST:
8868  case OCLASS_COLLATION:
8869  case OCLASS_CONVERSION:
8870  case OCLASS_LANGUAGE:
8871  case OCLASS_LARGEOBJECT:
8872  case OCLASS_OPERATOR:
8873  case OCLASS_OPCLASS:
8874  case OCLASS_OPFAMILY:
8875  case OCLASS_AMOP:
8876  case OCLASS_AMPROC:
8877  case OCLASS_SCHEMA:
8878  case OCLASS_TSPARSER:
8879  case OCLASS_TSDICT:
8880  case OCLASS_TSTEMPLATE:
8881  case OCLASS_TSCONFIG:
8882  case OCLASS_ROLE:
8883  case OCLASS_DATABASE:
8884  case OCLASS_TBLSPACE:
8885  case OCLASS_FDW:
8886  case OCLASS_FOREIGN_SERVER:
8887  case OCLASS_USER_MAPPING:
8888  case OCLASS_DEFACL:
8889  case OCLASS_EXTENSION:
8890 
8891  /*
8892  * We don't expect any of these sorts of objects to depend on
8893  * a column.
8894  */
8895  elog(ERROR, "unexpected object depending on column: %s",
8896  getObjectDescription(&foundObject));
8897  break;
8898 
8899  default:
8900  elog(ERROR, "unrecognized object class: %u",
8901  foundObject.classId);
8902  }
8903  }
8904 
8905  systable_endscan(scan);
8906 
8907  /*
8908  * Now scan for dependencies of this column on other things. The only
8909  * thing we should find is the dependency on the column datatype, which we
8910  * want to remove, and possibly a collation dependency.
8911  */
8912  ScanKeyInit(&key[0],
8914  BTEqualStrategyNumber, F_OIDEQ,
8916  ScanKeyInit(&key[1],
8918  BTEqualStrategyNumber, F_OIDEQ,
8920  ScanKeyInit(&key[2],
8922  BTEqualStrategyNumber, F_INT4EQ,
8923  Int32GetDatum((int32) attnum));
8924 
8925  scan = systable_beginscan(depRel, DependDependerIndexId, true,
8926  NULL, 3, key);
8927 
8928  while (HeapTupleIsValid(depTup = systable_getnext(scan)))
8929  {
8930  Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
8931 
8932  if (foundDep->deptype != DEPENDENCY_NORMAL)
8933  elog(ERROR, "found unexpected dependency type '%c'",
8934  foundDep->deptype);
8935  if (!(foundDep->refclassid == TypeRelationId &&
8936  foundDep->refobjid == attTup->atttypid) &&
8937  !(foundDep->refclassid == CollationRelationId &&
8938  foundDep->refobjid == attTup->attcollation))
8939  elog(ERROR, "found unexpected dependency for column");
8940 
8941  CatalogTupleDelete(depRel, &depTup->t_self);
8942  }
8943 
8944  systable_endscan(scan);
8945 
8946  heap_close(depRel, RowExclusiveLock);
8947 
8948  /*
8949  * Here we go --- change the recorded column type and collation. (Note
8950  * heapTup is a copy of the syscache entry, so okay to scribble on.)
8951  */
8952  attTup->atttypid = targettype;
8953  attTup->atttypmod = targettypmod;
8954  attTup->attcollation = targetcollid;
8955  attTup->attndims = list_length(typeName->arrayBounds);
8956  attTup->attlen = tform->typlen;
8957  attTup->attbyval = tform->typbyval;
8958  attTup->attalign = tform->typalign;
8959  attTup->attstorage = tform->typstorage;
8960 
8961  ReleaseSysCache(typeTuple);
8962 
8963  CatalogTupleUpdate(attrelation, &heapTup->t_self, heapTup);
8964 
8965  heap_close(attrelation, RowExclusiveLock);
8966 
8967  /* Install dependencies on new datatype and collation */
8968  add_column_datatype_dependency(RelationGetRelid(rel), attnum, targettype);
8969  add_column_collation_dependency(RelationGetRelid(rel), attnum, targetcollid);
8970 
8971  /*
8972  * Drop any pg_statistic entry for the column, since it's now wrong type
8973  */
8974  RemoveStatistics(RelationGetRelid(rel), attnum);
8975 
8977  RelationGetRelid(rel), attnum);
8978 
8979  /*
8980  * Update the default, if present, by brute force --- remove and re-add
8981  * the default. Probably unsafe to take shortcuts, since the new version
8982  * may well have additional dependencies. (It's okay to do this now,
8983  * rather than after other ALTER TYPE commands, since the default won't
8984  * depend on other column types.)
8985  */
8986  if (defaultexpr)
8987  {
8988  /* Must make new row visible since it will be updated again */
8990 
8991  /*
8992  * We use RESTRICT here for safety, but at present we do not expect
8993  * anything to depend on the default.
8994  */
8995  RemoveAttrDefault(RelationGetRelid(rel), attnum, DROP_RESTRICT, true,
8996  true);
8997 
8998  StoreAttrDefault(rel, attnum, defaultexpr, true);
8999  }
9000 
9002  RelationGetRelid(rel), attnum);
9003 
9004  /* Cleanup */
9005  heap_freetuple(heapTup);
9006 
9007  return address;
9008 }
#define Anum_pg_depend_refobjid
Definition: pg_depend.h:72
#define Anum_pg_depend_refobjsubid
Definition: pg_depend.h:73
#define Anum_pg_depend_refclassid
Definition: pg_depend.h:71
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:493
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:247
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1769
#define RelationRelationId
Definition: pg_class.h:29
#define DependReferenceIndexId
Definition: indexing.h:147
#define DependDependerIndexId
Definition: indexing.h:145
#define DependRelationId
Definition: pg_depend.h:29
Form_pg_attribute * attrs
Definition: tupdesc.h:74
char * pg_get_indexdef_string(Oid indexrelid)
Definition: ruleutils.c:1114
Definition: nodes.h:508
List * changedConstraintDefs
Definition: tablecmds.c:173
#define AttributeRelationId
Definition: pg_attribute.h:33
int errcode(int sqlerrcode)
Definition: elog.c:575
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:255
List * lcons_oid(Oid datum, List *list)
Definition: list.c:295
#define heap_close(r, l)
Definition: heapam.h:97
FormData_pg_type * Form_pg_type
Definition: pg_type.h:233
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
unsigned int Oid
Definition: postgres_ext.h:31
#define TypeRelationId
Definition: pg_type.h:34
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
ObjectClass getObjectClass(const ObjectAddress *object)
Definition: dependency.c:2312
SysScanDesc systable_beginscan(