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, bool child_is_partition)
 
static void StoreCatalogInheritance1 (Oid relationId, Oid parentOid, int16 seqNumber, Relation inhRelation, bool child_is_partition)
 
static int findAttrByName (const char *attributeName, List *schema)
 
static void AlterIndexNamespaces (Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
 
static void AlterSeqNamespaces (Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved, LOCKMODE lockmode)
 
static ObjectAddress ATExecAlterConstraint (Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
 
static ObjectAddress ATExecValidateConstraint (Relation rel, char *constrName, bool recurse, bool recursing, LOCKMODE lockmode)
 
static int transformColumnNameList (Oid relId, List *colList, int16 *attnums, Oid *atttypids)
 
static int transformFkeyGetPrimaryKey (Relation pkrel, Oid *indexOid, List **attnamelist, int16 *attnums, Oid *atttypids, Oid *opclasses)
 
static Oid transformFkeyCheckAttrs (Relation pkrel, int numattrs, int16 *attnums, Oid *opclasses)
 
static void checkFkeyPermissions (Relation rel, int16 *attnums, int natts)
 
static CoercionPathType findFkeyCast (Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
 
static void validateCheckConstraint (Relation rel, HeapTuple constrtup)
 
static void validateForeignKeyConstraint (char *conname, Relation rel, Relation pkrel, Oid pkindOid, Oid constraintOid)
 
static void createForeignKeyTriggers (Relation rel, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid)
 
static void ATController (AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
 
static void ATPrepCmd (List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
 
static void ATRewriteCatalogs (List **wqueue, LOCKMODE lockmode)
 
static void ATExecCmd (List **wqueue, AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static void ATRewriteTables (AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode)
 
static void ATRewriteTable (AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode)
 
static AlteredTableInfoATGetQueueEntry (List **wqueue, Relation rel)
 
static void ATSimplePermissions (Relation rel, int allowed_targets)
 
static void ATWrongRelkindError (Relation rel, int allowed_targets)
 
static void ATSimpleRecursion (List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode)
 
static void ATTypedTableRecursion (List **wqueue, Relation rel, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static Listfind_typed_table_dependencies (Oid typeOid, const char *typeName, DropBehavior behavior)
 
static void ATPrepAddColumn (List **wqueue, Relation rel, bool recurse, bool recursing, bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static ObjectAddress ATExecAddColumn (List **wqueue, AlteredTableInfo *tab, Relation rel, ColumnDef *colDef, bool isOid, bool recurse, bool recursing, bool if_not_exists, LOCKMODE lockmode)
 
static bool check_for_column_name_collision (Relation rel, const char *colname, bool if_not_exists)
 
static void add_column_datatype_dependency (Oid relid, int32 attnum, Oid typid)
 
static void add_column_collation_dependency (Oid relid, int32 attnum, Oid collid)
 
static void ATPrepAddOids (List **wqueue, Relation rel, bool recurse, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static void ATPrepDropNotNull (Relation rel, bool recurse, bool recursing)
 
static ObjectAddress ATExecDropNotNull (Relation rel, const char *colName, LOCKMODE lockmode)
 
static void ATPrepSetNotNull (Relation rel, bool recurse, bool recursing)
 
static ObjectAddress ATExecSetNotNull (AlteredTableInfo *tab, Relation rel, const char *colName, LOCKMODE lockmode)
 
static ObjectAddress ATExecColumnDefault (Relation rel, const char *colName, Node *newDefault, LOCKMODE lockmode)
 
static ObjectAddress ATExecAddIdentity (Relation rel, const char *colName, Node *def, LOCKMODE lockmode)
 
static ObjectAddress ATExecSetIdentity (Relation rel, const char *colName, Node *def, LOCKMODE lockmode)
 
static ObjectAddress ATExecDropIdentity (Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode)
 
static void ATPrepSetStatistics (Relation rel, const char *colName, 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.

Referenced by ATPrepCmd().

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

Definition at line 142 of file tablecmds.c.

Referenced by ATPrepCmd().

#define AT_PASS_MISC   8 /* other stuff */

Definition at line 151 of file tablecmds.c.

Referenced by ATPrepCmd().

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

Definition at line 145 of file tablecmds.c.

Referenced by ATPostAlterTypeParse().

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

Definition at line 144 of file tablecmds.c.

Referenced by ATPostAlterTypeParse().

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

Definition at line 141 of file tablecmds.c.

Referenced by ATPrepCmd().

#define ATT_COMPOSITE_TYPE   0x0010

Definition at line 283 of file tablecmds.c.

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

#define ATT_INDEX   0x0008

Definition at line 282 of file tablecmds.c.

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

#define ATT_MATVIEW   0x0004

Definition at line 281 of file tablecmds.c.

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

#define ATT_VIEW   0x0002

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

5525 {
5526  ObjectAddress myself,
5527  referenced;
5528 
5529  /* We know the default collation is pinned, so don't bother recording it */
5530  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
5531  {
5532  myself.classId = RelationRelationId;
5533  myself.objectId = relid;
5534  myself.objectSubId = attnum;
5535  referenced.classId = CollationRelationId;
5536  referenced.objectId = collid;
5537  referenced.objectSubId = 0;
5538  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
5539  }
5540 }
#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:538
#define DEFAULT_COLLATION_OID
Definition: pg_collation.h:74
#define CollationRelationId
Definition: pg_collation.h:30
static void add_column_datatype_dependency ( Oid  relid,
int32  attnum,
Oid  typid 
)
static

Definition at line 5506 of file tablecmds.c.

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

Referenced by ATExecAddColumn(), and ATExecAlterColumnType().

5507 {
5508  ObjectAddress myself,
5509  referenced;
5510 
5511  myself.classId = RelationRelationId;
5512  myself.objectId = relid;
5513  myself.objectSubId = attnum;
5514  referenced.classId = TypeRelationId;
5515  referenced.objectId = typid;
5516  referenced.objectSubId = 0;
5517  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
5518 }
#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 12608 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().

12610 {
12611  List *indexList;
12612  ListCell *l;
12613 
12614  indexList = RelationGetIndexList(rel);
12615 
12616  foreach(l, indexList)
12617  {
12618  Oid indexOid = lfirst_oid(l);
12619  ObjectAddress thisobj;
12620 
12621  thisobj.classId = RelationRelationId;
12622  thisobj.objectId = indexOid;
12623  thisobj.objectSubId = 0;
12624 
12625  /*
12626  * Note: currently, the index will not have its own dependency on the
12627  * namespace, so we don't need to do changeDependencyFor(). There's no
12628  * row type in pg_type, either.
12629  *
12630  * XXX this objsMoved test may be pointless -- surely we have a single
12631  * dependency link from a relation to each index?
12632  */
12633  if (!object_address_present(&thisobj, objsMoved))
12634  {
12635  AlterRelationNamespaceInternal(classRel, indexOid,
12636  oldNspOid, newNspOid,
12637  false, objsMoved);
12638  add_exact_object_address(&thisobj, objsMoved);
12639  }
12640  }
12641 
12642  list_free(indexList);
12643 }
#define RelationRelationId
Definition: pg_class.h:29
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
Definition: dependency.c:2154
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2094
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:12538
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4338
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 12538 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().

12542 {
12543  HeapTuple classTup;
12544  Form_pg_class classForm;
12545  ObjectAddress thisobj;
12546  bool already_done = false;
12547 
12548  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
12549  if (!HeapTupleIsValid(classTup))
12550  elog(ERROR, "cache lookup failed for relation %u", relOid);
12551  classForm = (Form_pg_class) GETSTRUCT(classTup);
12552 
12553  Assert(classForm->relnamespace == oldNspOid);
12554 
12555  thisobj.classId = RelationRelationId;
12556  thisobj.objectId = relOid;
12557  thisobj.objectSubId = 0;
12558 
12559  /*
12560  * If the object has already been moved, don't move it again. If it's
12561  * already in the right place, don't move it, but still fire the object
12562  * access hook.
12563  */
12564  already_done = object_address_present(&thisobj, objsMoved);
12565  if (!already_done && oldNspOid != newNspOid)
12566  {
12567  /* check for duplicate name (more friendly than unique-index failure) */
12568  if (get_relname_relid(NameStr(classForm->relname),
12569  newNspOid) != InvalidOid)
12570  ereport(ERROR,
12571  (errcode(ERRCODE_DUPLICATE_TABLE),
12572  errmsg("relation \"%s\" already exists in schema \"%s\"",
12573  NameStr(classForm->relname),
12574  get_namespace_name(newNspOid))));
12575 
12576  /* classTup is a copy, so OK to scribble on */
12577  classForm->relnamespace = newNspOid;
12578 
12579  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
12580 
12581  /* Update dependency on schema if caller said so */
12582  if (hasDependEntry &&
12584  relOid,
12586  oldNspOid,
12587  newNspOid) != 1)
12588  elog(ERROR, "failed to change schema dependency for relation \"%s\"",
12589  NameStr(classForm->relname));
12590  }
12591  if (!already_done)
12592  {
12593  add_exact_object_address(&thisobj, objsMoved);
12594 
12596  }
12597 
12598  heap_freetuple(classTup);
12599 }
#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:2154
int errcode(int sqlerrcode)
Definition: elog.c:575
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2094
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1683
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3038
#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:675
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:161
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:499
#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 12653 of file tablecmds.c.

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

Referenced by AlterTableNamespaceInternal().

12656 {
12657  Relation depRel;
12658  SysScanDesc scan;
12659  ScanKeyData key[2];
12660  HeapTuple tup;
12661 
12662  /*
12663  * SERIAL sequences are those having an auto dependency on one of the
12664  * table's columns (we don't care *which* column, exactly).
12665  */
12667 
12668  ScanKeyInit(&key[0],
12670  BTEqualStrategyNumber, F_OIDEQ,
12672  ScanKeyInit(&key[1],
12674  BTEqualStrategyNumber, F_OIDEQ,
12676  /* we leave refobjsubid unspecified */
12677 
12678  scan = systable_beginscan(depRel, DependReferenceIndexId, true,
12679  NULL, 2, key);
12680 
12681  while (HeapTupleIsValid(tup = systable_getnext(scan)))
12682  {
12683  Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
12684  Relation seqRel;
12685 
12686  /* skip dependencies other than auto dependencies on columns */
12687  if (depForm->refobjsubid == 0 ||
12688  depForm->classid != RelationRelationId ||
12689  depForm->objsubid != 0 ||
12690  !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
12691  continue;
12692 
12693  /* Use relation_open just in case it's an index */
12694  seqRel = relation_open(depForm->objid, lockmode);
12695 
12696  /* skip non-sequence relations */
12697  if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
12698  {
12699  /* No need to keep the lock */
12700  relation_close(seqRel, lockmode);
12701  continue;
12702  }
12703 
12704  /* Fix the pg_class and pg_depend entries */
12705  AlterRelationNamespaceInternal(classRel, depForm->objid,
12706  oldNspOid, newNspOid,
12707  true, objsMoved);
12708 
12709  /*
12710  * Sequences have entries in pg_type. We need to be careful to move
12711  * them to the new namespace, too.
12712  */
12714  newNspOid, false, false, objsMoved);
12715 
12716  /* Now we can close it. Keep the lock till end of transaction. */
12717  relation_close(seqRel, NoLock);
12718  }
12719 
12720  systable_endscan(scan);
12721 
12723 }
#define Anum_pg_depend_refobjid
Definition: pg_depend.h:72
#define Anum_pg_depend_refclassid
Definition: pg_depend.h:71
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define RelationGetForm(relation)
Definition: rel.h:411
#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:1260
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:328
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:416
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define NoLock
Definition: lockdefs.h:34
FormData_pg_depend * Form_pg_depend
Definition: pg_depend.h:61
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:12538
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:1114
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
#define RelationGetRelid(relation)
Definition: rel.h:417
#define BTEqualStrategyNumber
Definition: stratnum.h:31
void AlterTable ( Oid  relid,
LOCKMODE  lockmode,
AlterTableStmt stmt 
)

Definition at line 3094 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3095 {
3096  Relation rel;
3097 
3098  /* Caller is required to provide an adequate lock. */
3099  rel = relation_open(relid, NoLock);
3100 
3101  CheckTableNotInUse(rel, "ALTER TABLE");
3102 
3103  ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode);
3104 }
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
Definition: tablecmds.c:3412
#define NoLock
Definition: lockdefs.h:34
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3015
bool inh
Definition: primnodes.h:69
RangeVar * relation
Definition: parsenodes.h:1657
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1114
LOCKMODE AlterTableGetLockLevel ( List cmds)

Definition at line 3163 of file tablecmds.c.

References AccessExclusiveLock, AlterTableGetRelOptionsLockLevel(), AT_AddColumn, AT_AddColumnToView, AT_AddConstraint, AT_AddConstraintRecurse, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AddInherit, AT_AddOf, AT_AddOids, AT_AlterColumnGenericOptions, AT_AlterColumnType, AT_AlterConstraint, AT_AttachPartition, AT_ChangeOwner, AT_ClusterOn, AT_ColumnDefault, AT_DetachPartition, AT_DisableRowSecurity, AT_DisableRule, AT_DisableTrig, AT_DisableTrigAll, AT_DisableTrigUser, AT_DropCluster, AT_DropColumn, AT_DropConstraint, AT_DropIdentity, AT_DropInherit, AT_DropNotNull, AT_DropOf, AT_DropOids, AT_EnableAlwaysRule, AT_EnableAlwaysTrig, AT_EnableReplicaRule, AT_EnableReplicaTrig, AT_EnableRowSecurity, AT_EnableRule, AT_EnableTrig, AT_EnableTrigAll, AT_EnableTrigUser, AT_ForceRowSecurity, AT_GenericOptions, AT_NoForceRowSecurity, AT_ProcessedConstraint, AT_ReAddConstraint, AT_ReplaceRelOptions, AT_ReplicaIdentity, AT_ResetOptions, AT_ResetRelOptions, AT_SetIdentity, AT_SetLogged, AT_SetNotNull, AT_SetOptions, AT_SetRelOptions, AT_SetStatistics, AT_SetStorage, AT_SetTableSpace, AT_SetUnLogged, AT_ValidateConstraint, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, AlterTableCmd::def, elog, ERROR, IsA, lfirst, ShareRowExclusiveLock, ShareUpdateExclusiveLock, and AlterTableCmd::subtype.

Referenced by AlterTableInternal(), and ProcessUtilitySlow().

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

Definition at line 3118 of file tablecmds.c.

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

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

3119 {
3120  Relation rel;
3121  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
3122 
3123  rel = relation_open(relid, lockmode);
3124 
3126 
3127  ATController(NULL, rel, cmds, recurse, lockmode);
3128 }
int LOCKMODE
Definition: lockdefs.h:26
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
Definition: tablecmds.c:3412
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:3163
#define NULL
Definition: c.h:229
void EventTriggerAlterTableRelid(Oid objectId)
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1114
Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)

Definition at line 3044 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3045 {
3046  return RangeVarGetRelidExtended(stmt->relation, lockmode, stmt->missing_ok, false,
3048  (void *) stmt);
3049 }
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:13015
RangeVar * relation
Definition: parsenodes.h:1657
Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

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

10638 {
10639  List *relations = NIL;
10640  ListCell *l;
10641  ScanKeyData key[1];
10642  Relation rel;
10643  HeapScanDesc scan;
10644  HeapTuple tuple;
10645  Oid orig_tablespaceoid;
10646  Oid new_tablespaceoid;
10647  List *role_oids = roleSpecsToIds(stmt->roles);
10648 
10649  /* Ensure we were not asked to move something we can't */
10650  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
10651  stmt->objtype != OBJECT_MATVIEW)
10652  ereport(ERROR,
10653  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
10654  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
10655 
10656  /* Get the orig and new tablespace OIDs */
10657  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
10658  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
10659 
10660  /* Can't move shared relations in to or out of pg_global */
10661  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
10662  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
10663  new_tablespaceoid == GLOBALTABLESPACE_OID)
10664  ereport(ERROR,
10665  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
10666  errmsg("cannot move relations in to or out of pg_global tablespace")));
10667 
10668  /*
10669  * Must have CREATE rights on the new tablespace, unless it is the
10670  * database default tablespace (which all users implicitly have CREATE
10671  * rights on).
10672  */
10673  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
10674  {
10675  AclResult aclresult;
10676 
10677  aclresult = pg_tablespace_aclcheck(new_tablespaceoid, GetUserId(),
10678  ACL_CREATE);
10679  if (aclresult != ACLCHECK_OK)
10681  get_tablespace_name(new_tablespaceoid));
10682  }
10683 
10684  /*
10685  * Now that the checks are done, check if we should set either to
10686  * InvalidOid because it is our database's default tablespace.
10687  */
10688  if (orig_tablespaceoid == MyDatabaseTableSpace)
10689  orig_tablespaceoid = InvalidOid;
10690 
10691  if (new_tablespaceoid == MyDatabaseTableSpace)
10692  new_tablespaceoid = InvalidOid;
10693 
10694  /* no-op */
10695  if (orig_tablespaceoid == new_tablespaceoid)
10696  return new_tablespaceoid;
10697 
10698  /*
10699  * Walk the list of objects in the tablespace and move them. This will
10700  * only find objects in our database, of course.
10701  */
10702  ScanKeyInit(&key[0],
10704  BTEqualStrategyNumber, F_OIDEQ,
10705  ObjectIdGetDatum(orig_tablespaceoid));
10706 
10708  scan = heap_beginscan_catalog(rel, 1, key);
10709  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
10710  {
10711  Oid relOid = HeapTupleGetOid(tuple);
10712  Form_pg_class relForm;
10713 
10714  relForm = (Form_pg_class) GETSTRUCT(tuple);
10715 
10716  /*
10717  * Do not move objects in pg_catalog as part of this, if an admin
10718  * really wishes to do so, they can issue the individual ALTER
10719  * commands directly.
10720  *
10721  * Also, explicitly avoid any shared tables, temp tables, or TOAST
10722  * (TOAST will be moved with the main table).
10723  */
10724  if (IsSystemNamespace(relForm->relnamespace) || relForm->relisshared ||
10725  isAnyTempNamespace(relForm->relnamespace) ||
10726  relForm->relnamespace == PG_TOAST_NAMESPACE)
10727  continue;
10728 
10729  /* Only move the object type requested */
10730  if ((stmt->objtype == OBJECT_TABLE &&
10731  relForm->relkind != RELKIND_RELATION &&
10732  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
10733  (stmt->objtype == OBJECT_INDEX &&
10734  relForm->relkind != RELKIND_INDEX) ||
10735  (stmt->objtype == OBJECT_MATVIEW &&
10736  relForm->relkind != RELKIND_MATVIEW))
10737  continue;
10738 
10739  /* Check if we are only moving objects owned by certain roles */
10740  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
10741  continue;
10742 
10743  /*
10744  * Handle permissions-checking here since we are locking the tables
10745  * and also to avoid doing a bunch of work only to fail part-way. Note
10746  * that permissions will also be checked by AlterTableInternal().
10747  *
10748  * Caller must be considered an owner on the table to move it.
10749  */
10750  if (!pg_class_ownercheck(relOid, GetUserId()))
10752  NameStr(relForm->relname));
10753 
10754  if (stmt->nowait &&
10756  ereport(ERROR,
10757  (errcode(ERRCODE_OBJECT_IN_USE),
10758  errmsg("aborting because lock on relation \"%s.%s\" is not available",
10759  get_namespace_name(relForm->relnamespace),
10760  NameStr(relForm->relname))));
10761  else
10763 
10764  /* Add to our list of objects to move */
10765  relations = lappend_oid(relations, relOid);
10766  }
10767 
10768  heap_endscan(scan);
10770 
10771  if (relations == NIL)
10772  ereport(NOTICE,
10773  (errcode(ERRCODE_NO_DATA_FOUND),
10774  errmsg("no matching relations in tablespace \"%s\" found",
10775  orig_tablespaceoid == InvalidOid ? "(database default)" :
10776  get_tablespace_name(orig_tablespaceoid))));
10777 
10778  /* Everything is locked, loop through and move all of the relations. */
10779  foreach(l, relations)
10780  {
10781  List *cmds = NIL;
10783 
10784  cmd->subtype = AT_SetTableSpace;
10785  cmd->name = stmt->new_tablespacename;
10786 
10787  cmds = lappend(cmds, cmd);
10788 
10790  /* OID is set by AlterTableInternal */
10791  AlterTableInternal(lfirst_oid(l), cmds, false);
10793  }
10794 
10795  return new_tablespaceoid;
10796 }
#define NIL
Definition: pg_list.h:69
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:138
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1380
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4496
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1578
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:165
#define AccessShareLock
Definition: lockdefs.h:36
#define GLOBALTABLESPACE_OID
Definition: pg_tablespace.h:64
Definition: nodes.h:509
int errcode(int sqlerrcode)
Definition: elog.c:575
AlterTableType subtype
Definition: parsenodes.h:1744
#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:538
Oid MyDatabaseTableSpace
Definition: globals.c:78
void EventTriggerAlterTableStart(Node *parsetree)
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:82
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3038
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1399
#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:1794
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
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:557
List * roleSpecsToIds(List *memberNames)
Definition: user.c:1384
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505
#define NULL
Definition: c.h:229
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4546
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition: tablecmds.c:3118
#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:1426
#define NameStr(name)
Definition: c.h:499
#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:3046
#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 12429 of file tablecmds.c.

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

12430 {
12431  Relation rel;
12432  Oid relid;
12433  Oid oldNspOid;
12434  Oid nspOid;
12435  RangeVar *newrv;
12436  ObjectAddresses *objsMoved;
12437  ObjectAddress myself;
12438 
12440  stmt->missing_ok, false,
12442  (void *) stmt);
12443 
12444  if (!OidIsValid(relid))
12445  {
12446  ereport(NOTICE,
12447  (errmsg("relation \"%s\" does not exist, skipping",
12448  stmt->relation->relname)));
12449  return InvalidObjectAddress;
12450  }
12451 
12452  rel = relation_open(relid, NoLock);
12453 
12454  oldNspOid = RelationGetNamespace(rel);
12455 
12456  /* If it's an owned sequence, disallow moving it by itself. */
12457  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
12458  {
12459  Oid tableId;
12460  int32 colId;
12461 
12462  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
12463  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
12464  ereport(ERROR,
12465  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
12466  errmsg("cannot move an owned sequence into another schema"),
12467  errdetail("Sequence \"%s\" is linked to table \"%s\".",
12469  get_rel_name(tableId))));
12470  }
12471 
12472  /* Get and lock schema OID and check its permissions. */
12473  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
12475 
12476  /* common checks on switching namespaces */
12477  CheckSetNamespace(oldNspOid, nspOid);
12478 
12479  objsMoved = new_object_addresses();
12480  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
12481  free_object_addresses(objsMoved);
12482 
12483  ObjectAddressSet(myself, RelationRelationId, relid);
12484 
12485  if (oldschema)
12486  *oldschema = oldNspOid;
12487 
12488  /* close rel, but keep lock until commit */
12489  relation_close(rel, NoLock);
12490 
12491  return myself;
12492 }
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition: pg_depend.c:500
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c: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:1260
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2039
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2310
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
signed int int32
Definition: c.h:256
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:43
void AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:12500
#define NoLock
Definition: lockdefs.h:34
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:13015
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:437
#define ereport(elevel, rest)
Definition: elog.h:122
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition: namespace.c:2818
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:229
#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:1114
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1726
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:419
#define RelationGetNamespace(relation)
Definition: rel.h:444
void AlterTableNamespaceInternal ( Relation  rel,
Oid  oldNspOid,
Oid  nspOid,
ObjectAddresses objsMoved 
)

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

12502 {
12503  Relation classRel;
12504 
12505  Assert(objsMoved != NULL);
12506 
12507  /* OK, modify the pg_class row and pg_depend entry */
12509 
12510  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
12511  nspOid, true, objsMoved);
12512 
12513  /* Fix the table's row type too */
12514  AlterTypeNamespaceInternal(rel->rd_rel->reltype,
12515  nspOid, false, false, objsMoved);
12516 
12517  /* Fix other dependent stuff */
12518  if (rel->rd_rel->relkind == RELKIND_RELATION ||
12519  rel->rd_rel->relkind == RELKIND_MATVIEW ||
12520  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
12521  {
12522  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
12523  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
12524  objsMoved, AccessExclusiveLock);
12525  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
12526  false, objsMoved);
12527  }
12528 
12529  heap_close(classRel, RowExclusiveLock);
12530 }
#define RelationRelationId
Definition: pg_class.h:29
#define RELKIND_MATVIEW
Definition: pg_class.h:165
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c:3491
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:114
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Definition: tablecmds.c:12608
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:12653
#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:1284
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
Definition: tablecmds.c:12538
#define AccessExclusiveLock
Definition: lockdefs.h:46
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RelationGetRelid(relation)
Definition: rel.h:417
static ObjectAddress ATAddCheckConstraint ( List **  wqueue,
AlteredTableInfo tab,
Relation  rel,
Constraint constr,
bool  recurse,
bool  recursing,
bool  is_readd,
LOCKMODE  lockmode 
)
static

Definition at line 6899 of file tablecmds.c.

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

Referenced by ATExecAddConstraint().

6902 {
6903  List *newcons;
6904  ListCell *lcon;
6905  List *children;
6906  ListCell *child;
6908 
6909  /* At top level, permission check was done in ATPrepCmd, else do it */
6910  if (recursing)
6912 
6913  /*
6914  * Call AddRelationNewConstraints to do the work, making sure it works on
6915  * a copy of the Constraint so transformExpr can't modify the original. It
6916  * returns a list of cooked constraints.
6917  *
6918  * If the constraint ends up getting merged with a pre-existing one, it's
6919  * omitted from the returned list, which is what we want: we do not need
6920  * to do any validation work. That can only happen at child tables,
6921  * though, since we disallow merging at the top level.
6922  */
6923  newcons = AddRelationNewConstraints(rel, NIL,
6924  list_make1(copyObject(constr)),
6925  recursing | is_readd, /* allow_merge */
6926  !recursing, /* is_local */
6927  is_readd); /* is_internal */
6928 
6929  /* we don't expect more than one constraint here */
6930  Assert(list_length(newcons) <= 1);
6931 
6932  /* Add each to-be-validated constraint to Phase 3's queue */
6933  foreach(lcon, newcons)
6934  {
6935  CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
6936 
6937  if (!ccon->skip_validation)
6938  {
6939  NewConstraint *newcon;
6940 
6941  newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
6942  newcon->name = ccon->name;
6943  newcon->contype = ccon->contype;
6944  newcon->qual = ccon->expr;
6945 
6946  tab->constraints = lappend(tab->constraints, newcon);
6947  }
6948 
6949  /* Save the actually assigned name if it was defaulted */
6950  if (constr->conname == NULL)
6951  constr->conname = ccon->name;
6952 
6953  ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
6954  }
6955 
6956  /* At this point we must have a locked-down name to use */
6957  Assert(constr->conname != NULL);
6958 
6959  /* Advance command counter in case same table is visited multiple times */
6961 
6962  /*
6963  * If the constraint got merged with an existing constraint, we're done.
6964  * We mustn't recurse to child tables in this case, because they've
6965  * already got the constraint, and visiting them again would lead to an
6966  * incorrect value for coninhcount.
6967  */
6968  if (newcons == NIL)
6969  return address;
6970 
6971  /*
6972  * If adding a NO INHERIT constraint, no need to find our children.
6973  */
6974  if (constr->is_no_inherit)
6975  return address;
6976 
6977  /*
6978  * Propagate to children as appropriate. Unlike most other ALTER
6979  * routines, we have to do this one level of recursion at a time; we can't
6980  * use find_all_inheritors to do it in one pass.
6981  */
6982  children = find_inheritance_children(RelationGetRelid(rel), lockmode);
6983 
6984  /*
6985  * Check if ONLY was specified with ALTER TABLE. If so, allow the
6986  * constraint creation only if there are no children currently. Error out
6987  * otherwise.
6988  */
6989  if (!recurse && children != NIL)
6990  ereport(ERROR,
6991  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6992  errmsg("constraint must be added to child tables too")));
6993 
6994  foreach(child, children)
6995  {
6996  Oid childrelid = lfirst_oid(child);
6997  Relation childrel;
6998  AlteredTableInfo *childtab;
6999 
7000  /* find_inheritance_children already got lock */
7001  childrel = heap_open(childrelid, NoLock);
7002  CheckTableNotInUse(childrel, "ALTER TABLE");
7003 
7004  /* Find or create work queue entry for this table */
7005  childtab = ATGetQueueEntry(wqueue, childrel);
7006 
7007  /* Recurse to child */
7008  ATAddCheckConstraint(wqueue, childtab, childrel,
7009  constr, recurse, true, is_readd, lockmode);
7010 
7011  heap_close(childrel, NoLock);
7012  }
7013 
7014  return address;
7015 }
#define NIL
Definition: pg_list.h:69
char * name
Definition: tablecmds.c:182
Node * qual
Definition: tablecmds.c:187
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:6899
#define heap_close(r, l)
Definition: heapam.h:97
char * conname
Definition: parsenodes.h:2048
unsigned int Oid
Definition: postgres_ext.h:31
#define ATT_TABLE
Definition: tablecmds.c:279
List * constraints
Definition: tablecmds.c:163
#define list_make1(x1)
Definition: pg_list.h:139
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
static AlteredTableInfo * ATGetQueueEntry(List **wqueue, Relation rel)
Definition: tablecmds.c:4634
bool skip_validation
Definition: heap.h:35
ConstrType contype
Definition: heap.h:30
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3015
#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:878
void CommandCounterIncrement(void)
Definition: xact.c:922
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
bool is_no_inherit
Definition: parsenodes.h:2054
List * find_inheritance_children(Oid parentrelId, LOCKMODE lockmode)
Definition: pg_inherits.c:57
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#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:4671
#define ConstraintRelationId
Definition: pg_constraint.h:29
#define copyObject(obj)
Definition: nodes.h:621
Definition: pg_list.h:45
#define ATT_FOREIGN_TABLE
Definition: tablecmds.c:284
char * name
Definition: heap.h:32
#define RelationGetRelid(relation)
Definition: rel.h:417
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal)
Definition: heap.c:2206
#define lfirst_oid(lc)
Definition: pg_list.h:108
static ObjectAddress ATAddForeignKeyConstraint ( AlteredTableInfo tab,
Relation  rel,
Constraint fkconstraint,
LOCKMODE  lockmode 
)
static

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

7028 {
7029  Relation pkrel;
7030  int16 pkattnum[INDEX_MAX_KEYS];
7031  int16 fkattnum[INDEX_MAX_KEYS];
7032  Oid pktypoid[INDEX_MAX_KEYS];
7033  Oid fktypoid[INDEX_MAX_KEYS];
7034  Oid opclasses[INDEX_MAX_KEYS];
7035  Oid pfeqoperators[INDEX_MAX_KEYS];
7036  Oid ppeqoperators[INDEX_MAX_KEYS];
7037  Oid ffeqoperators[INDEX_MAX_KEYS];
7038  int i;
7039  int numfks,
7040  numpks;
7041  Oid indexOid;
7042  Oid constrOid;
7043  bool old_check_ok;
7044  ObjectAddress address;
7045  ListCell *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
7046 
7047  /*
7048  * Grab ShareRowExclusiveLock on the pk table, so that someone doesn't
7049  * delete rows out from under us.
7050  */
7051  if (OidIsValid(fkconstraint->old_pktable_oid))
7052  pkrel = heap_open(fkconstraint->old_pktable_oid, ShareRowExclusiveLock);
7053  else
7054  pkrel = heap_openrv(fkconstraint->pktable, ShareRowExclusiveLock);
7055 
7056  /*
7057  * Validity checks (permission checks wait till we have the column
7058  * numbers)
7059  */
7060  if (pkrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
7061  ereport(ERROR,
7062  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7063  errmsg("cannot reference partitioned table \"%s\"",
7064  RelationGetRelationName(pkrel))));
7065 
7066  if (pkrel->rd_rel->relkind != RELKIND_RELATION)
7067  ereport(ERROR,
7068  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
7069  errmsg("referenced relation \"%s\" is not a table",
7070  RelationGetRelationName(pkrel))));
7071 
7072  if (!allowSystemTableMods && IsSystemRelation(pkrel))
7073  ereport(ERROR,
7074  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
7075  errmsg("permission denied: \"%s\" is a system catalog",
7076  RelationGetRelationName(pkrel))));
7077 
7078  /*
7079  * References from permanent or unlogged tables to temp tables, and from
7080  * permanent tables to unlogged tables, are disallowed because the
7081  * referenced data can vanish out from under us. References from temp
7082  * tables to any other table type are also disallowed, because other
7083  * backends might need to run the RI triggers on the perm table, but they
7084  * can't reliably see tuples in the local buffers of other backends.
7085  */
7086  switch (rel->rd_rel->relpersistence)
7087  {
7089  if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT)
7090  ereport(ERROR,
7091  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7092  errmsg("constraints on permanent tables may reference only permanent tables")));
7093  break;
7095  if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT
7096  && pkrel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED)
7097  ereport(ERROR,
7098  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7099  errmsg("constraints on unlogged tables may reference only permanent or unlogged tables")));
7100  break;
7101  case RELPERSISTENCE_TEMP:
7102  if (pkrel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
7103  ereport(ERROR,
7104  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7105  errmsg("constraints on temporary tables may reference only temporary tables")));
7106  if (!pkrel->rd_islocaltemp || !rel->rd_islocaltemp)
7107  ereport(ERROR,
7108  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
7109  errmsg("constraints on temporary tables must involve temporary tables of this session")));
7110  break;
7111  }
7112 
7113  /*
7114  * Look up the referencing attributes to make sure they exist, and record
7115  * their attnums and type OIDs.
7116  */
7117  MemSet(pkattnum, 0, sizeof(pkattnum));
7118  MemSet(fkattnum, 0, sizeof(fkattnum));
7119  MemSet(pktypoid, 0, sizeof(pktypoid));
7120  MemSet(fktypoid, 0, sizeof(fktypoid));
7121  MemSet(opclasses, 0, sizeof(opclasses));
7122  MemSet(pfeqoperators, 0, sizeof(pfeqoperators));
7123  MemSet(ppeqoperators, 0, sizeof(ppeqoperators));
7124  MemSet(ffeqoperators, 0, sizeof(ffeqoperators));
7125 
7127  fkconstraint->fk_attrs,
7128  fkattnum, fktypoid);
7129 
7130  /*
7131  * If the attribute list for the referenced table was omitted, lookup the
7132  * definition of the primary key and use it. Otherwise, validate the
7133  * supplied attribute list. In either case, discover the index OID and
7134  * index opclasses, and the attnums and type OIDs of the attributes.
7135  */
7136  if (fkconstraint->pk_attrs == NIL)
7137  {
7138  numpks = transformFkeyGetPrimaryKey(pkrel, &indexOid,
7139  &fkconstraint->pk_attrs,
7140  pkattnum, pktypoid,
7141  opclasses);
7142  }
7143  else
7144  {
7145  numpks = transformColumnNameList(RelationGetRelid(pkrel),
7146  fkconstraint->pk_attrs,
7147  pkattnum, pktypoid);
7148  /* Look for an index matching the column list */
7149  indexOid = transformFkeyCheckAttrs(pkrel, numpks, pkattnum,
7150  opclasses);
7151  }
7152 
7153  /*
7154  * Now we can check permissions.
7155  */
7156  checkFkeyPermissions(pkrel, pkattnum, numpks);
7157 
7158  /*
7159  * Look up the equality operators to use in the constraint.
7160  *
7161  * Note that we have to be careful about the difference between the actual
7162  * PK column type and the opclass' declared input type, which might be
7163  * only binary-compatible with it. The declared opcintype is the right
7164  * thing to probe pg_amop with.
7165  */
7166  if (numfks != numpks)
7167  ereport(ERROR,
7168  (errcode(ERRCODE_INVALID_FOREIGN_KEY),
7169  errmsg("number of referencing and referenced columns for foreign key disagree")));
7170 
7171  /*
7172  * On the strength of a previous constraint, we might avoid scanning
7173  * tables to validate this one. See below.
7174  */
7175  old_check_ok = (fkconstraint->old_conpfeqop != NIL);
7176  Assert(!old_check_ok || numfks == list_length(fkconstraint->old_conpfeqop));
7177 
7178  for (i = 0; i < numpks; i++)
7179  {
7180  Oid pktype = pktypoid[i];
7181  Oid fktype = fktypoid[i];
7182  Oid fktyped;
7183  HeapTuple cla_ht;
7184  Form_pg_opclass cla_tup;
7185  Oid amid;
7186  Oid opfamily;
7187  Oid opcintype;
7188  Oid pfeqop;
7189  Oid ppeqop;
7190  Oid ffeqop;
7191  int16 eqstrategy;
7192  Oid pfeqop_right;
7193 
7194  /* We need several fields out of the pg_opclass entry */
7195  cla_ht = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclasses[i]));
7196  if (!HeapTupleIsValid(cla_ht))
7197  elog(ERROR, "cache lookup failed for opclass %u", opclasses[i]);
7198  cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
7199  amid = cla_tup->opcmethod;
7200  opfamily = cla_tup->opcfamily;
7201  opcintype = cla_tup->opcintype;
7202  ReleaseSysCache(cla_ht);
7203 
7204  /*
7205  * Check it's a btree; currently this can never fail since no other
7206  * index AMs support unique indexes. If we ever did have other types
7207  * of unique indexes, we'd need a way to determine which operator
7208  * strategy number is equality. (Is it reasonable to insist that
7209  * every such index AM use btree's number for equality?)
7210  */
7211  if (amid != BTREE_AM_OID)
7212  elog(ERROR, "only b-tree indexes are supported for foreign keys");
7213  eqstrategy = BTEqualStrategyNumber;
7214 
7215  /*
7216  * There had better be a primary equality operator for the index.
7217  * We'll use it for PK = PK comparisons.
7218  */
7219  ppeqop = get_opfamily_member(opfamily, opcintype, opcintype,
7220  eqstrategy);
7221 
7222  if (!OidIsValid(ppeqop))
7223  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
7224  eqstrategy, opcintype, opcintype, opfamily);
7225 
7226  /*
7227  * Are there equality operators that take exactly the FK type? Assume
7228  * we should look through any domain here.
7229  */
7230  fktyped = getBaseType(fktype);
7231 
7232  pfeqop = get_opfamily_member(opfamily, opcintype, fktyped,
7233  eqstrategy);
7234  if (OidIsValid(pfeqop))
7235  {
7236  pfeqop_right = fktyped;
7237  ffeqop = get_opfamily_member(opfamily, fktyped, fktyped,
7238  eqstrategy);
7239  }
7240  else
7241  {
7242  /* keep compiler quiet */
7243  pfeqop_right = InvalidOid;
7244  ffeqop = InvalidOid;
7245  }
7246 
7247  if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
7248  {
7249  /*
7250  * Otherwise, look for an implicit cast from the FK type to the
7251  * opcintype, and if found, use the primary equality operator.
7252  * This is a bit tricky because opcintype might be a polymorphic
7253  * type such as ANYARRAY or ANYENUM; so what we have to test is
7254  * whether the two actual column types can be concurrently cast to
7255  * that type. (Otherwise, we'd fail to reject combinations such
7256  * as int[] and point[].)
7257  */
7258  Oid input_typeids[2];
7259  Oid target_typeids[2];
7260 
7261  input_typeids[0] = pktype;
7262  input_typeids[1] = fktype;
7263  target_typeids[0] = opcintype;
7264  target_typeids[1] = opcintype;
7265  if (can_coerce_type(2, input_typeids, target_typeids,
7267  {
7268  pfeqop = ffeqop = ppeqop;
7269  pfeqop_right = opcintype;
7270  }
7271  }
7272 
7273  if (!(OidIsValid(pfeqop) && OidIsValid(ffeqop)))
7274  ereport(ERROR,
7275  (errcode(ERRCODE_DATATYPE_MISMATCH),
7276  errmsg("foreign key constraint \"%s\" "
7277  "cannot be implemented",
7278  fkconstraint->conname),
7279  errdetail("Key columns \"%s\" and \"%s\" "
7280  "are of incompatible types: %s and %s.",
7281  strVal(list_nth(fkconstraint->fk_attrs, i)),
7282  strVal(list_nth(fkconstraint->pk_attrs, i)),
7283  format_type_be(fktype),
7284  format_type_be(pktype))));
7285 
7286  if (old_check_ok)
7287  {
7288  /*
7289  * When a pfeqop changes, revalidate the constraint. We could
7290  * permit intra-opfamily changes, but that adds subtle complexity
7291  * without any concrete benefit for core types. We need not
7292  * assess ppeqop or ffeqop, which RI_Initial_Check() does not use.
7293  */
7294  old_check_ok = (pfeqop == lfirst_oid(old_pfeqop_item));
7295  old_pfeqop_item = lnext(old_pfeqop_item);
7296  }
7297  if (old_check_ok)
7298  {
7299  Oid old_fktype;
7300  Oid new_fktype;
7301  CoercionPathType old_pathtype;
7302  CoercionPathType new_pathtype;
7303  Oid old_castfunc;
7304  Oid new_castfunc;
7305 
7306  /*
7307  * Identify coercion pathways from each of the old and new FK-side
7308  * column types to the right (foreign) operand type of the pfeqop.
7309  * We may assume that pg_constraint.conkey is not changing.
7310  */
7311  old_fktype = tab->oldDesc->attrs[fkattnum[i] - 1]->atttypid;
7312  new_fktype = fktype;
7313  old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
7314  &old_castfunc);
7315  new_pathtype = findFkeyCast(pfeqop_right, new_fktype,
7316  &new_castfunc);
7317 
7318  /*
7319  * Upon a change to the cast from the FK column to its pfeqop
7320  * operand, revalidate the constraint. For this evaluation, a
7321  * binary coercion cast is equivalent to no cast at all. While
7322  * type implementors should design implicit casts with an eye
7323  * toward consistency of operations like equality, we cannot
7324  * assume here that they have done so.
7325  *
7326  * A function with a polymorphic argument could change behavior
7327  * arbitrarily in response to get_fn_expr_argtype(). Therefore,
7328  * when the cast destination is polymorphic, we only avoid
7329  * revalidation if the input type has not changed at all. Given
7330  * just the core data types and operator classes, this requirement
7331  * prevents no would-be optimizations.
7332  *
7333  * If the cast converts from a base type to a domain thereon, then
7334  * that domain type must be the opcintype of the unique index.
7335  * Necessarily, the primary key column must then be of the domain
7336  * type. Since the constraint was previously valid, all values on
7337  * the foreign side necessarily exist on the primary side and in
7338  * turn conform to the domain. Consequently, we need not treat
7339  * domains specially here.
7340  *
7341  * Since we require that all collations share the same notion of
7342  * equality (which they do, because texteq reduces to bitwise
7343  * equality), we don't compare collation here.
7344  *
7345  * We need not directly consider the PK type. It's necessarily
7346  * binary coercible to the opcintype of the unique index column,
7347  * and ri_triggers.c will only deal with PK datums in terms of
7348  * that opcintype. Changing the opcintype also changes pfeqop.
7349  */
7350  old_check_ok = (new_pathtype == old_pathtype &&
7351  new_castfunc == old_castfunc &&
7352  (!IsPolymorphicType(pfeqop_right) ||
7353  new_fktype == old_fktype));
7354 
7355  }
7356 
7357  pfeqoperators[i] = pfeqop;
7358  ppeqoperators[i] = ppeqop;
7359  ffeqoperators[i] = ffeqop;
7360  }
7361 
7362  /*
7363  * Record the FK constraint in pg_constraint.
7364  */
7365  constrOid = CreateConstraintEntry(fkconstraint->conname,
7366  RelationGetNamespace(rel),
7368  fkconstraint->deferrable,
7369  fkconstraint->initdeferred,
7370  fkconstraint->initially_valid,
7371  RelationGetRelid(rel),
7372  fkattnum,
7373  numfks,
7374  InvalidOid, /* not a domain
7375  * constraint */
7376  indexOid,
7377  RelationGetRelid(pkrel),
7378  pkattnum,
7379  pfeqoperators,
7380  ppeqoperators,
7381  ffeqoperators,
7382  numpks,
7383  fkconstraint->fk_upd_action,
7384  fkconstraint->fk_del_action,
7385  fkconstraint->fk_matchtype,
7386  NULL, /* no exclusion constraint */
7387  NULL, /* no check constraint */
7388  NULL,
7389  NULL,
7390  true, /* islocal */
7391  0, /* inhcount */
7392  true, /* isnoinherit */
7393  false); /* is_internal */
7394  ObjectAddressSet(address, ConstraintRelationId, constrOid);
7395 
7396  /*
7397  * Create the triggers that will enforce the constraint.
7398  */
7399  createForeignKeyTriggers(rel, RelationGetRelid(pkrel), fkconstraint,
7400  constrOid, indexOid);
7401 
7402  /*
7403  * Tell Phase 3 to check that the constraint is satisfied by existing
7404  * rows. We can skip this during table creation, when requested explicitly
7405  * by specifying NOT VALID in an ADD FOREIGN KEY command, and when we're
7406  * recreating a constraint following a SET DATA TYPE operation that did
7407  * not impugn its validity.
7408  */
7409  if (!old_check_ok && !fkconstraint->skip_validation)
7410  {
7411  NewConstraint *newcon;
7412 
7413  newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
7414  newcon->name = fkconstraint->conname;
7415  newcon->contype = CONSTR_FOREIGN;
7416  newcon->refrelid = RelationGetRelid(pkrel);
7417  newcon->refindid = indexOid;
7418  newcon->conid = constrOid;
7419  newcon->qual = (Node *) fkconstraint;
7420 
7421  tab->constraints = lappend(tab->constraints, newcon);
7422  }
7423 
7424  /*
7425  * Close pk table, but keep lock until we've committed.
7426  */
7427  heap_close(pkrel, NoLock);
7428 
7429  return address;
7430 }
signed short int16
Definition: c.h:255
#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:2080
bool IsSystemRelation(Relation relation)
Definition: catalog.c:62
#define RELPERSISTENCE_UNLOGGED
Definition: pg_class.h:171
char fk_matchtype
Definition: parsenodes.h:2077
static int transformColumnNameList(Oid relId, List *colList, int16 *attnums, Oid *atttypids)
Definition: tablecmds.c:7779
#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:509
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
bool initdeferred
Definition: parsenodes.h:2050
#define MemSet(start, val, len)
Definition: c.h:857
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:2076
char * conname
Definition: parsenodes.h:2048
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
static void checkFkeyPermissions(Relation rel, int16 *attnums, int natts)
Definition: tablecmds.c:8091
#define OidIsValid(objectId)
Definition: c.h:538
CoercionPathType
Definition: parse_coerce.h:24
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:152
List * constraints
Definition: tablecmds.c:163
#define RELPERSISTENCE_PERMANENT
Definition: pg_class.h:170
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define IsPolymorphicType(typid)
Definition: pg_type.h:745
bool deferrable
Definition: parsenodes.h:2049
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:437
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:8338
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
Oid old_pktable_oid
Definition: parsenodes.h:2081
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:878
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1312
bool allowSystemTableMods
Definition: globals.c:111
#define InvalidOid
Definition: postgres_ext.h:36
bool initially_valid
Definition: parsenodes.h:2085
static int transformFkeyGetPrimaryKey(Relation pkrel, Oid *indexOid, List **attnamelist, int16 *attnums, Oid *atttypids, Oid *opclasses)
Definition: tablecmds.c:7824
char fk_del_action
Definition: parsenodes.h:2079
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define ShareRowExclusiveLock
Definition: lockdefs.h:42
static CoercionPathType findFkeyCast(Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
Definition: tablecmds.c:8062
#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:7921
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:2074
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2271
#define RELKIND_RELATION
Definition: pg_class.h:160
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:68
bool skip_validation
Definition: parsenodes.h:2084
#define RelationGetRelid(relation)
Definition: rel.h:417
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:2075
#define BTEqualStrategyNumber
Definition: stratnum.h:31
char fk_upd_action
Definition: parsenodes.h:2078
#define lfirst_oid(lc)
Definition: pg_list.h:108
#define RelationGetNamespace(relation)
Definition: rel.h:444
static bool ATColumnChangeRequiresRewrite ( Node expr,
AttrNumber  varattno 
)
static

Definition at line 8945 of file tablecmds.c.

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

Referenced by ATPrepAlterColumnType().

8946 {
8947  Assert(expr != NULL);
8948 
8949  for (;;)
8950  {
8951  /* only one varno, so no need to check that */
8952  if (IsA(expr, Var) &&((Var *) expr)->varattno == varattno)
8953  return false;
8954  else if (IsA(expr, RelabelType))
8955  expr = (Node *) ((RelabelType *) expr)->arg;
8956  else if (IsA(expr, CoerceToDomain))
8957  {
8958  CoerceToDomain *d = (CoerceToDomain *) expr;
8959 
8961  return true;
8962  expr = (Node *) d->arg;
8963  }
8964  else
8965  return true;
8966  }
8967 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Definition: nodes.h:509
Definition: primnodes.h:163
bool DomainHasConstraints(Oid type_id)
Definition: typcache.c:1059
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
void * arg
static void ATController ( AlterTableStmt parsetree,
Relation  rel,
List cmds,
bool  recurse,
LOCKMODE  lockmode 
)
static

Definition at line 3412 of file tablecmds.c.

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

Referenced by AlterTable(), and AlterTableInternal().

3414 {
3415  List *wqueue = NIL;
3416  ListCell *lcmd;
3417 
3418  /* Phase 1: preliminary examination of commands, create work queue */
3419  foreach(lcmd, cmds)
3420  {
3421  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3422 
3423  ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode);
3424  }
3425 
3426  /* Close the relation, but keep lock until commit */
3427  relation_close(rel, NoLock);
3428 
3429  /* Phase 2: update system catalogs */
3430  ATRewriteCatalogs(&wqueue, lockmode);
3431 
3432  /* Phase 3: scan/rewrite tables as needed */
3433  ATRewriteTables(parsetree, &wqueue, lockmode);
3434 }
#define NIL
Definition: pg_list.h:69
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1260
#define NoLock
Definition: lockdefs.h:34
static void ATRewriteTables(AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode)
Definition: tablecmds.c:4089
static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
Definition: tablecmds.c:3446
#define lfirst(lc)
Definition: pg_list.h:106
static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode)
Definition: tablecmds.c:3746
Definition: pg_list.h:45
void AtEOSubXact_on_commit_actions ( bool  isCommit,
SubTransactionId  mySubid,
SubTransactionId  parentSubid 
)

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

12907 {
12908  ListCell *cur_item;
12909  ListCell *prev_item;
12910 
12911  prev_item = NULL;
12912  cur_item = list_head(on_commits);
12913 
12914  while (cur_item != NULL)
12915  {
12916  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
12917 
12918  if (!isCommit && oc->creating_subid == mySubid)
12919  {
12920  /* cur_item must be removed */
12921  on_commits = list_delete_cell(on_commits, cur_item, prev_item);
12922  pfree(oc);
12923  if (prev_item)
12924  cur_item = lnext(prev_item);
12925  else
12926  cur_item = list_head(on_commits);
12927  }
12928  else
12929  {
12930  /* cur_item must be preserved */
12931  if (oc->creating_subid == mySubid)
12932  oc->creating_subid = parentSubid;
12933  if (oc->deleting_subid == mySubid)
12934  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
12935  prev_item = cur_item;
12936  cur_item = lnext(prev_item);
12937  }
12938  }
12939 }
SubTransactionId creating_subid
Definition: tablecmds.c:120
void pfree(void *pointer)
Definition: mcxt.c:950
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:229
#define lfirst(lc)
Definition: pg_list.h:106
#define InvalidSubTransactionId
Definition: c.h:403
void AtEOXact_on_commit_actions ( bool  isCommit)

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

12864 {
12865  ListCell *cur_item;
12866  ListCell *prev_item;
12867 
12868  prev_item = NULL;
12869  cur_item = list_head(on_commits);
12870 
12871  while (cur_item != NULL)
12872  {
12873  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
12874 
12875  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
12877  {
12878  /* cur_item must be removed */
12879  on_commits = list_delete_cell(on_commits, cur_item, prev_item);
12880  pfree(oc);
12881  if (prev_item)
12882  cur_item = lnext(prev_item);
12883  else
12884  cur_item = list_head(on_commits);
12885  }
12886  else
12887  {
12888  /* cur_item must be preserved */
12891  prev_item = cur_item;
12892  cur_item = lnext(prev_item);
12893  }
12894  }
12895 }
SubTransactionId creating_subid
Definition: tablecmds.c:120
void pfree(void *pointer)
Definition: mcxt.c:950
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:229
#define lfirst(lc)
Definition: pg_list.h:106
#define InvalidSubTransactionId
Definition: c.h:403
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 5091 of file tablecmds.c.

References ACL_USAGE, aclcheck_error_type(), ACLCHECK_OK, add_column_collation_dependency(), add_column_datatype_dependency(), AddRelationNewConstraints(), TypeName::arrayBounds, AT_REWRITE_ALTER_OID, AT_REWRITE_DEFAULT_VAL, ATGetQueueEntry(), ATSimplePermissions(), ATT_FOREIGN_TABLE, ATT_TABLE, RawColumnDefault::attnum, NewColumnValue::attnum, AttributeRelationId, build_column_default(), CatalogTupleUpdate(), check_for_column_name_collision(), CheckAttributeType(), CheckTableNotInUse(), COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, ColumnDef::colname, CommandCounterIncrement(), copyObject, DomainHasConstraints(), elog, ereport, errcode(), errdetail(), errmsg(), ERROR, NewColumnValue::expr, expression_planner(), find_inheritance_children(), FormData_pg_attribute, get_collation_name(), get_typcollation(), getBaseTypeAndTypmod(), GetColumnDefCollation(), GETSTRUCT, GetUserId(), heap_close, heap_freetuple(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, ColumnDef::identity, ColumnDef::inhcount, InsertPgAttributeTuple(), InvalidObjectAddress, InvokeObjectPostCreateHook, ColumnDef::is_local, ColumnDef::is_not_null, lappend(), lfirst_oid, list_length(), list_make1, list_make1_oid, makeNullConst(), MaxHeapAttributeNumber, namestrcpy(), AlteredTableInfo::new_notnull, newval, AlteredTableInfo::newvals, NIL, NoLock, NOTICE, 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().

5095 {
5096  Oid myrelid = RelationGetRelid(rel);
5097  Relation pgclass,
5098  attrdesc;
5099  HeapTuple reltup;
5100  FormData_pg_attribute attribute;
5101  int newattnum;
5102  char relkind;
5103  HeapTuple typeTuple;
5104  Oid typeOid;
5105  int32 typmod;
5106  Oid collOid;
5107  Form_pg_type tform;
5108  Expr *defval;
5109  List *children;
5110  ListCell *child;
5111  AclResult aclresult;
5112  ObjectAddress address;
5113 
5114  /* At top level, permission check was done in ATPrepCmd, else do it */
5115  if (recursing)
5117 
5118  if (rel->rd_rel->relispartition && !recursing)
5119  ereport(ERROR,
5120  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5121  errmsg("cannot add column to a partition")));
5122 
5124 
5125  /*
5126  * Are we adding the column to a recursion child? If so, check whether to
5127  * merge with an existing definition for the column. If we do merge, we
5128  * must not recurse. Children will already have the column, and recursing
5129  * into them would mess up attinhcount.
5130  */
5131  if (colDef->inhcount > 0)
5132  {
5133  HeapTuple tuple;
5134 
5135  /* Does child already have a column by this name? */
5136  tuple = SearchSysCacheCopyAttName(myrelid, colDef->colname);
5137  if (HeapTupleIsValid(tuple))
5138  {
5139  Form_pg_attribute childatt = (Form_pg_attribute) GETSTRUCT(tuple);
5140  Oid ctypeId;
5141  int32 ctypmod;
5142  Oid ccollid;
5143 
5144  /* Child column must match on type, typmod, and collation */
5145  typenameTypeIdAndMod(NULL, colDef->typeName, &ctypeId, &ctypmod);
5146  if (ctypeId != childatt->atttypid ||
5147  ctypmod != childatt->atttypmod)
5148  ereport(ERROR,
5149  (errcode(ERRCODE_DATATYPE_MISMATCH),
5150  errmsg("child table \"%s\" has different type for column \"%s\"",
5151  RelationGetRelationName(rel), colDef->colname)));
5152  ccollid = GetColumnDefCollation(NULL, colDef, ctypeId);
5153  if (ccollid != childatt->attcollation)
5154  ereport(ERROR,
5155  (errcode(ERRCODE_COLLATION_MISMATCH),
5156  errmsg("child table \"%s\" has different collation for column \"%s\"",
5157  RelationGetRelationName(rel), colDef->colname),
5158  errdetail("\"%s\" versus \"%s\"",
5159  get_collation_name(ccollid),
5160  get_collation_name(childatt->attcollation))));
5161 
5162  /* If it's OID, child column must actually be OID */
5163  if (isOid && childatt->attnum != ObjectIdAttributeNumber)
5164  ereport(ERROR,
5165  (errcode(ERRCODE_DATATYPE_MISMATCH),
5166  errmsg("child table \"%s\" has a conflicting \"%s\" column",
5167  RelationGetRelationName(rel), colDef->colname)));
5168 
5169  /* Bump the existing child att's inhcount */
5170  childatt->attinhcount++;
5171  CatalogTupleUpdate(attrdesc, &tuple->t_self, tuple);
5172 
5173  heap_freetuple(tuple);
5174 
5175  /* Inform the user about the merge */
5176  ereport(NOTICE,
5177  (errmsg("merging definition of column \"%s\" for child \"%s\"",
5178  colDef->colname, RelationGetRelationName(rel))));
5179 
5180  heap_close(attrdesc, RowExclusiveLock);
5181  return InvalidObjectAddress;
5182  }
5183  }
5184 
5186 
5187  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(myrelid));
5188  if (!HeapTupleIsValid(reltup))
5189  elog(ERROR, "cache lookup failed for relation %u", myrelid);
5190  relkind = ((Form_pg_class) GETSTRUCT(reltup))->relkind;
5191 
5192  /*
5193  * Cannot add identity column if table has children, because identity does
5194  * not inherit. (Adding column and identity separately will work.)
5195  */
5196  if (colDef->identity &&
5197  recurse &&
5198  find_inheritance_children(myrelid, NoLock) != NIL)
5199  ereport(ERROR,
5200  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5201  errmsg("cannot recursively add identity column to table that has child tables")));
5202 
5203  /* skip if the name already exists and if_not_exists is true */
5204  if (!check_for_column_name_collision(rel, colDef->colname, if_not_exists))
5205  {
5206  heap_close(attrdesc, RowExclusiveLock);
5207  heap_freetuple(reltup);
5208  heap_close(pgclass, RowExclusiveLock);
5209  return InvalidObjectAddress;
5210  }
5211 
5212  /* Determine the new attribute's number */
5213  if (isOid)
5214  newattnum = ObjectIdAttributeNumber;
5215  else
5216  {
5217  newattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts + 1;
5218  if (newattnum > MaxHeapAttributeNumber)
5219  ereport(ERROR,
5220  (errcode(ERRCODE_TOO_MANY_COLUMNS),
5221  errmsg("tables can have at most %d columns",
5223  }
5224 
5225  typeTuple = typenameType(NULL, colDef->typeName, &typmod);
5226  tform = (Form_pg_type) GETSTRUCT(typeTuple);
5227  typeOid = HeapTupleGetOid(typeTuple);
5228 
5229  aclresult = pg_type_aclcheck(typeOid, GetUserId(), ACL_USAGE);
5230  if (aclresult != ACLCHECK_OK)
5231  aclcheck_error_type(aclresult, typeOid);
5232 
5233  collOid = GetColumnDefCollation(NULL, colDef, typeOid);
5234 
5235  /* make sure datatype is legal for a column */
5236  CheckAttributeType(colDef->colname, typeOid, collOid,
5237  list_make1_oid(rel->rd_rel->reltype),
5238  false);
5239 
5240  /* construct new attribute's pg_attribute entry */
5241  attribute.attrelid = myrelid;
5242  namestrcpy(&(attribute.attname), colDef->colname);
5243  attribute.atttypid = typeOid;
5244  attribute.attstattarget = (newattnum > 0) ? -1 : 0;
5245  attribute.attlen = tform->typlen;
5246  attribute.attcacheoff = -1;
5247  attribute.atttypmod = typmod;
5248  attribute.attnum = newattnum;
5249  attribute.attbyval = tform->typbyval;
5250  attribute.attndims = list_length(colDef->typeName->arrayBounds);
5251  attribute.attstorage = tform->typstorage;
5252  attribute.attalign = tform->typalign;
5253  attribute.attnotnull = colDef->is_not_null;
5254  attribute.atthasdef = false;
5255  attribute.attidentity = colDef->identity;
5256  attribute.attisdropped = false;
5257  attribute.attislocal = colDef->is_local;
5258  attribute.attinhcount = colDef->inhcount;
5259  attribute.attcollation = collOid;
5260  /* attribute.attacl is handled by InsertPgAttributeTuple */
5261 
5262  ReleaseSysCache(typeTuple);
5263 
5264  InsertPgAttributeTuple(attrdesc, &attribute, NULL);
5265 
5266  heap_close(attrdesc, RowExclusiveLock);
5267 
5268  /*
5269  * Update pg_class tuple as appropriate
5270  */
5271  if (isOid)
5272  ((Form_pg_class) GETSTRUCT(reltup))->relhasoids = true;
5273  else
5274  ((Form_pg_class) GETSTRUCT(reltup))->relnatts = newattnum;
5275 
5276  CatalogTupleUpdate(pgclass, &reltup->t_self, reltup);
5277 
5278  heap_freetuple(reltup);
5279 
5280  /* Post creation hook for new attribute */
5281  InvokeObjectPostCreateHook(RelationRelationId, myrelid, newattnum);
5282 
5283  heap_close(pgclass, RowExclusiveLock);
5284 
5285  /* Make the attribute's catalog entry visible */
5287 
5288  /*
5289  * Store the DEFAULT, if any, in the catalogs
5290  */
5291  if (colDef->raw_default)
5292  {
5293  RawColumnDefault *rawEnt;
5294 
5295  rawEnt = (RawColumnDefault *) palloc(sizeof(RawColumnDefault));
5296  rawEnt->attnum = attribute.attnum;
5297  rawEnt->raw_default = copyObject(colDef->raw_default);
5298 
5299  /*
5300  * This function is intended for CREATE TABLE, so it processes a
5301  * _list_ of defaults, but we just do one.
5302  */
5304  false, true, false);
5305 
5306  /* Make the additional catalog changes visible */
5308  }
5309 
5310  /*
5311  * Tell Phase 3 to fill in the default expression, if there is one.
5312  *
5313  * If there is no default, Phase 3 doesn't have to do anything, because
5314  * that effectively means that the default is NULL. The heap tuple access
5315  * routines always check for attnum > # of attributes in tuple, and return
5316  * NULL if so, so without any modification of the tuple data we will get
5317  * the effect of NULL values in the new column.
5318  *
5319  * An exception occurs when the new column is of a domain type: the domain
5320  * might have a NOT NULL constraint, or a check constraint that indirectly
5321  * rejects nulls. If there are any domain constraints then we construct
5322  * an explicit NULL default value that will be passed through
5323  * CoerceToDomain processing. (This is a tad inefficient, since it causes
5324  * rewriting the table which we really don't have to do, but the present
5325  * design of domain processing doesn't offer any simple way of checking
5326  * the constraints more directly.)
5327  *
5328  * Note: we use build_column_default, and not just the cooked default
5329  * returned by AddRelationNewConstraints, so that the right thing happens
5330  * when a datatype's default applies.
5331  *
5332  * We skip this step completely for views and foreign tables. For a view,
5333  * we can only get here from CREATE OR REPLACE VIEW, which historically
5334  * doesn't set up defaults, not even for domain-typed columns. And in any
5335  * case we mustn't invoke Phase 3 on a view or foreign table, since they
5336  * have no storage.
5337  */
5338  if (relkind != RELKIND_VIEW && relkind != RELKIND_COMPOSITE_TYPE
5339  && relkind != RELKIND_FOREIGN_TABLE && attribute.attnum > 0)
5340  {
5341  defval = (Expr *) build_column_default(rel, attribute.attnum);
5342 
5343  if (!defval && DomainHasConstraints(typeOid))
5344  {
5345  Oid baseTypeId;
5346  int32 baseTypeMod;
5347  Oid baseTypeColl;
5348 
5349  baseTypeMod = typmod;
5350  baseTypeId = getBaseTypeAndTypmod(typeOid, &baseTypeMod);
5351  baseTypeColl = get_typcollation(baseTypeId);
5352  defval = (Expr *) makeNullConst(baseTypeId, baseTypeMod, baseTypeColl);
5353  defval = (Expr *) coerce_to_target_type(NULL,
5354  (Node *) defval,
5355  baseTypeId,
5356  typeOid,
5357  typmod,
5360  -1);
5361  if (defval == NULL) /* should not happen */
5362  elog(ERROR, "failed to coerce base type to domain");
5363  }
5364 
5365  if (defval)
5366  {
5368 
5369  newval = (NewColumnValue *) palloc0(sizeof(NewColumnValue));
5370  newval->attnum = attribute.attnum;
5371  newval->expr = expression_planner(defval);
5372 
5373  tab->newvals = lappend(tab->newvals, newval);
5375  }
5376 
5377  /*
5378  * If the new column is NOT NULL, tell Phase 3 it needs to test that.
5379  * (Note we don't do this for an OID column. OID will be marked not
5380  * null, but since it's filled specially, there's no need to test
5381  * anything.)
5382  */
5383  tab->new_notnull |= colDef->is_not_null;
5384  }
5385 
5386  /*
5387  * If we are adding an OID column, we have to tell Phase 3 to rewrite the
5388  * table to fix that.
5389  */
5390  if (isOid)
5391  tab->rewrite |= AT_REWRITE_ALTER_OID;
5392 
5393  /*
5394  * Add needed dependency entries for the new column.
5395  */
5396  add_column_datatype_dependency(myrelid, newattnum, attribute.atttypid);
5397  add_column_collation_dependency(myrelid, newattnum, attribute.attcollation);
5398 
5399  /*
5400  * Propagate to children as appropriate. Unlike most other ALTER
5401  * routines, we have to do this one level of recursion at a time; we can't
5402  * use find_all_inheritors to do it in one pass.
5403  */
5404  children = find_inheritance_children(RelationGetRelid(rel), lockmode);
5405 
5406  /*
5407  * If we are told not to recurse, there had better not be any child
5408  * tables; else the addition would put them out of step.
5409  */
5410  if (children && !recurse)
5411  ereport(ERROR,
5412  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
5413  errmsg("column must be added to child tables too")));
5414 
5415  /* Children should see column as singly inherited */
5416  if (!recursing)
5417  {
5418  colDef = copyObject(colDef);
5419  colDef->inhcount = 1;
5420  colDef->is_local = false;
5421  }
5422 
5423  foreach(child, children)
5424  {
5425  Oid childrelid = lfirst_oid(child);
5426  Relation childrel;
5427  AlteredTableInfo *childtab;
5428 
5429  /* find_inheritance_children already got lock */
5430  childrel = heap_open(childrelid, NoLock);
5431  CheckTableNotInUse(childrel, "ALTER TABLE");
5432 
5433  /* Find or create work queue entry for this table */
5434  childtab = ATGetQueueEntry(wqueue, childrel);
5435 
5436  /* Recurse to child; return value is ignored */
5437  ATExecAddColumn(wqueue, childtab, childrel,
5438  colDef, isOid, recurse, true,
5439  if_not_exists, lockmode);
5440 
5441  heap_close(childrel, NoLock);
5442  }
5443 
5444  ObjectAddressSubSet(address, RelationRelationId, myrelid, newattnum);
5445  return address;
5446 }
#define NIL
Definition: pg_list.h:69
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2288
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:247
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
AttrNumber attnum
Definition: heap.h:24
bool is_local
Definition: parsenodes.h:643
Oid GetUserId(void)
Definition: miscinit.c:283
#define ObjectIdAttributeNumber
Definition: sysattr.h:22
char identity
Definition: parsenodes.h:649
char * get_collation_name(Oid colloid)
Definition: lsyscache.c:967
#define RelationRelationId
Definition: pg_class.h:29
Expr * expression_planner(Expr *expr)
Definition: planner.c:5928
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:5091
Definition: nodes.h:509
#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:644
FormData_pg_type * Form_pg_type
Definition: pg_type.h:233
Form_pg_class rd_rel
Definition: rel.h:114
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
unsigned int Oid
Definition: postgres_ext.h:31
#define ATT_TABLE
Definition: tablecmds.c:279
int namestrcpy(Name name, const char *str)
Definition: name.c:217
#define RELKIND_COMPOSITE_TYPE
Definition: pg_class.h:166
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3457
signed int int32
Definition: c.h:256
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:334
bool DomainHasConstraints(Oid type_id)
Definition: typcache.c:1059
#define list_make1(x1)
Definition: pg_list.h:139
#define AT_REWRITE_DEFAULT_VAL
Definition: event_trigger.h:32
static void add_column_datatype_dependency(Oid relid, int32 attnum, Oid typid)
Definition: tablecmds.c:5506
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:77
HeapTuple SearchSysCacheCopyAttName(Oid relid, const char *attname)
Definition: syscache.c:1227
ItemPointerData t_self
Definition: htup.h:65
static void add_column_collation_dependency(Oid relid, int32 attnum, Oid collid)
Definition: tablecmds.c:5524
#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:437
static AlteredTableInfo * ATGetQueueEntry(List **wqueue, Relation rel)
Definition: tablecmds.c:4634
Node * raw_default
Definition: heap.h:25
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ACL_USAGE
Definition: parsenodes.h:80
#define AT_REWRITE_ALTER_OID
Definition: event_trigger.h:34
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3015
#define ereport(elevel, rest)
Definition: elog.h:122
Node * raw_default
Definition: parsenodes.h:647
List * lappend(List *list, void *datum)
Definition: list.c:128
void CheckAttributeType(const char *attname, Oid atttypid, Oid attcollation, List *containing_rowtypes, bool allow_system_table_mods)
Definition: heap.c:488
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:878
AclResult
Definition: acl.h:170
void CommandCounterIncrement(void)
Definition: xact.c:922
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
#define list_make1_oid(x1)
Definition: pg_list.h:151
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
void typenameTypeIdAndMod(ParseState *pstate, const TypeName *typeName, Oid *typeid_p, int32 *typmod_p)
Definition: parse_type.c:293
FormData_pg_attribute
Definition: pg_attribute.h:171
List * find_inheritance_children(Oid parentrelId, LOCKMODE lockmode)
Definition: pg_inherits.c:57
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2781
#define NOTICE
Definition: elog.h:37
#define MaxHeapAttributeNumber
Definition: htup_details.h:47
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
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:641
#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:161
List * arrayBounds
Definition: parsenodes.h:215
void InsertPgAttributeTuple(Relation pg_attribute_rel, Form_pg_attribute new_attribute, CatalogIndexState indstate)
Definition: heap.c:598
const ObjectAddress InvalidObjectAddress
void * palloc(Size size)
Definition: mcxt.c:849
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:5453
#define RELKIND_VIEW
Definition: pg_class.h:164
int inhcount
Definition: parsenodes.h:642
static void ATSimplePermissions(Relation rel, int allowed_targets)
Definition: tablecmds.c:4671
char * colname
Definition: parsenodes.h:640
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
#define copyObject(obj)
Definition: nodes.h:621
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4534
Definition: pg_list.h:45
#define ATT_FOREIGN_TABLE
Definition: tablecmds.c:284
#define RelationGetRelid(relation)
Definition: rel.h:417
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal)
Definition: heap.c:2206
#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 6821 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().

6824 {
6826 
6827  Assert(IsA(newConstraint, Constraint));
6828 
6829  /*
6830  * Currently, we only expect to see CONSTR_CHECK and CONSTR_FOREIGN nodes
6831  * arriving here (see the preprocessing done in parse_utilcmd.c). Use a
6832  * switch anyway to make it easier to add more code later.
6833  */
6834  switch (newConstraint->contype)
6835  {
6836  case CONSTR_CHECK:
6837  address =
6838  ATAddCheckConstraint(wqueue, tab, rel,
6839  newConstraint, recurse, false, is_readd,
6840  lockmode);
6841  break;
6842 
6843  case CONSTR_FOREIGN:
6844 
6845  /*
6846  * Note that we currently never recurse for FK constraints, so the
6847  * "recurse" flag is silently ignored.
6848  *
6849  * Assign or validate constraint name
6850  */
6851  if (newConstraint->conname)
6852  {
6854  RelationGetRelid(rel),
6855  RelationGetNamespace(rel),
6856  newConstraint->conname))
6857  ereport(ERROR,
6859  errmsg("constraint \"%s\" for relation \"%s\" already exists",
6860  newConstraint->conname,
6861  RelationGetRelationName(rel))));
6862  }
6863  else
6864  newConstraint->conname =
6866  strVal(linitial(newConstraint->fk_attrs)),
6867  "fkey",
6868  RelationGetNamespace(rel),
6869  NIL);
6870 
6871  address = ATAddForeignKeyConstraint(tab, rel, newConstraint,
6872  lockmode);
6873  break;
6874 
6875  default:
6876  elog(ERROR, "unrecognized constraint type: %d",
6877  (int) newConstraint->contype);
6878  }
6879 
6880  return address;
6881 }
#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:560
static ObjectAddress ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel, Constraint *fkconstraint, LOCKMODE lockmode)
Definition: tablecmds.c:7026
#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:6899
char * conname
Definition: parsenodes.h:2048
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:437
#define ereport(elevel, rest)
Definition: elog.h:122
#define Assert(condition)
Definition: c.h:675
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:2045
#define elog
Definition: elog.h:219
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:31
#define RelationGetRelid(relation)
Definition: rel.h:417
List * fk_attrs
Definition: parsenodes.h:2075
#define RelationGetNamespace(relation)
Definition: rel.h:444
static ObjectAddress ATExecAddIdentity ( Relation  rel,
const char *  colName,
Node def,
LOCKMODE  lockmode 
)
static

Definition at line 5904 of file tablecmds.c.

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

Referenced by ATExecCmd().

5906 {
5907  Relation attrelation;
5908  HeapTuple tuple;
5909  Form_pg_attribute attTup;
5910  AttrNumber attnum;
5911  ObjectAddress address;
5912  ColumnDef *cdef = castNode(ColumnDef, def);
5913 
5915 
5916  tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5917  if (!HeapTupleIsValid(tuple))
5918  ereport(ERROR,
5919  (errcode(ERRCODE_UNDEFINED_COLUMN),
5920  errmsg("column \"%s\" of relation \"%s\" does not exist",
5921  colName, RelationGetRelationName(rel))));
5922  attTup = (Form_pg_attribute) GETSTRUCT(tuple);
5923  attnum = attTup->attnum;
5924 
5925  /* Can't alter a system attribute */
5926  if (attnum <= 0)
5927  ereport(ERROR,
5928  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5929  errmsg("cannot alter system column \"%s\"",
5930  colName)));
5931 
5932  /*
5933  * Creating a column as identity implies NOT NULL, so adding the identity
5934  * to an existing column that is not NOT NULL would create a state that
5935  * cannot be reproduced without contortions.
5936  */
5937  if (!attTup->attnotnull)
5938  ereport(ERROR,
5939  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5940  errmsg("column \"%s\" of relation \"%s\" must be declared NOT NULL before identity can be added",
5941  colName, RelationGetRelationName(rel))));
5942 
5943  if (attTup->attidentity)
5944  ereport(ERROR,
5945  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5946  errmsg("column \"%s\" of relation \"%s\" is already an identity column",
5947  colName, RelationGetRelationName(rel))));
5948 
5949  if (attTup->atthasdef)
5950  ereport(ERROR,
5951  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5952  errmsg("column \"%s\" of relation \"%s\" already has a default value",
5953  colName, RelationGetRelationName(rel))));
5954 
5955  attTup->attidentity = cdef->identity;
5956  CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
5957 
5959  RelationGetRelid(rel),
5960  attTup->attnum);
5962  RelationGetRelid(rel), attnum);
5963  heap_freetuple(tuple);
5964 
5965  heap_close(attrelation, RowExclusiveLock);
5966 
5967  return address;
5968 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define castNode(_type_, nodeptr)
Definition: nodes.h:578
char identity
Definition: parsenodes.h:649
#define RelationRelationId
Definition: pg_class.h:29
#define AttributeRelationId
Definition: pg_attribute.h:33
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCacheCopyAttName(Oid relid, const char *attname)
Definition: syscache.c:1227
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:437
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
int errmsg(const char *fmt,...)
Definition: elog.c:797
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:417
static ObjectAddress ATExecAddIndex ( AlteredTableInfo tab,
Relation  rel,
IndexStmt stmt,
bool  is_rebuild,
LOCKMODE  lockmode 
)
static

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

6692 {
6693  bool check_rights;
6694  bool skip_build;
6695  bool quiet;
6696  ObjectAddress address;
6697 
6698  Assert(IsA(stmt, IndexStmt));
6699  Assert(!stmt->concurrent);
6700 
6701  /* The IndexStmt has already been through transformIndexStmt */
6702  Assert(stmt->transformed);
6703 
6704  /* suppress schema rights check when rebuilding existing index */
6705  check_rights = !is_rebuild;
6706  /* skip index build if phase 3 will do it or we're reusing an old one */
6707  skip_build = tab->rewrite > 0 || OidIsValid(stmt->oldNode);
6708  /* suppress notices when rebuilding existing index */
6709  quiet = is_rebuild;
6710 
6711  address = DefineIndex(RelationGetRelid(rel),
6712  stmt,
6713  InvalidOid, /* no predefined OID */
6714  true, /* is_alter_table */
6715  check_rights,
6716  skip_build,
6717  quiet);
6718 
6719  /*
6720  * If TryReuseIndex() stashed a relfilenode for us, we used it for the new
6721  * index instead of building from scratch. The DROP of the old edition of
6722  * this index will have scheduled the storage for deletion at commit, so
6723  * cancel that pending deletion.
6724  */
6725  if (OidIsValid(stmt->oldNode))
6726  {
6727  Relation irel = index_open(address.objectId, NoLock);
6728 
6729  RelationPreserveStorage(irel->rd_node, true);
6730  index_close(irel, NoLock);
6731  }
6732 
6733  return address;
6734 }
void RelationPreserveStorage(RelFileNode rnode, bool atCommit)
Definition: storage.c:190
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
#define OidIsValid(objectId)
Definition: c.h:538
#define NoLock
Definition: lockdefs.h:34
bool transformed
Definition: parsenodes.h:2678
#define InvalidOid
Definition: postgres_ext.h:36
RelFileNode rd_node
Definition: rel.h:85
#define Assert(condition)
Definition: c.h:675
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:2679
#define RelationGetRelid(relation)
Definition: rel.h:417
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 6742 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().

6744 {
6745  Oid index_oid = stmt->indexOid;
6746  Relation indexRel;
6747  char *indexName;
6748  IndexInfo *indexInfo;
6749  char *constraintName;
6750  char constraintType;
6751  ObjectAddress address;
6752 
6753  Assert(IsA(stmt, IndexStmt));
6754  Assert(OidIsValid(index_oid));
6755  Assert(stmt->isconstraint);
6756 
6757  indexRel = index_open(index_oid, AccessShareLock);
6758 
6759  indexName = pstrdup(RelationGetRelationName(indexRel));
6760 
6761  indexInfo = BuildIndexInfo(indexRel);
6762 
6763  /* this should have been checked at parse time */
6764  if (!indexInfo->ii_Unique)
6765  elog(ERROR, "index \"%s\" is not unique", indexName);
6766 
6767  /*
6768  * Determine name to assign to constraint. We require a constraint to
6769  * have the same name as the underlying index; therefore, use the index's
6770  * existing name as the default constraint name, and if the user
6771  * explicitly gives some other name for the constraint, rename the index
6772  * to match.
6773  */
6774  constraintName = stmt->idxname;
6775  if (constraintName == NULL)
6776  constraintName = indexName;
6777  else if (strcmp(constraintName, indexName) != 0)
6778  {
6779  ereport(NOTICE,
6780  (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
6781  indexName, constraintName)));
6782  RenameRelationInternal(index_oid, constraintName, false);
6783  }
6784 
6785  /* Extra checks needed if making primary key */
6786  if (stmt->primary)
6787  index_check_primary_key(rel, indexInfo, true);
6788 
6789  /* Note we currently don't support EXCLUSION constraints here */
6790  if (stmt->primary)
6791  constraintType = CONSTRAINT_PRIMARY;
6792  else
6793  constraintType = CONSTRAINT_UNIQUE;
6794 
6795  /* Create the catalog entries for the constraint */
6796  address = index_constraint_create(rel,
6797  index_oid,
6798  indexInfo,
6799  constraintName,
6800  constraintType,
6801  stmt->deferrable,
6802  stmt->initdeferred,
6803  stmt->primary,
6804  true, /* update pg_index */
6805  true, /* remove old dependencies */
6807  false); /* is_internal */
6808 
6809  index_close(indexRel, NoLock);
6810 
6811  return address;
6812 }
bool deferrable
Definition: parsenodes.h:2676
bool primary
Definition: parsenodes.h:2674
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal)
Definition: tablecmds.c:2919
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
char * pstrdup(const char *in)
Definition: mcxt.c:1077
#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:1640
unsigned int Oid
Definition: postgres_ext.h:31
#define CONSTRAINT_UNIQUE
#define OidIsValid(objectId)
Definition: c.h:538
#define CONSTRAINT_PRIMARY
Oid indexOid
Definition: parsenodes.h:2671
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:437
#define ereport(elevel, rest)
Definition: elog.h:122
char * idxname
Definition: parsenodes.h:2662
bool allowSystemTableMods
Definition: globals.c:111
#define NOTICE
Definition: elog.h:37
bool ii_Unique
Definition: execnodes.h:146
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
bool initdeferred
Definition: parsenodes.h:2677
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
bool isconstraint
Definition: parsenodes.h:2675
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:1148
#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 10947 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().

10948 {
10949  Relation parent_rel;
10950  List *children;
10951  ObjectAddress address;
10952 
10953  /*
10954  * A self-exclusive lock is needed here. See the similar case in
10955  * MergeAttributes() for a full explanation.
10956  */
10957  parent_rel = heap_openrv(parent, ShareUpdateExclusiveLock);
10958 
10959  /*
10960  * Must be owner of both parent and child -- child was checked by
10961  * ATSimplePermissions call in ATPrepCmd
10962  */
10964 
10965  /* Permanent rels cannot inherit from temporary ones */
10966  if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
10967  child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
10968  ereport(ERROR,
10969  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10970  errmsg("cannot inherit from temporary relation \"%s\"",
10971  RelationGetRelationName(parent_rel))));
10972 
10973  /* If parent rel is temp, it must belong to this session */
10974  if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
10975  !parent_rel->rd_islocaltemp)
10976  ereport(ERROR,
10977  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10978  errmsg("cannot inherit from temporary relation of another session")));
10979 
10980  /* Ditto for the child */
10981  if (child_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
10982  !child_rel->rd_islocaltemp)
10983  ereport(ERROR,
10984  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10985  errmsg("cannot inherit to temporary relation of another session")));
10986 
10987  /* Prevent partitioned tables from becoming inheritance parents */
10988  if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
10989  ereport(ERROR,
10990  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10991  errmsg("cannot inherit from partitioned table \"%s\"",
10992  parent->relname)));
10993 
10994  /* Likewise for partitions */
10995  if (parent_rel->rd_rel->relispartition)
10996  ereport(ERROR,
10997  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10998  errmsg("cannot inherit from a partition")));
10999 
11000  /*
11001  * Prevent circularity by seeing if proposed parent inherits from child.
11002  * (In particular, this disallows making a rel inherit from itself.)
11003  *
11004  * This is not completely bulletproof because of race conditions: in
11005  * multi-level inheritance trees, someone else could concurrently be
11006  * making another inheritance link that closes the loop but does not join
11007  * either of the rels we have locked. Preventing that seems to require
11008  * exclusive locks on the entire inheritance tree, which is a cure worse
11009  * than the disease. find_all_inheritors() will cope with circularity
11010  * anyway, so don't sweat it too much.
11011  *
11012  * We use weakest lock we can on child's children, namely AccessShareLock.
11013  */
11014  children = find_all_inheritors(RelationGetRelid(child_rel),
11016 
11017  if (list_member_oid(children, RelationGetRelid(parent_rel)))
11018  ereport(ERROR,
11019  (errcode(ERRCODE_DUPLICATE_TABLE),
11020  errmsg("circular inheritance not allowed"),
11021  errdetail("\"%s\" is already a child of \"%s\".",
11022  parent->relname,
11023  RelationGetRelationName(child_rel))));
11024 
11025  /* If parent has OIDs then child must have OIDs */
11026  if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
11027  ereport(ERROR,
11028  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11029  errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
11030  RelationGetRelationName(child_rel),
11031  RelationGetRelationName(parent_rel))));
11032 
11033  /* OK to create inheritance */
11034  CreateInheritance(child_rel, parent_rel);
11035 
11037  RelationGetRelid(parent_rel));
11038 
11039  /* keep our lock on the parent relation until commit */
11040  heap_close(parent_rel, NoLock);
11041 
11042  return address;
11043 }
#define RelationRelationId
Definition: pg_class.h:29
bool rd_islocaltemp
Definition: rel.h:90
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:114
#define ATT_TABLE
Definition: tablecmds.c:279
static void CreateInheritance(Relation child_rel, Relation parent_rel)
Definition: tablecmds.c:11053
char * relname
Definition: primnodes.h:68
#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:437
#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:1312
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505
#define NULL
Definition: c.h:229
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:167
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void ATSimplePermissions(Relation rel, int allowed_targets)
Definition: tablecmds.c:4671
#define RELPERSISTENCE_TEMP
Definition: pg_class.h:172
Definition: pg_list.h:45
#define ATT_FOREIGN_TABLE
Definition: tablecmds.c:284
#define RelationGetRelid(relation)
Definition: rel.h:417
static ObjectAddress ATExecAddOf ( Relation  rel,
const TypeName ofTypename,
LOCKMODE  lockmode 
)
static

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

11755 {
11756  Oid relid = RelationGetRelid(rel);
11757  Type typetuple;
11758  Oid typeid;
11759  Relation inheritsRelation,
11760  relationRelation;
11761  SysScanDesc scan;
11762  ScanKeyData key;
11763  AttrNumber table_attno,
11764  type_attno;
11765  TupleDesc typeTupleDesc,
11766  tableTupleDesc;
11767  ObjectAddress tableobj,
11768  typeobj;
11769  HeapTuple classtuple;
11770 
11771  /* Validate the type. */
11772  typetuple = typenameType(NULL, ofTypename, NULL);
11773  check_of_type(typetuple);
11774  typeid = HeapTupleGetOid(typetuple);
11775 
11776  /* Fail if the table has any inheritance parents. */
11777  inheritsRelation = heap_open(InheritsRelationId, AccessShareLock);
11778  ScanKeyInit(&key,
11780  BTEqualStrategyNumber, F_OIDEQ,
11781  ObjectIdGetDatum(relid));
11782  scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
11783  true, NULL, 1, &key);
11785  ereport(ERROR,
11786  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11787  errmsg("typed tables cannot inherit")));
11788  systable_endscan(scan);
11789  heap_close(inheritsRelation, AccessShareLock);
11790 
11791  /*
11792  * Check the tuple descriptors for compatibility. Unlike inheritance, we
11793  * require that the order also match. However, attnotnull need not match.
11794  * Also unlike inheritance, we do not require matching relhasoids.
11795  */
11796  typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
11797  tableTupleDesc = RelationGetDescr(rel);
11798  table_attno = 1;
11799  for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
11800  {
11801  Form_pg_attribute type_attr,
11802  table_attr;
11803  const char *type_attname,
11804  *table_attname;
11805 
11806  /* Get the next non-dropped type attribute. */
11807  type_attr = typeTupleDesc->attrs[type_attno - 1];
11808  if (type_attr->attisdropped)
11809  continue;
11810  type_attname = NameStr(type_attr->attname);
11811 
11812  /* Get the next non-dropped table attribute. */
11813  do
11814  {
11815  if (table_attno > tableTupleDesc->natts)
11816  ereport(ERROR,
11817  (errcode(ERRCODE_DATATYPE_MISMATCH),
11818  errmsg("table is missing column \"%s\"",
11819  type_attname)));
11820  table_attr = tableTupleDesc->attrs[table_attno++ - 1];
11821  } while (table_attr->attisdropped);
11822  table_attname = NameStr(table_attr->attname);
11823 
11824  /* Compare name. */
11825  if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
11826  ereport(ERROR,
11827  (errcode(ERRCODE_DATATYPE_MISMATCH),
11828  errmsg("table has column \"%s\" where type requires \"%s\"",
11829  table_attname, type_attname)));
11830 
11831  /* Compare type. */
11832  if (table_attr->atttypid != type_attr->atttypid ||
11833  table_attr->atttypmod != type_attr->atttypmod ||
11834  table_attr->attcollation != type_attr->attcollation)
11835  ereport(ERROR,
11836  (errcode(ERRCODE_DATATYPE_MISMATCH),
11837  errmsg("table \"%s\" has different type for column \"%s\"",
11838  RelationGetRelationName(rel), type_attname)));
11839  }
11840  DecrTupleDescRefCount(typeTupleDesc);
11841 
11842  /* Any remaining columns at the end of the table had better be dropped. */
11843  for (; table_attno <= tableTupleDesc->natts; table_attno++)
11844  {
11845  Form_pg_attribute table_attr = tableTupleDesc->attrs[table_attno - 1];
11846 
11847  if (!table_attr->attisdropped)
11848  ereport(ERROR,
11849  (errcode(ERRCODE_DATATYPE_MISMATCH),
11850  errmsg("table has extra column \"%s\"",
11851  NameStr(table_attr->attname))));
11852  }
11853 
11854  /* If the table was already typed, drop the existing dependency. */
11855  if (rel->rd_rel->reloftype)
11856  drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype);
11857 
11858  /* Record a dependency on the new type. */
11859  tableobj.classId = RelationRelationId;
11860  tableobj.objectId = relid;
11861  tableobj.objectSubId = 0;
11862  typeobj.classId = TypeRelationId;
11863  typeobj.objectId = typeid;
11864  typeobj.objectSubId = 0;
11865  recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
11866 
11867  /* Update pg_class.reloftype */
11868  relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
11869  classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
11870  if (!HeapTupleIsValid(classtuple))
11871  elog(ERROR, "cache lookup failed for relation %u", relid);
11872  ((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
11873  CatalogTupleUpdate(relationRelation, &classtuple->t_self, classtuple);
11874 
11876 
11877  heap_freetuple(classtuple);
11878  heap_close(relationRelation, RowExclusiveLock);
11879 
11880  ReleaseSysCache(typetuple);
11881 
11882  return typeobj;
11883 }
#define Anum_pg_inherits_inhrelid
Definition: pg_inherits.h:50
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:247
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1257
#define RelationGetDescr(relation)
Definition: rel.h:429
#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:114
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:328
int natts
Definition: tupdesc.h:73
#define NAMEDATALEN
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:416
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
void check_of_type(HeapTuple typetuple)
Definition: tablecmds.c:5028
static void drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid)
Definition: tablecmds.c:11703
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:437
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
void DecrTupleDescRefCount(TupleDesc tupdesc)
Definition: tupdesc.c:336
#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:161
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:499
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:417
#define BTEqualStrategyNumber
Definition: stratnum.h:31
static ObjectAddress ATExecAlterColumnGenericOptions ( Relation  rel,
const char *  colName,
List options,
LOCKMODE  lockmode 
)
static

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

9381 {
9382  Relation ftrel;
9383  Relation attrel;
9384  ForeignServer *server;
9385  ForeignDataWrapper *fdw;
9386  HeapTuple tuple;
9387  HeapTuple newtuple;
9388  bool isnull;
9389  Datum repl_val[Natts_pg_attribute];
9390  bool repl_null[Natts_pg_attribute];
9391  bool repl_repl[Natts_pg_attribute];
9392  Datum datum;
9393  Form_pg_foreign_table fttableform;
9394  Form_pg_attribute atttableform;
9395  AttrNumber attnum;
9396  ObjectAddress address;
9397 
9398  if (options == NIL)
9399  return InvalidObjectAddress;
9400 
9401  /* First, determine FDW validator associated to the foreign table. */
9403  tuple = SearchSysCache1(FOREIGNTABLEREL, rel->rd_id);
9404  if (!HeapTupleIsValid(tuple))
9405  ereport(ERROR,
9406  (errcode(ERRCODE_UNDEFINED_OBJECT),
9407  errmsg("foreign table \"%s\" does not exist",
9408  RelationGetRelationName(rel))));
9409  fttableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
9410  server = GetForeignServer(fttableform->ftserver);
9411  fdw = GetForeignDataWrapper(server->fdwid);
9412 
9413  heap_close(ftrel, AccessShareLock);
9414  ReleaseSysCache(tuple);
9415 
9417  tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9418  if (!HeapTupleIsValid(tuple))
9419  ereport(ERROR,
9420  (errcode(ERRCODE_UNDEFINED_COLUMN),
9421  errmsg("column \"%s\" of relation \"%s\" does not exist",
9422  colName, RelationGetRelationName(rel))));
9423 
9424  /* Prevent them from altering a system attribute */
9425  atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
9426  attnum = atttableform->attnum;
9427  if (attnum <= 0)
9428  ereport(ERROR,
9429  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9430  errmsg("cannot alter system column \"%s\"", colName)));
9431 
9432 
9433  /* Initialize buffers for new tuple values */
9434  memset(repl_val, 0, sizeof(repl_val));
9435  memset(repl_null, false, sizeof(repl_null));
9436  memset(repl_repl, false, sizeof(repl_repl));
9437 
9438  /* Extract the current options */
9439  datum = SysCacheGetAttr(ATTNAME,
9440  tuple,
9442  &isnull);
9443  if (isnull)
9444  datum = PointerGetDatum(NULL);
9445 
9446  /* Transform the options */
9448  datum,
9449  options,
9450  fdw->fdwvalidator);
9451 
9452  if (PointerIsValid(DatumGetPointer(datum)))
9453  repl_val[Anum_pg_attribute_attfdwoptions - 1] = datum;
9454  else
9455  repl_null[Anum_pg_attribute_attfdwoptions - 1] = true;
9456 
9457  repl_repl[Anum_pg_attribute_attfdwoptions - 1] = true;
9458 
9459  /* Everything looks good - update the tuple */
9460 
9461  newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrel),
9462  repl_val, repl_null, repl_repl);
9463 
9464  CatalogTupleUpdate(attrel, &newtuple->t_self, newtuple);
9465 
9467  RelationGetRelid(rel),
9468  atttableform->attnum);
9470  RelationGetRelid(rel), attnum);
9471 
9472  ReleaseSysCache(tuple);
9473 
9474  heap_close(attrel, RowExclusiveLock);
9475 
9476  heap_freetuple(newtuple);
9477 
9478  return address;
9479 }
#define NIL
Definition: pg_list.h:69
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define RelationGetDescr(relation)
Definition: rel.h:429
Datum transformGenericOptions(Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
Definition: foreigncmds.c:109
#define PointerGetDatum(X)
Definition: postgres.h:562
#define RelationRelationId
Definition: pg_class.h:29
#define AccessShareLock
Definition: lockdefs.h:36
#define AttributeRelationId
Definition: pg_attribute.h:33
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:152
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:437
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
Oid rd_id
Definition: rel.h:116
ForeignServer * GetForeignServer(Oid serverid)
Definition: foreign.c:93
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1278
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
HeapTuple SearchSysCacheAttName(Oid relid, const char *attname)
Definition: syscache.c:1204
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
#define Anum_pg_attribute_attfdwoptions
Definition: pg_attribute.h:216
#define DatumGetPointer(X)
Definition: postgres.h:555
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define ForeignTableRelationId
#define Natts_pg_attribute
Definition: pg_attribute.h:194
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:793
#define PointerIsValid(pointer)
Definition: c.h:526
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:417
static ObjectAddress ATExecAlterColumnType ( AlteredTableInfo tab,
Relation  rel,
AlterTableCmd cmd,
LOCKMODE  lockmode 
)
static

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

8977 {
8978  char *colName = cmd->name;
8979  ColumnDef *def = (ColumnDef *) cmd->def;
8980  TypeName *typeName = def->typeName;
8981  HeapTuple heapTup;
8982  Form_pg_attribute attTup;
8983  AttrNumber attnum;
8984  HeapTuple typeTuple;
8985  Form_pg_type tform;
8986  Oid targettype;
8987  int32 targettypmod;
8988  Oid targetcollid;
8989  Node *defaultexpr;
8990  Relation attrelation;
8991  Relation depRel;
8992  ScanKeyData key[3];
8993  SysScanDesc scan;
8994  HeapTuple depTup;
8995  ObjectAddress address;
8996 
8998 
8999  /* Look up the target column */
9000  heapTup = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
9001  if (!HeapTupleIsValid(heapTup)) /* shouldn't happen */
9002  ereport(ERROR,
9003  (errcode(ERRCODE_UNDEFINED_COLUMN),
9004  errmsg("column \"%s\" of relation \"%s\" does not exist",
9005  colName, RelationGetRelationName(rel))));
9006  attTup = (Form_pg_attribute) GETSTRUCT(heapTup);
9007  attnum = attTup->attnum;
9008 
9009  /* Check for multiple ALTER TYPE on same column --- can't cope */
9010  if (attTup->atttypid != tab->oldDesc->attrs[attnum - 1]->atttypid ||
9011  attTup->atttypmod != tab->oldDesc->attrs[attnum - 1]->atttypmod)
9012  ereport(ERROR,
9013  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9014  errmsg("cannot alter type of column \"%s\" twice",
9015  colName)));
9016 
9017  /* Look up the target type (should not fail, since prep found it) */
9018  typeTuple = typenameType(NULL, typeName, &targettypmod);
9019  tform = (Form_pg_type) GETSTRUCT(typeTuple);
9020  targettype = HeapTupleGetOid(typeTuple);
9021  /* And the collation */
9022  targetcollid = GetColumnDefCollation(NULL, def, targettype);
9023 
9024  /*
9025  * If there is a default expression for the column, get it and ensure we
9026  * can coerce it to the new datatype. (We must do this before changing
9027  * the column type, because build_column_default itself will try to
9028  * coerce, and will not issue the error message we want if it fails.)
9029  *
9030  * We remove any implicit coercion steps at the top level of the old
9031  * default expression; this has been agreed to satisfy the principle of
9032  * least surprise. (The conversion to the new column type should act like
9033  * it started from what the user sees as the stored expression, and the
9034  * implicit coercions aren't going to be shown.)
9035  */
9036  if (attTup->atthasdef)
9037  {
9038  defaultexpr = build_column_default(rel, attnum);
9039  Assert(defaultexpr);
9040  defaultexpr = strip_implicit_coercions(defaultexpr);
9041  defaultexpr = coerce_to_target_type(NULL, /* no UNKNOWN params */
9042  defaultexpr, exprType(defaultexpr),
9043  targettype, targettypmod,
9046  -1);
9047  if (defaultexpr == NULL)
9048  ereport(ERROR,
9049  (errcode(ERRCODE_DATATYPE_MISMATCH),
9050  errmsg("default for column \"%s\" cannot be cast automatically to type %s",
9051  colName, format_type_be(targettype))));
9052  }
9053  else
9054  defaultexpr = NULL;
9055 
9056  /*
9057  * Find everything that depends on the column (constraints, indexes, etc),
9058  * and record enough information to let us recreate the objects.
9059  *
9060  * The actual recreation does not happen here, but only after we have
9061  * performed all the individual ALTER TYPE operations. We have to save
9062  * the info before executing ALTER TYPE, though, else the deparser will
9063  * get confused.
9064  *
9065  * There could be multiple entries for the same object, so we must check
9066  * to ensure we process each one only once. Note: we assume that an index
9067  * that implements a constraint will not show a direct dependency on the
9068  * column.
9069  */
9071 
9072  ScanKeyInit(&key[0],
9074  BTEqualStrategyNumber, F_OIDEQ,
9076  ScanKeyInit(&key[1],
9078  BTEqualStrategyNumber, F_OIDEQ,
9080  ScanKeyInit(&key[2],
9082  BTEqualStrategyNumber, F_INT4EQ,
9083  Int32GetDatum((int32) attnum));
9084 
9085  scan = systable_beginscan(depRel, DependReferenceIndexId, true,
9086  NULL, 3, key);
9087 
9088  while (HeapTupleIsValid(depTup = systable_getnext(scan)))
9089  {
9090  Form_pg_depend foundDep = (Form_pg_depend) GETSTRUCT(depTup);
9091  ObjectAddress foundObject;
9092 
9093  /* We don't expect any PIN dependencies on columns */
9094  if (foundDep->deptype == DEPENDENCY_PIN)
9095  elog(ERROR, "cannot alter type of a pinned column");
9096 
9097  foundObject.classId = foundDep->classid;
9098  foundObject.objectId = foundDep->objid;
9099  foundObject.objectSubId = foundDep->objsubid;
9100 
9101  switch (getObjectClass(&foundObject))
9102  {
9103  case OCLASS_CLASS:
9104  {
9105  char relKind = get_rel_relkind(foundObject.objectId);
9106 
9107  if (relKind == RELKIND_INDEX)
9108  {
9109  Assert(foundObject.objectSubId == 0);
9110  if (!list_member_oid(tab->changedIndexOids, foundObject.objectId))
9111  {
9113  foundObject.objectId);
9115  pg_get_indexdef_string(foundObject.objectId));
9116  }
9117  }
9118  else if (relKind == RELKIND_SEQUENCE)
9119  {
9120  /*
9121  * This must be a SERIAL column's sequence. We need
9122  * not do anything to it.
9123  */
9124  Assert(foundObject.objectSubId == 0);
9125  }
9126  else
9127  {
9128  /* Not expecting any other direct dependencies... */
9129  elog(ERROR, "unexpected object depending on column: %s",
9130  getObjectDescription(&foundObject));
9131  }
9132  break;
9133  }
9134 
9135  case OCLASS_CONSTRAINT:
9136  Assert(foundObject.objectSubId == 0);
9138  foundObject.objectId))
9139  {
9140  char *defstring = pg_get_constraintdef_command(foundObject.objectId);
9141 
9142  /*
9143  * Put NORMAL dependencies at the front of the list and
9144  * AUTO dependencies at the back. This makes sure that
9145  * foreign-key constraints depending on this column will
9146  * be dropped before unique or primary-key constraints of
9147  * the column; which we must have because the FK
9148  * constraints depend on the indexes belonging to the
9149  * unique constraints.
9150  */
9151  if (foundDep->deptype == DEPENDENCY_NORMAL)
9152  {
9153  tab->changedConstraintOids =
9154  lcons_oid(foundObject.objectId,
9155  tab->changedConstraintOids);
9156  tab->changedConstraintDefs =
9157  lcons(defstring,
9158  tab->changedConstraintDefs);
9159  }
9160  else
9161  {
9162  tab->changedConstraintOids =
9164  foundObject.objectId);
9165  tab->changedConstraintDefs =
9167  defstring);
9168  }
9169  }
9170  break;
9171 
9172  case OCLASS_REWRITE:
9173  /* XXX someday see if we can cope with revising views */
9174  ereport(ERROR,
9175  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9176  errmsg("cannot alter type of a column used by a view or rule"),
9177  errdetail("%s depends on column \"%s\"",
9178  getObjectDescription(&foundObject),
9179  colName)));
9180  break;
9181 
9182  case OCLASS_TRIGGER:
9183 
9184  /*
9185  * A trigger can depend on a column because the column is
9186  * specified as an update target, or because the column is
9187  * used in the trigger's WHEN condition. The first case would
9188  * not require any extra work, but the second case would
9189  * require updating the WHEN expression, which will take a
9190  * significant amount of new code. Since we can't easily tell
9191  * which case applies, we punt for both. FIXME someday.
9192  */
9193  ereport(ERROR,
9194  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9195  errmsg("cannot alter type of a column used in a trigger definition"),
9196  errdetail("%s depends on column \"%s\"",
9197  getObjectDescription(&foundObject),
9198  colName)));
9199  break;
9200 
9201  case OCLASS_POLICY:
9202 
9203  /*
9204  * A policy can depend on a column because the column is
9205  * specified in the policy's USING or WITH CHECK qual
9206  * expressions. It might be possible to rewrite and recheck
9207  * the policy expression, but punt for now. It's certainly
9208  * easy enough to remove and recreate the policy; still, FIXME
9209  * someday.
9210  */
9211  ereport(ERROR,
9212  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9213  errmsg("cannot alter type of a column used in a policy definition"),
9214  errdetail("%s depends on column \"%s\"",
9215  getObjectDescription(&foundObject),
9216  colName)));
9217  break;
9218 
9219  case OCLASS_DEFAULT:
9220 
9221  /*
9222  * Ignore the column's default expression, since we will fix
9223  * it below.
9224  */
9225  Assert(defaultexpr);
9226  break;
9227 
9228  case OCLASS_PROC:
9229  case OCLASS_TYPE:
9230  case OCLASS_CAST:
9231  case OCLASS_COLLATION:
9232  case OCLASS_CONVERSION:
9233  case OCLASS_LANGUAGE:
9234  case OCLASS_LARGEOBJECT:
9235  case OCLASS_OPERATOR:
9236  case OCLASS_OPCLASS:
9237  case OCLASS_OPFAMILY:
9238  case OCLASS_AMOP:
9239  case OCLASS_AMPROC:
9240  case OCLASS_SCHEMA:
9241  case OCLASS_TSPARSER:
9242  case OCLASS_TSDICT:
9243  case OCLASS_TSTEMPLATE:
9244  case OCLASS_TSCONFIG:
9245  case OCLASS_ROLE:
9246  case OCLASS_DATABASE:
9247  case OCLASS_TBLSPACE:
9248  case OCLASS_FDW:
9249  case OCLASS_FOREIGN_SERVER:
9250  case OCLASS_USER_MAPPING:
9251  case OCLASS_DEFACL:
9252  case OCLASS_EXTENSION:
9253 
9254  /*
9255  * We don't expect any of these sorts of objects to depend on
9256  * a column.
9257  */
9258  elog(ERROR, "unexpected object depending on column: %s",
9259  getObjectDescription(&foundObject));
9260  break;
9261 
9262  default:
9263