PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
tablecmds.c File Reference
#include "postgres.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/multixact.h"
#include "access/reloptions.h"
#include "access/relscan.h"
#include "access/sysattr.h"
#include "access/tupconvert.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/objectaccess.h"
#include "catalog/partition.h"
#include "catalog/pg_am.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_constraint_fn.h"
#include "catalog/pg_depend.h"
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_inherits_fn.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_tablespace.h"
#include "catalog/pg_trigger.h"
#include "catalog/pg_type.h"
#include "catalog/pg_type_fn.h"
#include "catalog/storage.h"
#include "catalog/storage_xlog.h"
#include "catalog/toasting.h"
#include "commands/cluster.h"
#include "commands/comment.h"
#include "commands/defrem.h"
#include "commands/event_trigger.h"
#include "commands/policy.h"
#include "commands/sequence.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "commands/trigger.h"
#include "commands/typecmds.h"
#include "commands/user.h"
#include "executor/executor.h"
#include "foreign/foreign.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/parsenodes.h"
#include "optimizer/clauses.h"
#include "optimizer/planner.h"
#include "optimizer/predtest.h"
#include "optimizer/prep.h"
#include "optimizer/var.h"
#include "parser/parse_clause.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_expr.h"
#include "parser/parse_oper.h"
#include "parser/parse_relation.h"
#include "parser/parse_type.h"
#include "parser/parse_utilcmd.h"
#include "parser/parser.h"
#include "pgstat.h"
#include "rewrite/rewriteDefine.h"
#include "rewrite/rewriteHandler.h"
#include "rewrite/rewriteManip.h"
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "storage/lock.h"
#include "storage/predicate.h"
#include "storage/smgr.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/relcache.h"
#include "utils/ruleutils.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/tqual.h"
#include "utils/typcache.h"
Include dependency graph for tablecmds.c:

Go to the source code of this file.

Data Structures

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

Macros

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

Typedefs

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

Functions

static void truncate_check_rel (Relation rel)
 
static ListMergeAttributes (List *schema, List *supers, char relpersistence, bool is_partition, List **supOids, List **supconstr, int *supOidCount)
 
static bool MergeCheckConstraint (List *constraints, char *name, Node *expr)
 
static void MergeAttributesIntoExisting (Relation child_rel, Relation parent_rel)
 
static void MergeConstraintsIntoExisting (Relation child_rel, Relation parent_rel)
 
static void StoreCatalogInheritance (Oid relationId, List *supers, bool child_is_partition)
 
static void StoreCatalogInheritance1 (Oid relationId, Oid parentOid, int16 seqNumber, Relation inhRelation, bool child_is_partition)
 
static int findAttrByName (const char *attributeName, List *schema)
 
static void AlterIndexNamespaces (Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
 
static void AlterSeqNamespaces (Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved, LOCKMODE lockmode)
 
static ObjectAddress ATExecAlterConstraint (Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
 
static ObjectAddress ATExecValidateConstraint (Relation rel, char *constrName, bool recurse, bool recursing, LOCKMODE lockmode)
 
static int transformColumnNameList (Oid relId, List *colList, int16 *attnums, Oid *atttypids)
 
static int transformFkeyGetPrimaryKey (Relation pkrel, Oid *indexOid, List **attnamelist, int16 *attnums, Oid *atttypids, Oid *opclasses)
 
static Oid transformFkeyCheckAttrs (Relation pkrel, int numattrs, int16 *attnums, Oid *opclasses)
 
static void checkFkeyPermissions (Relation rel, int16 *attnums, int natts)
 
static CoercionPathType findFkeyCast (Oid targetTypeId, Oid sourceTypeId, Oid *funcid)
 
static void validateCheckConstraint (Relation rel, HeapTuple constrtup)
 
static void validateForeignKeyConstraint (char *conname, Relation rel, Relation pkrel, Oid pkindOid, Oid constraintOid)
 
static void createForeignKeyTriggers (Relation rel, Oid refRelOid, Constraint *fkconstraint, Oid constraintOid, Oid indexOid)
 
static void ATController (AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
 
static void ATPrepCmd (List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
 
static void ATRewriteCatalogs (List **wqueue, LOCKMODE lockmode)
 
static void ATExecCmd (List **wqueue, AlteredTableInfo *tab, Relation rel, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static void ATRewriteTables (AlterTableStmt *parsetree, List **wqueue, LOCKMODE lockmode)
 
static void ATRewriteTable (AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode)
 
static AlteredTableInfoATGetQueueEntry (List **wqueue, Relation rel)
 
static void ATSimplePermissions (Relation rel, int allowed_targets)
 
static void ATWrongRelkindError (Relation rel, int allowed_targets)
 
static void ATSimpleRecursion (List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, LOCKMODE lockmode)
 
static void ATTypedTableRecursion (List **wqueue, Relation rel, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static Listfind_typed_table_dependencies (Oid typeOid, const char *typeName, DropBehavior behavior)
 
static void ATPrepAddColumn (List **wqueue, Relation rel, bool recurse, bool recursing, bool is_view, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static ObjectAddress ATExecAddColumn (List **wqueue, AlteredTableInfo *tab, Relation rel, ColumnDef *colDef, bool isOid, bool recurse, bool recursing, bool if_not_exists, LOCKMODE lockmode)
 
static bool check_for_column_name_collision (Relation rel, const char *colname, bool if_not_exists)
 
static void add_column_datatype_dependency (Oid relid, int32 attnum, Oid typid)
 
static void add_column_collation_dependency (Oid relid, int32 attnum, Oid collid)
 
static void ATPrepAddOids (List **wqueue, Relation rel, bool recurse, AlterTableCmd *cmd, LOCKMODE lockmode)
 
static void ATPrepDropNotNull (Relation rel, bool recurse, bool recursing)
 
static ObjectAddress ATExecDropNotNull (Relation rel, const char *colName, LOCKMODE lockmode)
 
static void ATPrepSetNotNull (Relation rel, bool recurse, bool recursing)
 
static ObjectAddress ATExecSetNotNull (AlteredTableInfo *tab, Relation rel, const char *colName, LOCKMODE lockmode)
 
static ObjectAddress ATExecColumnDefault (Relation rel, const char *colName, Node *newDefault, LOCKMODE lockmode)
 
static ObjectAddress ATExecAddIdentity (Relation rel, const char *colName, Node *def, LOCKMODE lockmode)
 
static ObjectAddress ATExecSetIdentity (Relation rel, const char *colName, Node *def, LOCKMODE lockmode)
 
static ObjectAddress ATExecDropIdentity (Relation rel, const char *colName, bool missing_ok, LOCKMODE lockmode)
 
static void ATPrepSetStatistics (Relation rel, const char *colName, 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, DependencyType deptype)
 
static ObjectAddress ATExecAddOf (Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
 
static void ATExecDropOf (Relation rel, LOCKMODE lockmode)
 
static void ATExecReplicaIdentity (Relation rel, ReplicaIdentityStmt *stmt, LOCKMODE lockmode)
 
static void ATExecGenericOptions (Relation rel, List *options)
 
static void ATExecEnableRowSecurity (Relation rel)
 
static void ATExecDisableRowSecurity (Relation rel)
 
static void ATExecForceNoForceRowSecurity (Relation rel, bool force_rls)
 
static void copy_relation_data (SMgrRelation rel, SMgrRelation dst, ForkNumber forkNum, char relpersistence)
 
static const char * storage_name (char c)
 
static void RangeVarCallbackForDropRelation (const RangeVar *rel, Oid relOid, Oid oldRelOid, void *arg)
 
static void RangeVarCallbackForAlterRelation (const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
 
static bool is_partition_attr (Relation rel, AttrNumber attnum, bool *used_in_expr)
 
static PartitionSpectransformPartitionSpec (Relation rel, PartitionSpec *partspec, char *strategy)
 
static void ComputePartitionAttrs (Relation rel, List *partParams, AttrNumber *partattrs, List **partexprs, Oid *partopclass, Oid *partcollation)
 
static void CreateInheritance (Relation child_rel, Relation parent_rel)
 
static void RemoveInheritance (Relation child_rel, Relation parent_rel)
 
static ObjectAddress ATExecAttachPartition (List **wqueue, Relation rel, PartitionCmd *cmd)
 
static 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().

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

Definition at line 291 of file tablecmds.c.

Referenced by RemoveInheritance(), and StoreCatalogInheritance1().

Typedef Documentation

Function Documentation

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

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

5516 {
5517  ObjectAddress myself,
5518  referenced;
5519 
5520  /* We know the default collation is pinned, so don't bother recording it */
5521  if (OidIsValid(collid) && collid != DEFAULT_COLLATION_OID)
5522  {
5523  myself.classId = RelationRelationId;
5524  myself.objectId = relid;
5525  myself.objectSubId = attnum;
5526  referenced.classId = CollationRelationId;
5527  referenced.objectId = collid;
5528  referenced.objectSubId = 0;
5529  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
5530  }
5531 }
#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:75
#define CollationRelationId
Definition: pg_collation.h:30
static void add_column_datatype_dependency ( Oid  relid,
int32  attnum,
Oid  typid 
)
static

Definition at line 5497 of file tablecmds.c.

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

Referenced by ATExecAddColumn(), and ATExecAlterColumnType().

5498 {
5499  ObjectAddress myself,
5500  referenced;
5501 
5502  myself.classId = RelationRelationId;
5503  myself.objectId = relid;
5504  myself.objectSubId = attnum;
5505  referenced.classId = TypeRelationId;
5506  referenced.objectId = typid;
5507  referenced.objectSubId = 0;
5508  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
5509 }
#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 12596 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().

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

12530 {
12531  HeapTuple classTup;
12532  Form_pg_class classForm;
12533  ObjectAddress thisobj;
12534  bool already_done = false;
12535 
12536  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
12537  if (!HeapTupleIsValid(classTup))
12538  elog(ERROR, "cache lookup failed for relation %u", relOid);
12539  classForm = (Form_pg_class) GETSTRUCT(classTup);
12540 
12541  Assert(classForm->relnamespace == oldNspOid);
12542 
12543  thisobj.classId = RelationRelationId;
12544  thisobj.objectId = relOid;
12545  thisobj.objectSubId = 0;
12546 
12547  /*
12548  * If the object has already been moved, don't move it again. If it's
12549  * already in the right place, don't move it, but still fire the object
12550  * access hook.
12551  */
12552  already_done = object_address_present(&thisobj, objsMoved);
12553  if (!already_done && oldNspOid != newNspOid)
12554  {
12555  /* check for duplicate name (more friendly than unique-index failure) */
12556  if (get_relname_relid(NameStr(classForm->relname),
12557  newNspOid) != InvalidOid)
12558  ereport(ERROR,
12559  (errcode(ERRCODE_DUPLICATE_TABLE),
12560  errmsg("relation \"%s\" already exists in schema \"%s\"",
12561  NameStr(classForm->relname),
12562  get_namespace_name(newNspOid))));
12563 
12564  /* classTup is a copy, so OK to scribble on */
12565  classForm->relnamespace = newNspOid;
12566 
12567  CatalogTupleUpdate(classRel, &classTup->t_self, classTup);
12568 
12569  /* Update dependency on schema if caller said so */
12570  if (hasDependEntry &&
12572  relOid,
12574  oldNspOid,
12575  newNspOid) != 1)
12576  elog(ERROR, "failed to change schema dependency for relation \"%s\"",
12577  NameStr(classForm->relname));
12578  }
12579  if (!already_done)
12580  {
12581  add_exact_object_address(&thisobj, objsMoved);
12582 
12584  }
12585 
12586  heap_freetuple(classTup);
12587 }
#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:2167
int errcode(int sqlerrcode)
Definition: elog.c:575
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2107
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1683
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h: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:165
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 12641 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().

12644 {
12645  Relation depRel;
12646  SysScanDesc scan;
12647  ScanKeyData key[2];
12648  HeapTuple tup;
12649 
12650  /*
12651  * SERIAL sequences are those having an auto dependency on one of the
12652  * table's columns (we don't care *which* column, exactly).
12653  */
12655 
12656  ScanKeyInit(&key[0],
12658  BTEqualStrategyNumber, F_OIDEQ,
12660  ScanKeyInit(&key[1],
12662  BTEqualStrategyNumber, F_OIDEQ,
12664  /* we leave refobjsubid unspecified */
12665 
12666  scan = systable_beginscan(depRel, DependReferenceIndexId, true,
12667  NULL, 2, key);
12668 
12669  while (HeapTupleIsValid(tup = systable_getnext(scan)))
12670  {
12671  Form_pg_depend depForm = (Form_pg_depend) GETSTRUCT(tup);
12672  Relation seqRel;
12673 
12674  /* skip dependencies other than auto dependencies on columns */
12675  if (depForm->refobjsubid == 0 ||
12676  depForm->classid != RelationRelationId ||
12677  depForm->objsubid != 0 ||
12678  !(depForm->deptype == DEPENDENCY_AUTO || depForm->deptype == DEPENDENCY_INTERNAL))
12679  continue;
12680 
12681  /* Use relation_open just in case it's an index */
12682  seqRel = relation_open(depForm->objid, lockmode);
12683 
12684  /* skip non-sequence relations */
12685  if (RelationGetForm(seqRel)->relkind != RELKIND_SEQUENCE)
12686  {
12687  /* No need to keep the lock */
12688  relation_close(seqRel, lockmode);
12689  continue;
12690  }
12691 
12692  /* Fix the pg_class and pg_depend entries */
12693  AlterRelationNamespaceInternal(classRel, depForm->objid,
12694  oldNspOid, newNspOid,
12695  true, objsMoved);
12696 
12697  /*
12698  * Sequences have entries in pg_type. We need to be careful to move
12699  * them to the new namespace, too.
12700  */
12702  newNspOid, false, false, objsMoved);
12703 
12704  /* Now we can close it. Keep the lock till end of transaction. */
12705  relation_close(seqRel, NoLock);
12706  }
12707 
12708  systable_endscan(scan);
12709 
12711 }
#define Anum_pg_depend_refobjid
Definition: pg_depend.h:72
#define Anum_pg_depend_refclassid
Definition: pg_depend.h:71
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define RelationGetForm(relation)
Definition: rel.h:410
#define RelationRelationId
Definition: pg_class.h:29
#define DependReferenceIndexId
Definition: indexing.h:147
#define DependRelationId
Definition: pg_depend.h:29
#define AccessShareLock
Definition: lockdefs.h:36
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition: typecmds.c: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:12526
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:416
#define BTEqualStrategyNumber
Definition: stratnum.h:31
void AlterTable ( Oid  relid,
LOCKMODE  lockmode,
AlterTableStmt stmt 
)

Definition at line 3089 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

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

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

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

Definition at line 3113 of file tablecmds.c.

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

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

3114 {
3115  Relation rel;
3116  LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
3117 
3118  rel = relation_open(relid, lockmode);
3119 
3121 
3122  ATController(NULL, rel, cmds, recurse, lockmode);
3123 }
int LOCKMODE
Definition: lockdefs.h:26
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode)
Definition: tablecmds.c:3406
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition: tablecmds.c:3158
#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 3039 of file tablecmds.c.

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

Referenced by ProcessUtilitySlow().

3040 {
3041  return RangeVarGetRelidExtended(stmt->relation, lockmode, stmt->missing_ok, false,
3043  (void *) stmt);
3044 }
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:218
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:13003
RangeVar * relation
Definition: parsenodes.h:1677
Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)

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

10622 {
10623  List *relations = NIL;
10624  ListCell *l;
10625  ScanKeyData key[1];
10626  Relation rel;
10627  HeapScanDesc scan;
10628  HeapTuple tuple;
10629  Oid orig_tablespaceoid;
10630  Oid new_tablespaceoid;
10631  List *role_oids = roleSpecsToIds(stmt->roles);
10632 
10633  /* Ensure we were not asked to move something we can't */
10634  if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
10635  stmt->objtype != OBJECT_MATVIEW)
10636  ereport(ERROR,
10637  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
10638  errmsg("only tables, indexes, and materialized views exist in tablespaces")));
10639 
10640  /* Get the orig and new tablespace OIDs */
10641  orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
10642  new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
10643 
10644  /* Can't move shared relations in to or out of pg_global */
10645  /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
10646  if (orig_tablespaceoid == GLOBALTABLESPACE_OID ||
10647  new_tablespaceoid == GLOBALTABLESPACE_OID)
10648  ereport(ERROR,
10649  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
10650  errmsg("cannot move relations in to or out of pg_global tablespace")));
10651 
10652  /*
10653  * Must have CREATE rights on the new tablespace, unless it is the
10654  * database default tablespace (which all users implicitly have CREATE
10655  * rights on).
10656  */
10657  if (OidIsValid(new_tablespaceoid) && new_tablespaceoid != MyDatabaseTableSpace)
10658  {
10659  AclResult aclresult;
10660 
10661  aclresult = pg_tablespace_aclcheck(new_tablespaceoid, GetUserId(),
10662  ACL_CREATE);
10663  if (aclresult != ACLCHECK_OK)
10665  get_tablespace_name(new_tablespaceoid));
10666  }
10667 
10668  /*
10669  * Now that the checks are done, check if we should set either to
10670  * InvalidOid because it is our database's default tablespace.
10671  */
10672  if (orig_tablespaceoid == MyDatabaseTableSpace)
10673  orig_tablespaceoid = InvalidOid;
10674 
10675  if (new_tablespaceoid == MyDatabaseTableSpace)
10676  new_tablespaceoid = InvalidOid;
10677 
10678  /* no-op */
10679  if (orig_tablespaceoid == new_tablespaceoid)
10680  return new_tablespaceoid;
10681 
10682  /*
10683  * Walk the list of objects in the tablespace and move them. This will
10684  * only find objects in our database, of course.
10685  */
10686  ScanKeyInit(&key[0],
10688  BTEqualStrategyNumber, F_OIDEQ,
10689  ObjectIdGetDatum(orig_tablespaceoid));
10690 
10692  scan = heap_beginscan_catalog(rel, 1, key);
10693  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
10694  {
10695  Oid relOid = HeapTupleGetOid(tuple);
10696  Form_pg_class relForm;
10697 
10698  relForm = (Form_pg_class) GETSTRUCT(tuple);
10699 
10700  /*
10701  * Do not move objects in pg_catalog as part of this, if an admin
10702  * really wishes to do so, they can issue the individual ALTER
10703  * commands directly.
10704  *
10705  * Also, explicitly avoid any shared tables, temp tables, or TOAST
10706  * (TOAST will be moved with the main table).
10707  */
10708  if (IsSystemNamespace(relForm->relnamespace) || relForm->relisshared ||
10709  isAnyTempNamespace(relForm->relnamespace) ||
10710  relForm->relnamespace == PG_TOAST_NAMESPACE)
10711  continue;
10712 
10713  /* Only move the object type requested */
10714  if ((stmt->objtype == OBJECT_TABLE &&
10715  relForm->relkind != RELKIND_RELATION &&
10716  relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
10717  (stmt->objtype == OBJECT_INDEX &&
10718  relForm->relkind != RELKIND_INDEX) ||
10719  (stmt->objtype == OBJECT_MATVIEW &&
10720  relForm->relkind != RELKIND_MATVIEW))
10721  continue;
10722 
10723  /* Check if we are only moving objects owned by certain roles */
10724  if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
10725  continue;
10726 
10727  /*
10728  * Handle permissions-checking here since we are locking the tables
10729  * and also to avoid doing a bunch of work only to fail part-way. Note
10730  * that permissions will also be checked by AlterTableInternal().
10731  *
10732  * Caller must be considered an owner on the table to move it.
10733  */
10734  if (!pg_class_ownercheck(relOid, GetUserId()))
10736  NameStr(relForm->relname));
10737 
10738  if (stmt->nowait &&
10740  ereport(ERROR,
10741  (errcode(ERRCODE_OBJECT_IN_USE),
10742  errmsg("aborting because lock on relation \"%s.%s\" is not available",
10743  get_namespace_name(relForm->relnamespace),
10744  NameStr(relForm->relname))));
10745  else
10747 
10748  /* Add to our list of objects to move */
10749  relations = lappend_oid(relations, relOid);
10750  }
10751 
10752  heap_endscan(scan);
10754 
10755  if (relations == NIL)
10756  ereport(NOTICE,
10757  (errcode(ERRCODE_NO_DATA_FOUND),
10758  errmsg("no matching relations in tablespace \"%s\" found",
10759  orig_tablespaceoid == InvalidOid ? "(database default)" :
10760  get_tablespace_name(orig_tablespaceoid))));
10761 
10762  /* Everything is locked, loop through and move all of the relations. */
10763  foreach(l, relations)
10764  {
10765  List *cmds = NIL;
10767 
10768  cmd->subtype = AT_SetTableSpace;
10769  cmd->name = stmt->new_tablespacename;
10770 
10771  cmds = lappend(cmds, cmd);
10772 
10774  /* OID is set by AlterTableInternal */
10775  AlterTableInternal(lfirst_oid(l), cmds, false);
10777  }
10778 
10779  return new_tablespaceoid;
10780 }
#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:1764
#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:79
void EventTriggerAlterTableStart(Node *parsetree)
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:82
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c: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:163
#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:1361
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:3113
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1426
#define NameStr(name)
Definition: c.h: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:3156
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:105
#define RELKIND_RELATION
Definition: pg_class.h:160
Definition: pg_list.h:45
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define lfirst_oid(lc)
Definition: pg_list.h:108
void EventTriggerAlterTableEnd(void)
ObjectAddress AlterTableNamespace ( AlterObjectSchemaStmt stmt,
Oid oldschema 
)

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

12418 {
12419  Relation rel;
12420  Oid relid;
12421  Oid oldNspOid;
12422  Oid nspOid;
12423  RangeVar *newrv;
12424  ObjectAddresses *objsMoved;
12425  ObjectAddress myself;
12426 
12428  stmt->missing_ok, false,
12430  (void *) stmt);
12431 
12432  if (!OidIsValid(relid))
12433  {
12434  ereport(NOTICE,
12435  (errmsg("relation \"%s\" does not exist, skipping",
12436  stmt->relation->relname)));
12437  return InvalidObjectAddress;
12438  }
12439 
12440  rel = relation_open(relid, NoLock);
12441 
12442  oldNspOid = RelationGetNamespace(rel);
12443 
12444  /* If it's an owned sequence, disallow moving it by itself. */
12445  if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
12446  {
12447  Oid tableId;
12448  int32 colId;
12449 
12450  if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
12451  sequenceIsOwned(relid, DEPENDENCY_INTERNAL, &tableId, &colId))
12452  ereport(ERROR,
12453  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
12454  errmsg("cannot move an owned sequence into another schema"),
12455  errdetail("Sequence \"%s\" is linked to table \"%s\".",
12457  get_rel_name(tableId))));
12458  }
12459 
12460  /* Get and lock schema OID and check its permissions. */
12461  newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
12463 
12464  /* common checks on switching namespaces */
12465  CheckSetNamespace(oldNspOid, nspOid);
12466 
12467  objsMoved = new_object_addresses();
12468  AlterTableNamespaceInternal(rel, oldNspOid, nspOid, objsMoved);
12469  free_object_addresses(objsMoved);
12470 
12471  ObjectAddressSet(myself, RelationRelationId, relid);
12472 
12473  if (oldschema)
12474  *oldschema = oldNspOid;
12475 
12476  /* close rel, but keep lock until commit */
12477  relation_close(rel, NoLock);
12478 
12479  return myself;
12480 }
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition: pg_depend.c:500
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:218
#define RelationRelationId
Definition: pg_class.h:29
int errcode(int sqlerrcode)
Definition: elog.c:575
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1260
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2052
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2323
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:12488
#define NoLock
Definition: lockdefs.h:34
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: tablecmds.c:13003
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define RelationGetRelationName(relation)
Definition: rel.h:436
#define ereport(elevel, rest)
Definition: elog.h:122
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition: namespace.c:2928
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:508
#define NOTICE
Definition: elog.h:37
#define NULL
Definition: c.h:229
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define AccessExclusiveLock
Definition: lockdefs.h:45
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:797
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c: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:443
void AlterTableNamespaceInternal ( Relation  rel,
Oid  oldNspOid,
Oid  nspOid,
ObjectAddresses objsMoved 
)

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

12490 {
12491  Relation classRel;
12492 
12493  Assert(objsMoved != NULL);
12494 
12495  /* OK, modify the pg_class row and pg_depend entry */
12497 
12498  AlterRelationNamespaceInternal(classRel, RelationGetRelid(rel), oldNspOid,
12499  nspOid, true, objsMoved);
12500 
12501  /* Fix the table's row type too */
12502  AlterTypeNamespaceInternal(rel->rd_rel->reltype,
12503  nspOid, false, false, objsMoved);
12504 
12505  /* Fix other dependent stuff */
12506  if (rel->rd_rel->relkind == RELKIND_RELATION ||
12507  rel->rd_rel->relkind == RELKIND_MATVIEW ||
12508  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
12509  {
12510  AlterIndexNamespaces(classRel, rel, oldNspOid, nspOid, objsMoved);
12511  AlterSeqNamespaces(classRel, rel, oldNspOid, nspOid,
12512  objsMoved, AccessExclusiveLock);
12513  AlterConstraintNamespaces(RelationGetRelid(rel), oldNspOid, nspOid,
12514  false, objsMoved);
12515  }
12516 
12517  heap_close(classRel, RowExclusiveLock);
12518 }
#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:12596
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:12641
#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:12526
#define AccessExclusiveLock
Definition: lockdefs.h:45
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RelationGetRelid(relation)
Definition: rel.h:416
static ObjectAddress ATAddCheckConstraint ( List **  wqueue,
AlteredTableInfo tab,
Relation  rel,
Constraint constr,
bool  recurse,
bool  recursing,
bool  is_readd,
LOCKMODE  lockmode 
)
static

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

6868 {
6869  List *newcons;
6870  ListCell *lcon;
6871  List *children;
6872  ListCell *child;
6874 
6875  /* At top level, permission check was done in ATPrepCmd, else do it */
6876  if (recursing)
6878 
6879  /*
6880  * Call AddRelationNewConstraints to do the work, making sure it works on
6881  * a copy of the Constraint so transformExpr can't modify the original. It
6882  * returns a list of cooked constraints.
6883  *
6884  * If the constraint ends up getting merged with a pre-existing one, it's
6885  * omitted from the returned list, which is what we want: we do not need
6886  * to do any validation work. That can only happen at child tables,
6887  * though, since we disallow merging at the top level.
6888  */
6889  newcons = AddRelationNewConstraints(rel, NIL,
6890  list_make1(copyObject(constr)),
6891  recursing | is_readd, /* allow_merge */
6892  !recursing, /* is_local */
6893  is_readd); /* is_internal */
6894 
6895  /* we don't expect more than one constraint here */
6896  Assert(list_length(newcons) <= 1);
6897 
6898  /* Add each to-be-validated constraint to Phase 3's queue */
6899  foreach(lcon, newcons)
6900  {
6901  CookedConstraint *ccon = (CookedConstraint *) lfirst(lcon);
6902 
6903  if (!ccon->skip_validation)
6904  {
6905  NewConstraint *newcon;
6906 
6907  newcon = (NewConstraint *) palloc0(sizeof(NewConstraint));
6908  newcon->name = ccon->name;
6909  newcon->contype = ccon->contype;
6910  newcon->qual = ccon->expr;
6911 
6912  tab->constraints = lappend(tab->constraints, newcon);
6913  }
6914 
6915  /* Save the actually assigned name if it was defaulted */
6916  if (constr->conname == NULL)
6917  constr->conname = ccon->name;
6918 
6919  ObjectAddressSet(address, ConstraintRelationId, ccon->conoid);
6920  }
6921 
6922  /* At this point we must have a locked-down name to use */
6923  Assert(constr->conname != NULL);
6924 
6925  /* Advance command counter in case same table is visited multiple times */
6927 
6928  /*
6929  * If the constraint got merged with an existing constraint, we're done.
6930  * We mustn't recurse to child tables in this case, because they've
6931  * already got the constraint, and visiting them again would lead to an
6932  * incorrect value for coninhcount.
6933  */
6934  if (newcons == NIL)
6935  return address;
6936 
6937  /*
6938  * If adding a NO INHERIT constraint, no need to find our children.
6939  */
6940  if (constr->is_no_inherit)
6941  return address;
6942 
6943  /*
6944  * Propagate to children as appropriate. Unlike most other ALTER
6945  * routines, we have to do this one level of recursion at a time; we can't
6946  * use find_all_inheritors to do it in one pass.
6947  */
6948  children = find_inheritance_children(RelationGetRelid(rel), lockmode);
6949 
6950  /*
6951  * Check if ONLY was specified with ALTER TABLE. If so, allow the
6952  * constraint creation only if there are no children currently. Error out
6953  * otherwise.
6954  */
6955  if (!recurse && children != NIL)
6956  ereport(ERROR,
6957  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
6958  errmsg("constraint must be added to child tables too")));
6959 
6960  foreach(child, children)
6961  {
6962  Oid childrelid = lfirst_oid(child);
6963  Relation childrel;
6964  AlteredTableInfo *childtab;
6965 
6966  /* find_inheritance_children already got lock */
6967  childrel = heap_open(childrelid, NoLock);
6968  CheckTableNotInUse(childrel, "ALTER TABLE");
6969 
6970  /* Find or create work queue entry for this table */
6971  childtab = ATGetQueueEntry(wqueue, childrel);
6972 
6973  /* Recurse to child */
6974  ATAddCheckConstraint(wqueue, childtab, childrel,
6975  constr, recurse, true, is_readd, lockmode);
6976 
6977  heap_close(childrel, NoLock);
6978  }
6979 
6980  return address;
6981 }
#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:6865
#define heap_close(r, l)
Definition: heapam.h:97
char * conname
Definition: parsenodes.h:2068
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:4625
bool skip_validation
Definition: heap.h:35
ConstrType contype
Definition: heap.h:30
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3010
#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:2074
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:4662
#define ConstraintRelationId
Definition: pg_constraint.h:29
#define copyObject(obj)
Definition: nodes.h:622
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:416
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal)
Definition: heap.c:2201
#define lfirst_oid(lc)
Definition: pg_list.h:108
static ObjectAddress ATAddForeignKeyConstraint ( AlteredTableInfo tab,
Relation  rel,
Constraint fkconstraint,
LOCKMODE  lockmode 
)
static

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

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

Definition at line 8911 of file tablecmds.c.

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

Referenced by ATPrepAlterColumnType().

8912 {
8913  Assert(expr != NULL);
8914 
8915  for (;;)
8916  {
8917  /* only one varno, so no need to check that */
8918  if (IsA(expr, Var) &&((Var *) expr)->varattno == varattno)
8919  return false;
8920  else if (IsA(expr, RelabelType))
8921  expr = (Node *) ((RelabelType *) expr)->arg;
8922  else if (IsA(expr, CoerceToDomain))
8923  {
8924  CoerceToDomain *d = (CoerceToDomain *) expr;
8925 
8927  return true;
8928  expr = (Node *) d->arg;
8929  }
8930  else
8931  return true;
8932  }
8933 }
#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 3406 of file tablecmds.c.

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

Referenced by AlterTable(), and AlterTableInternal().

3408 {
3409  List *wqueue = NIL;
3410  ListCell *lcmd;
3411 
3412  /* Phase 1: preliminary examination of commands, create work queue */
3413  foreach(lcmd, cmds)
3414  {
3415  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3416 
3417  ATPrepCmd(&wqueue, rel, cmd, recurse, false, lockmode);
3418  }
3419 
3420  /* Close the relation, but keep lock until commit */
3421  relation_close(rel, NoLock);
3422 
3423  /* Phase 2: update system catalogs */
3424  ATRewriteCatalogs(&wqueue, lockmode);
3425 
3426  /* Phase 3: scan/rewrite tables as needed */
3427  ATRewriteTables(parsetree, &wqueue, lockmode);
3428 }
#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:4080
static void ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd, bool recurse, bool recursing, LOCKMODE lockmode)
Definition: tablecmds.c:3440
#define lfirst(lc)
Definition: pg_list.h:106
static void ATRewriteCatalogs(List **wqueue, LOCKMODE lockmode)
Definition: tablecmds.c:3739
Definition: pg_list.h:45
void AtEOSubXact_on_commit_actions ( bool  isCommit,
SubTransactionId  mySubid,
SubTransactionId  parentSubid 
)

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

12895 {
12896  ListCell *cur_item;
12897  ListCell *prev_item;
12898 
12899  prev_item = NULL;
12900  cur_item = list_head(on_commits);
12901 
12902  while (cur_item != NULL)
12903  {
12904  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
12905 
12906  if (!isCommit && oc->creating_subid == mySubid)
12907  {
12908  /* cur_item must be removed */
12909  on_commits = list_delete_cell(on_commits, cur_item, prev_item);
12910  pfree(oc);
12911  if (prev_item)
12912  cur_item = lnext(prev_item);
12913  else
12914  cur_item = list_head(on_commits);
12915  }
12916  else
12917  {
12918  /* cur_item must be preserved */
12919  if (oc->creating_subid == mySubid)
12920  oc->creating_subid = parentSubid;
12921  if (oc->deleting_subid == mySubid)
12922  oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
12923  prev_item = cur_item;
12924  cur_item = lnext(prev_item);
12925  }
12926  }
12927 }
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 12851 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().

12852 {
12853  ListCell *cur_item;
12854  ListCell *prev_item;
12855 
12856  prev_item = NULL;
12857  cur_item = list_head(on_commits);
12858 
12859  while (cur_item != NULL)
12860  {
12861  OnCommitItem *oc = (OnCommitItem *) lfirst(cur_item);
12862 
12863  if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
12865  {
12866  /* cur_item must be removed */
12867  on_commits = list_delete_cell(on_commits, cur_item, prev_item);
12868  pfree(oc);
12869  if (prev_item)
12870  cur_item = lnext(prev_item);
12871  else
12872  cur_item = list_head(on_commits);
12873  }
12874  else
12875  {
12876  /* cur_item must be preserved */
12879  prev_item = cur_item;
12880  cur_item = lnext(prev_item);
12881  }
12882  }
12883 }
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 5082 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().

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

6790 {
6792 
6793  Assert(IsA(newConstraint, Constraint));
6794 
6795  /*
6796  * Currently, we only expect to see CONSTR_CHECK and CONSTR_FOREIGN nodes
6797  * arriving here (see the preprocessing done in parse_utilcmd.c). Use a
6798  * switch anyway to make it easier to add more code later.
6799  */
6800  switch (newConstraint->contype)
6801  {
6802  case CONSTR_CHECK:
6803  address =
6804  ATAddCheckConstraint(wqueue, tab, rel,
6805  newConstraint, recurse, false, is_readd,
6806  lockmode);
6807  break;
6808 
6809  case CONSTR_FOREIGN:
6810 
6811  /*
6812  * Note that we currently never recurse for FK constraints, so the
6813  * "recurse" flag is silently ignored.
6814  *
6815  * Assign or validate constraint name
6816  */
6817  if (newConstraint->conname)
6818  {
6820  RelationGetRelid(rel),
6821  RelationGetNamespace(rel),
6822  newConstraint->conname))
6823  ereport(ERROR,
6825  errmsg("constraint \"%s\" for relation \"%s\" already exists",
6826  newConstraint->conname,
6827  RelationGetRelationName(rel))));
6828  }
6829  else
6830  newConstraint->conname =
6832  strVal(linitial(newConstraint->fk_attrs)),
6833  "fkey",
6834  RelationGetNamespace(rel),
6835  NIL);
6836 
6837  address = ATAddForeignKeyConstraint(tab, rel, newConstraint,
6838  lockmode);
6839  break;
6840 
6841  default:
6842  elog(ERROR, "unrecognized constraint type: %d",
6843  (int) newConstraint->contype);
6844  }
6845 
6846  return address;
6847 }
#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:6992
#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:6865
char * conname
Definition: parsenodes.h:2068
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:436
#define ereport(elevel, rest)
Definition: elog.h:122
#define Assert(condition)
Definition: c.h: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:2065
#define elog
Definition: elog.h:219
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:31
#define RelationGetRelid(relation)
Definition: rel.h:416
List * fk_attrs
Definition: parsenodes.h:2095
#define RelationGetNamespace(relation)
Definition: rel.h:443
static ObjectAddress ATExecAddIdentity ( Relation  rel,
const char *  colName,
Node def,
LOCKMODE  lockmode 
)
static

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

5871 {
5872  Relation attrelation;
5873  HeapTuple tuple;
5874  Form_pg_attribute attTup;
5875  AttrNumber attnum;
5876  ObjectAddress address;
5877  ColumnDef *cdef = castNode(ColumnDef, def);
5878 
5880 
5881  tuple = SearchSysCacheCopyAttName(RelationGetRelid(rel), colName);
5882  if (!HeapTupleIsValid(tuple))
5883  ereport(ERROR,
5884  (errcode(ERRCODE_UNDEFINED_COLUMN),
5885  errmsg("column \"%s\" of relation \"%s\" does not exist",
5886  colName, RelationGetRelationName(rel))));
5887  attTup = (Form_pg_attribute) GETSTRUCT(tuple);
5888  attnum = attTup->attnum;
5889 
5890  /* Can't alter a system attribute */
5891  if (attnum <= 0)
5892  ereport(ERROR,
5893  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5894  errmsg("cannot alter system column \"%s\"",
5895  colName)));
5896 
5897  /*
5898  * Creating a column as identity implies NOT NULL, so adding the identity
5899  * to an existing column that is not NOT NULL would create a state that
5900  * cannot be reproduced without contortions.
5901  */
5902  if (!attTup->attnotnull)
5903  ereport(ERROR,
5904  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5905  errmsg("column \"%s\" of relation \"%s\" must be declared NOT NULL before identity can be added",
5906  colName, RelationGetRelationName(rel))));
5907 
5908  if (attTup->attidentity)
5909  ereport(ERROR,
5910  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5911  errmsg("column \"%s\" of relation \"%s\" is already an identity column",
5912  colName, RelationGetRelationName(rel))));
5913 
5914  if (attTup->atthasdef)
5915  ereport(ERROR,
5916  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5917  errmsg("column \"%s\" of relation \"%s\" already has a default value",
5918  colName, RelationGetRelationName(rel))));
5919 
5920  attTup->attidentity = cdef->identity;
5921  CatalogTupleUpdate(attrelation, &tuple->t_self, tuple);
5922 
5924  RelationGetRelid(rel),
5925  attTup->attnum);
5927  RelationGetRelid(rel), attnum);
5928  heap_freetuple(tuple);
5929 
5930  heap_close(attrelation, RowExclusiveLock);
5931 
5932  return address;
5933 }
#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:1372
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCacheCopyAttName(Oid relid, const char *attname)
Definition: syscache.c:1228
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:436
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c: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:416
static ObjectAddress ATExecAddIndex ( AlteredTableInfo tab,
Relation  rel,
IndexStmt stmt,
bool  is_rebuild,
LOCKMODE  lockmode 
)
static

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

6657 {
6658  bool check_rights;
6659  bool skip_build;
6660  bool quiet;
6661  ObjectAddress address;
6662 
6663  Assert(IsA(stmt, IndexStmt));
6664  Assert(!stmt->concurrent);
6665 
6666  /* The IndexStmt has already been through transformIndexStmt */
6667  Assert(stmt->transformed);
6668 
6669  /* suppress schema rights check when rebuilding existing index */
6670  check_rights = !is_rebuild;
6671  /* skip index build if phase 3 will do it or we're reusing an old one */
6672  skip_build = tab->rewrite > 0 || OidIsValid(stmt->oldNode);
6673  /* suppress notices when rebuilding existing index */
6674  quiet = is_rebuild;
6675 
6676  address = DefineIndex(RelationGetRelid(rel),
6677  stmt,
6678  InvalidOid, /* no predefined OID */
6679  true, /* is_alter_table */
6680  check_rights,
6681  false, /* check_not_in_use - we did it already */
6682  skip_build,
6683  quiet);
6684 
6685  /*
6686  * If TryReuseIndex() stashed a relfilenode for us, we used it for the new
6687  * index instead of building from scratch. The DROP of the old edition of
6688  * this index will have scheduled the storage for deletion at commit, so
6689  * cancel that pending deletion.
6690  */
6691  if (OidIsValid(stmt->oldNode))
6692  {
6693  Relation irel = index_open(address.objectId, NoLock);
6694 
6695  RelationPreserveStorage(irel->rd_node, true);
6696  index_close(irel, NoLock);
6697  }
6698 
6699  return address;
6700 }
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:2699
#define InvalidOid
Definition: postgres_ext.h:36
RelFileNode rd_node
Definition: rel.h:85
#define Assert(condition)
Definition: c.h:675
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
bool concurrent
Definition: parsenodes.h:2700
ObjectAddress DefineIndex(Oid relationId, IndexStmt *stmt, Oid indexRelationId, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
Definition: indexcmds.c:308
#define RelationGetRelid(relation)
Definition: rel.h:416
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
static ObjectAddress ATExecAddIndexConstraint ( AlteredTableInfo tab,
Relation  rel,
IndexStmt stmt,
LOCKMODE  lockmode 
)
static

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

6710 {
6711  Oid index_oid = stmt->indexOid;
6712  Relation indexRel;
6713  char *indexName;
6714  IndexInfo *indexInfo;
6715  char *constraintName;
6716  char constraintType;
6717  ObjectAddress address;
6718 
6719  Assert(IsA(stmt, IndexStmt));
6720  Assert(OidIsValid(index_oid));
6721  Assert(stmt->isconstraint);
6722 
6723  indexRel = index_open(index_oid, AccessShareLock);
6724 
6725  indexName = pstrdup(RelationGetRelationName(indexRel));
6726 
6727  indexInfo = BuildIndexInfo(indexRel);
6728 
6729  /* this should have been checked at parse time */
6730  if (!indexInfo->ii_Unique)
6731  elog(ERROR, "index \"%s\" is not unique", indexName);
6732 
6733  /*
6734  * Determine name to assign to constraint. We require a constraint to
6735  * have the same name as the underlying index; therefore, use the index's
6736  * existing name as the default constraint name, and if the user
6737  * explicitly gives some other name for the constraint, rename the index
6738  * to match.
6739  */
6740  constraintName = stmt->idxname;
6741  if (constraintName == NULL)
6742  constraintName = indexName;
6743  else if (strcmp(constraintName, indexName) != 0)
6744  {
6745  ereport(NOTICE,
6746  (errmsg("ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index \"%s\" to \"%s\"",
6747  indexName, constraintName)));
6748  RenameRelationInternal(index_oid, constraintName, false);
6749  }
6750 
6751  /* Extra checks needed if making primary key */
6752  if (stmt->primary)
6753  index_check_primary_key(rel, indexInfo, true);
6754 
6755  /* Note we currently don't support EXCLUSION constraints here */
6756  if (stmt->primary)
6757  constraintType = CONSTRAINT_PRIMARY;
6758  else
6759  constraintType = CONSTRAINT_UNIQUE;
6760 
6761  /* Create the catalog entries for the constraint */
6762  address = index_constraint_create(rel,
6763  index_oid,
6764  indexInfo,
6765  constraintName,
6766  constraintType,
6767  stmt->deferrable,
6768  stmt->initdeferred,
6769  stmt->primary,
6770  true, /* update pg_index */
6771  true, /* remove old dependencies */
6773  false); /* is_internal */
6774 
6775  index_close(indexRel, NoLock);
6776 
6777  return address;
6778 }
bool deferrable
Definition: parsenodes.h:2697
bool primary
Definition: parsenodes.h:2695
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal)
Definition: tablecmds.c:2914
#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:2692
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:436
#define ereport(elevel, rest)
Definition: elog.h:122
char * idxname
Definition: parsenodes.h:2683
bool allowSystemTableMods
Definition: globals.c:112
#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:2698
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
bool isconstraint
Definition: parsenodes.h:2696
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 10931 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().

10932 {
10933  Relation parent_rel;
10934  List *children;
10935  ObjectAddress address;
10936 
10937  /*
10938  * A self-exclusive lock is needed here. See the similar case in
10939  * MergeAttributes() for a full explanation.
10940  */
10941  parent_rel = heap_openrv(parent, ShareUpdateExclusiveLock);
10942 
10943  /*
10944  * Must be owner of both parent and child -- child was checked by
10945  * ATSimplePermissions call in ATPrepCmd
10946  */
10948 
10949  /* Permanent rels cannot inherit from temporary ones */
10950  if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
10951  child_rel->rd_rel->relpersistence != RELPERSISTENCE_TEMP)
10952  ereport(ERROR,
10953  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10954  errmsg("cannot inherit from temporary relation \"%s\"",
10955  RelationGetRelationName(parent_rel))));
10956 
10957  /* If parent rel is temp, it must belong to this session */
10958  if (parent_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
10959  !parent_rel->rd_islocaltemp)
10960  ereport(ERROR,
10961  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10962  errmsg("cannot inherit from temporary relation of another session")));
10963 
10964  /* Ditto for the child */
10965  if (child_rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
10966  !child_rel->rd_islocaltemp)
10967  ereport(ERROR,
10968  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10969  errmsg("cannot inherit to temporary relation of another session")));
10970 
10971  /* Prevent partitioned tables from becoming inheritance parents */
10972  if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
10973  ereport(ERROR,
10974  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10975  errmsg("cannot inherit from partitioned table \"%s\"",
10976  parent->relname)));
10977 
10978  /* Likewise for partitions */
10979  if (parent_rel->rd_rel->relispartition)
10980  ereport(ERROR,
10981  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
10982  errmsg("cannot inherit from a partition")));
10983 
10984  /*
10985  * Prevent circularity by seeing if proposed parent inherits from child.
10986  * (In particular, this disallows making a rel inherit from itself.)
10987  *
10988  * This is not completely bulletproof because of race conditions: in
10989  * multi-level inheritance trees, someone else could concurrently be
10990  * making another inheritance link that closes the loop but does not join
10991  * either of the rels we have locked. Preventing that seems to require
10992  * exclusive locks on the entire inheritance tree, which is a cure worse
10993  * than the disease. find_all_inheritors() will cope with circularity
10994  * anyway, so don't sweat it too much.
10995  *
10996  * We use weakest lock we can on child's children, namely AccessShareLock.
10997  */
10998  children = find_all_inheritors(RelationGetRelid(child_rel),
11000 
11001  if (list_member_oid(children, RelationGetRelid(parent_rel)))
11002  ereport(ERROR,
11003  (errcode(ERRCODE_DUPLICATE_TABLE),
11004  errmsg("circular inheritance not allowed"),
11005  errdetail("\"%s\" is already a child of \"%s\".",
11006  parent->relname,
11007  RelationGetRelationName(child_rel))));
11008 
11009  /* If parent has OIDs then child must have OIDs */
11010  if (parent_rel->rd_rel->relhasoids && !child_rel->rd_rel->relhasoids)
11011  ereport(ERROR,
11012  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11013  errmsg("table \"%s\" without OIDs cannot inherit from table \"%s\" with OIDs",
11014  RelationGetRelationName(child_rel),
11015  RelationGetRelationName(parent_rel))));
11016 
11017  /* OK to create inheritance */
11018  CreateInheritance(child_rel, parent_rel);
11019 
11021  RelationGetRelid(parent_rel));
11022 
11023  /* keep our lock on the parent relation until commit */
11024  heap_close(parent_rel, NoLock);
11025 
11026  return address;
11027 }
#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:11037
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:436
#define ereport(elevel, rest)
Definition: elog.h:122
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c: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:4662
#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:416
static ObjectAddress ATExecAddOf ( Relation  rel,
const TypeName ofTypename,
LOCKMODE  lockmode 
)
static

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

11741 {
11742  Oid relid = RelationGetRelid(rel);
11743  Type typetuple;
11744  Oid typeid;
11745  Relation inheritsRelation,
11746  relationRelation;
11747  SysScanDesc scan;
11748  ScanKeyData key;
11749  AttrNumber table_attno,
11750  type_attno;
11751  TupleDesc typeTupleDesc,
11752  tableTupleDesc;
11753  ObjectAddress tableobj,
11754  typeobj;
11755  HeapTuple classtuple;
11756 
11757  /* Validate the type. */
11758  typetuple = typenameType(NULL, ofTypename, NULL);
11759  check_of_type(typetuple);
11760  typeid = HeapTupleGetOid(typetuple);
11761 
11762  /* Fail if the table has any inheritance parents. */
11763  inheritsRelation = heap_open(InheritsRelationId, AccessShareLock);
11764  ScanKeyInit(&key,
11766  BTEqualStrategyNumber, F_OIDEQ,
11767  ObjectIdGetDatum(relid));
11768  scan = systable_beginscan(inheritsRelation, InheritsRelidSeqnoIndexId,
11769  true, NULL, 1, &key);
11771  ereport(ERROR,
11772  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
11773  errmsg("typed tables cannot inherit")));
11774  systable_endscan(scan);
11775  heap_close(inheritsRelation, AccessShareLock);
11776 
11777  /*
11778  * Check the tuple descriptors for compatibility. Unlike inheritance, we
11779  * require that the order also match. However, attnotnull need not match.
11780  * Also unlike inheritance, we do not require matching relhasoids.
11781  */
11782  typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
11783  tableTupleDesc = RelationGetDescr(rel);
11784  table_attno = 1;
11785  for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
11786  {
11787  Form_pg_attribute type_attr,
11788  table_attr;
11789  const char *type_attname,
11790  *table_attname;
11791 
11792  /* Get the next non-dropped type attribute. */
11793  type_attr = typeTupleDesc->attrs[type_attno - 1];
11794  if (type_attr->attisdropped)
11795  continue;
11796  type_attname = NameStr(type_attr->attname);
11797 
11798  /* Get the next non-dropped table attribute. */
11799  do
11800  {
11801  if (table_attno > tableTupleDesc->natts)
11802  ereport(ERROR,
11803  (errcode(ERRCODE_DATATYPE_MISMATCH),
11804  errmsg("table is missing column \"%s\"",
11805  type_attname)));
11806  table_attr = tableTupleDesc->attrs[table_attno++ - 1];
11807  } while (table_attr->attisdropped);
11808  table_attname = NameStr(table_attr->attname);
11809 
11810  /* Compare name. */
11811  if (strncmp(table_attname, type_attname, NAMEDATALEN) != 0)
11812  ereport(ERROR,
11813  (errcode(ERRCODE_DATATYPE_MISMATCH),
11814  errmsg("table has column \"%s\" where type requires \"%s\"",
11815  table_attname, type_attname)));
11816 
11817  /* Compare type. */
11818  if (table_attr->atttypid != type_attr->atttypid ||
11819  table_attr->atttypmod != type_attr->atttypmod ||
11820  table_attr->attcollation != type_attr->attcollation)
11821  ereport(ERROR,
11822  (errcode(ERRCODE_DATATYPE_MISMATCH),
11823  errmsg("table \"%s\" has different type for column \"%s\"",
11824  RelationGetRelationName(rel), type_attname)));
11825  }
11826  DecrTupleDescRefCount(typeTupleDesc);
11827 
11828  /* Any remaining columns at the end of the table had better be dropped. */
11829  for (; table_attno <= tableTupleDesc->natts; table_attno++)
11830  {
11831  Form_pg_attribute table_attr = tableTupleDesc->attrs[table_attno - 1];
11832 
11833  if (!table_attr->attisdropped)
11834  ereport(ERROR,
11835  (errcode(ERRCODE_DATATYPE_MISMATCH),
11836  errmsg("table has extra column \"%s\"",
11837  NameStr(table_attr->attname))));
11838  }
11839 
11840  /* If the table was already typed, drop the existing dependency. */
11841  if (rel->rd_rel->reloftype)
11842  drop_parent_dependency(relid, TypeRelationId, rel->rd_rel->reloftype,
11844 
11845  /* Record a dependency on the new type. */
11846  tableobj.classId = RelationRelationId;
11847  tableobj.objectId = relid;
11848  tableobj.objectSubId = 0;
11849  typeobj.classId = TypeRelationId;
11850  typeobj.objectId = typeid;
11851  typeobj.objectSubId = 0;
11852  recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
11853 
11854  /* Update pg_class.reloftype */
11855  relationRelation = heap_open(RelationRelationId, RowExclusiveLock);
11856  classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
11857  if (!HeapTupleIsValid(classtuple))
11858  elog(ERROR, "cache lookup failed for relation %u", relid);
11859  ((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
11860  CatalogTupleUpdate(relationRelation, &classtuple->t_self, classtuple);
11861 
11863 
11864  heap_freetuple(classtuple);
11865  heap_close(relationRelation, RowExclusiveLock);
11866 
11867  ReleaseSysCache(typetuple);
11868 
11869  return typeobj;
11870 }
#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:428
static void drop_parent_dependency(Oid relid, Oid refclassid, Oid refobjid, DependencyType deptype)
Definition: tablecmds.c:11688
#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:1372
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:5019
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:436
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
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:165
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:416
#define BTEqualStrategyNumber
Definition: stratnum.h:31
static ObjectAddress ATExecAlterColumnGenericOptions ( Relation  rel,
const char *  colName,
List options,
LOCKMODE  lockmode 
)
static

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

9365 {
9366  Relation ftrel;
9367  Relation attrel;
9368  ForeignServer *server;
9369  ForeignDataWrapper *fdw;
9370  HeapTuple tuple;
9371  HeapTuple newtuple;
9372  bool isnull;
9373  Datum repl_val[Natts_pg_attribute];
9374  bool repl_null[Natts_pg_attribute];
9375  bool repl_repl[Natts_pg_attribute];
9376  Datum datum;
9377  Form_pg_foreign_table fttableform;
9378  Form_pg_attribute atttableform;
9379  AttrNumber attnum;
9380  ObjectAddress address;
9381 
9382  if (options == NIL)
9383  return InvalidObjectAddress;
9384 
9385  /* First, determine FDW validator associated to the foreign table. */
9387  tuple = SearchSysCache1(FOREIGNTABLEREL, rel->rd_id);
9388  if (!HeapTupleIsValid(tuple))
9389  ereport(ERROR,
9390  (errcode(ERRCODE_UNDEFINED_OBJECT),
9391  errmsg("foreign table \"%s\" does not exist",
9392  RelationGetRelationName(rel))));
9393  fttableform = (Form_pg_foreign_table) GETSTRUCT(tuple);
9394  server = GetForeignServer(fttableform->ftserver);
9395  fdw = GetForeignDataWrapper(server->fdwid);
9396 
9397  heap_close(ftrel, AccessShareLock);
9398  ReleaseSysCache(tuple);
9399 
9401  tuple = SearchSysCacheAttName(RelationGetRelid(rel), colName);
9402  if (!HeapTupleIsValid(tuple))
9403  ereport(ERROR,
9404  (errcode(ERRCODE_UNDEFINED_COLUMN),
9405  errmsg("column \"%s\" of relation \"%s\" does not exist",
9406  colName, RelationGetRelationName(rel))));
9407 
9408  /* Prevent them from altering a system attribute */
9409  atttableform = (Form_pg_attribute) GETSTRUCT(tuple);
9410  attnum = atttableform->attnum;
9411  if (attnum <= 0)
9412  ereport(ERROR,
9413  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9414  errmsg("cannot alter system column \"%s\"", colName)));
9415 
9416 
9417  /* Initialize buffers for new tuple values */
9418  memset(repl_val, 0, sizeof(repl_val));
9419  memset(repl_null, false, sizeof(repl_null));
9420  memset(repl_repl, false, sizeof(repl_repl));
9421 
9422  /* Extract the current options */
9423  datum = SysCacheGetAttr(ATTNAME,
9424  tuple,
9426  &isnull);
9427  if (isnull)
9428  datum = PointerGetDatum(NULL);
9429 
9430  /* Transform the options */
9432  datum,
9433  options,
9434  fdw->fdwvalidator);
9435 
9436  if (PointerIsValid(DatumGetPointer(datum)))
9437  repl_val[Anum_pg_attribute_attfdwoptions - 1] = datum;
9438  else
9439  repl_null[Anum_pg_attribute_attfdwoptions - 1] = true;
9440 
9441  repl_repl[Anum_pg_attribute_attfdwoptions - 1] = true;
9442 
9443  /* Everything looks good - update the tuple */
9444 
9445  newtuple = heap_modify_tuple(tuple, RelationGetDescr(attrel),
9446  repl_val, repl_null, repl_repl);
9447 
9448  CatalogTupleUpdate(attrel, &newtuple->t_self, newtuple);
9449 
9451  RelationGetRelid(rel),
9452  atttableform->attnum);
9454  RelationGetRelid(rel), attnum);
9455 
9456  ReleaseSysCache(tuple);
9457 
9458  heap_close(attrel, RowExclusiveLock);
9459 
9460  heap_freetuple(newtuple);
9461 
9462  return address;
9463 }
#define NIL
Definition: pg_list.h:69
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define RelationGetDescr(relation)
Definition: rel.h:428
Datum transformGenericOptions(Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
Definition: foreigncmds.c:109
#define PointerGetDatum(X)
Definition: postgres.h:562
#define RelationRelationId
Definition: pg_class.h:29
#define AccessShareLock
Definition: lockdefs.h:36
#define AttributeRelationId
Definition: pg_attribute.h:33
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
ForeignDataWrapper * GetForeignDataWrapper(Oid fdwid)
Definition: foreign.c:35
FormData_pg_foreign_table * Form_pg_foreign_table
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:436
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
Oid rd_id
Definition: rel.h:116
ForeignServer * GetForeignServer(Oid serverid)
Definition: foreign.c:93
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1279
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:1205
#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:791
#define PointerIsValid(pointer)
Definition: c.h:526
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:416
static ObjectAddress ATExecAlterColumnType ( AlteredTableInfo tab,
Relation  rel,
AlterTableCmd cmd,
LOCKMODE  lockmode 
)
static

Definition at line 8941 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_AM, OCLASS_AMOP, OCLASS_AMPROC, OCLASS_CAST, OCLASS_CLASS, OCLASS_COLLATION, OCLASS_CONSTRAINT, OCLASS_CONVERSION, OCLASS_DATABASE, OCLASS_DEFACL, OCLASS_DEFAULT, OCLASS_EVENT_TRIGGER, OCLASS_EXTENSION, OCLASS_FDW, OCLASS_FOREIGN_SERVER, OCLASS_LANGUAGE, OCLASS_LARGEOBJECT, OCLASS_OPCLASS, OCLASS_OPERATOR, OCLASS_OPFAMILY, OCLASS_POLICY, OCLASS_PROC, OCLASS_PUBLICATION, OCLASS_PUBLICATION_REL, OCLASS_REWRITE, OCLASS_ROLE, OCLASS_SCHEMA, OCLASS_STATISTIC_EXT, OCLASS_SUBSCRIPTION, OCLASS_TBLSPACE, OCLASS_TRANSFORM, OCLASS_TRIGGER, OCLASS_TSCONFIG, OCLASS_TSDICT, OCLASS_TSPARSER, OCLASS_TSTEMPLATE, OCLASS_TYPE, OCLASS_USER_MAPPING, AlteredTableInfo::oldDesc, pg_get_constraintdef_command(), pg_get_indexdef_string(), RelationGetRelationName, RelationGetRelid, RelationRelationId, ReleaseSysCache(), RELKIND_INDEX, RELKIND_SEQUENCE, RemoveAttrDefault(), RemoveStatistics(), RowExclusiveLock, ScanKeyInit(), SearchSysCacheCopyAttName(), StoreAttrDefault(), strip_implicit_coercions(), systable_beginscan(), systable_endscan(), systable_getnext(), ColumnDef::typeName, typenameType(), TypeRelationId, and UpdateStatisticsForTypeChange().

Referenced by ATExecCmd().

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