PostgreSQL Source Code git master
Loading...
Searching...
No Matches
typecmds.h File Reference
#include "access/htup.h"
#include "catalog/dependency.h"
#include "parser/parse_node.h"
Include dependency graph for typecmds.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define DEFAULT_TYPDELIM   ','
 

Functions

ObjectAddress DefineType (ParseState *pstate, List *names, List *parameters)
 
void RemoveTypeById (Oid typeOid)
 
ObjectAddress DefineDomain (ParseState *pstate, CreateDomainStmt *stmt)
 
ObjectAddress DefineEnum (CreateEnumStmt *stmt)
 
ObjectAddress DefineRange (ParseState *pstate, CreateRangeStmt *stmt)
 
ObjectAddress AlterEnum (AlterEnumStmt *stmt)
 
ObjectAddress DefineCompositeType (RangeVar *typevar, List *coldeflist)
 
Oid AssignTypeArrayOid (void)
 
Oid AssignTypeMultirangeOid (void)
 
Oid AssignTypeMultirangeArrayOid (void)
 
ObjectAddress AlterDomainDefault (List *names, Node *defaultRaw)
 
ObjectAddress AlterDomainNotNull (List *names, bool notNull)
 
ObjectAddress AlterDomainAddConstraint (List *names, Node *newConstraint, ObjectAddress *constrAddr)
 
ObjectAddress AlterDomainValidateConstraint (List *names, const char *constrName)
 
ObjectAddress AlterDomainDropConstraint (List *names, const char *constrName, DropBehavior behavior, bool missing_ok)
 
void checkDomainOwner (HeapTuple tup)
 
ObjectAddress RenameType (RenameStmt *stmt)
 
ObjectAddress AlterTypeOwner (List *names, Oid newOwnerId, ObjectType objecttype)
 
void AlterTypeOwner_oid (Oid typeOid, Oid newOwnerId, bool hasDependEntry)
 
void AlterTypeOwnerInternal (Oid typeOid, Oid newOwnerId)
 
ObjectAddress AlterTypeNamespace (List *names, const char *newschema, ObjectType objecttype, Oid *oldschema)
 
Oid AlterTypeNamespace_oid (Oid typeOid, Oid nspOid, bool ignoreDependent, ObjectAddresses *objsMoved)
 
Oid AlterTypeNamespaceInternal (Oid typeOid, Oid nspOid, bool isImplicitArray, bool ignoreDependent, bool errorOnTableType, ObjectAddresses *objsMoved)
 
ObjectAddress AlterType (AlterTypeStmt *stmt)
 

Macro Definition Documentation

◆ DEFAULT_TYPDELIM

#define DEFAULT_TYPDELIM   ','

Definition at line 22 of file typecmds.h.

Function Documentation

◆ AlterDomainAddConstraint()

ObjectAddress AlterDomainAddConstraint ( List names,
Node newConstraint,
ObjectAddress constrAddr 
)
extern

Definition at line 2960 of file typecmds.c.

2962{
2963 TypeName *typename;
2964 Oid domainoid;
2966 HeapTuple tup;
2968 Constraint *constr;
2969 char *ccbin;
2971
2972 /* Make a TypeName so we can use standard type lookup machinery */
2973 typename = makeTypeNameFromNameList(names);
2974 domainoid = typenameTypeId(NULL, typename);
2975
2976 /* Look up the domain in the type table */
2978
2980 if (!HeapTupleIsValid(tup))
2981 elog(ERROR, "cache lookup failed for type %u", domainoid);
2983
2984 /* Check it's a domain and check user has permission for ALTER DOMAIN */
2986
2988 elog(ERROR, "unrecognized node type: %d",
2989 (int) nodeTag(newConstraint));
2990
2991 constr = (Constraint *) newConstraint;
2992
2993 /* enforced by parser */
2994 Assert(constr->contype == CONSTR_CHECK || constr->contype == CONSTR_NOTNULL);
2995
2996 if (constr->contype == CONSTR_CHECK)
2997 {
2998 /*
2999 * First, process the constraint expression and add an entry to
3000 * pg_constraint.
3001 */
3002
3003 ccbin = domainAddCheckConstraint(domainoid, typTup->typnamespace,
3004 typTup->typbasetype, typTup->typtypmod,
3005 constr, NameStr(typTup->typname), constrAddr);
3006
3007
3008 /*
3009 * If requested to validate the constraint, test all values stored in
3010 * the attributes based on the domain the constraint is being added
3011 * to.
3012 */
3013 if (!constr->skip_validation)
3015
3016 /*
3017 * We must send out an sinval message for the domain, to ensure that
3018 * any dependent plans get rebuilt. Since this command doesn't change
3019 * the domain's pg_type row, that won't happen automatically; do it
3020 * manually.
3021 */
3023 }
3024 else if (constr->contype == CONSTR_NOTNULL)
3025 {
3026 /* Is the domain already set NOT NULL? */
3027 if (typTup->typnotnull)
3028 {
3030 return address;
3031 }
3033 typTup->typbasetype, typTup->typtypmod,
3034 constr, NameStr(typTup->typname), constrAddr);
3035
3036 if (!constr->skip_validation)
3038
3039 typTup->typnotnull = true;
3040 CatalogTupleUpdate(typrel, &tup->t_self, tup);
3041 }
3042
3044
3045 /* Clean up */
3047
3048 return address;
3049}
#define NameStr(name)
Definition c.h:765
#define Assert(condition)
Definition c.h:873
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
void CatalogTupleUpdate(Relation heapRel, const ItemPointerData *otid, HeapTuple tup)
Definition indexing.c:313
void CacheInvalidateHeapTuple(Relation relation, HeapTuple tuple, HeapTuple newtuple)
Definition inval.c:1571
#define ShareLock
Definition lockdefs.h:40
#define RowExclusiveLock
Definition lockdefs.h:38
TypeName * makeTypeNameFromNameList(List *names)
Definition makefuncs.c:531
#define IsA(nodeptr, _type_)
Definition nodes.h:164
#define nodeTag(nodeptr)
Definition nodes.h:139
const ObjectAddress InvalidObjectAddress
#define ObjectAddressSet(addr, class_id, object_id)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition parse_type.c:291
@ CONSTR_NOTNULL
@ CONSTR_CHECK
FormData_pg_type * Form_pg_type
Definition pg_type.h:261
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:262
unsigned int Oid
static int fb(int x)
ConstrType contype
bool skip_validation
#define SearchSysCacheCopy1(cacheId, key1)
Definition syscache.h:91
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40
static char * domainAddCheckConstraint(Oid domainOid, Oid domainNamespace, Oid baseTypeOid, int typMod, Constraint *constr, const char *domainName, ObjectAddress *constrAddr)
Definition typecmds.c:3541
void checkDomainOwner(HeapTuple tup)
Definition typecmds.c:3521
static void domainAddNotNullConstraint(Oid domainOid, Oid domainNamespace, Oid baseTypeOid, int typMod, Constraint *constr, const char *domainName, ObjectAddress *constrAddr)
Definition typecmds.c:3701
static void validateDomainNotNullConstraint(Oid domainoid)
Definition typecmds.c:3161
static void validateDomainCheckConstraint(Oid domainoid, const char *ccbin, LOCKMODE lockmode)
Definition typecmds.c:3233

References Assert, CacheInvalidateHeapTuple(), CatalogTupleUpdate(), checkDomainOwner(), CONSTR_CHECK, CONSTR_NOTNULL, Constraint::contype, domainAddCheckConstraint(), domainAddNotNullConstraint(), elog, ERROR, fb(), GETSTRUCT(), HeapTupleIsValid, InvalidObjectAddress, IsA, makeTypeNameFromNameList(), NameStr, nodeTag, ObjectAddressSet, ObjectIdGetDatum(), RowExclusiveLock, SearchSysCacheCopy1, ShareLock, Constraint::skip_validation, table_close(), table_open(), typenameTypeId(), validateDomainCheckConstraint(), and validateDomainNotNullConstraint().

Referenced by ATExecCmd(), and ProcessUtilitySlow().

◆ AlterDomainDefault()

ObjectAddress AlterDomainDefault ( List names,
Node defaultRaw 
)
extern

Definition at line 2639 of file typecmds.c.

2640{
2641 TypeName *typename;
2642 Oid domainoid;
2643 HeapTuple tup;
2644 ParseState *pstate;
2645 Relation rel;
2646 char *defaultValue;
2647 Node *defaultExpr = NULL; /* NULL if no default specified */
2649 bool new_record_nulls[Natts_pg_type] = {0};
2650 bool new_record_repl[Natts_pg_type] = {0};
2651 HeapTuple newtuple;
2653 ObjectAddress address;
2654
2655 /* Make a TypeName so we can use standard type lookup machinery */
2656 typename = makeTypeNameFromNameList(names);
2657 domainoid = typenameTypeId(NULL, typename);
2658
2659 /* Look up the domain in the type table */
2661
2663 if (!HeapTupleIsValid(tup))
2664 elog(ERROR, "cache lookup failed for type %u", domainoid);
2666
2667 /* Check it's a domain and check user has permission for ALTER DOMAIN */
2669
2670 /* Setup new tuple */
2671
2672 /* Store the new default into the tuple */
2673 if (defaultRaw)
2674 {
2675 /* Create a dummy ParseState for transformExpr */
2676 pstate = make_parsestate(NULL);
2677
2678 /*
2679 * Cook the colDef->raw_expr into an expression. Note: Name is
2680 * strictly for error message
2681 */
2683 typTup->typbasetype,
2684 typTup->typtypmod,
2685 NameStr(typTup->typname),
2686 0);
2687
2688 /*
2689 * If the expression is just a NULL constant, we treat the command
2690 * like ALTER ... DROP DEFAULT. (But see note for same test in
2691 * DefineDomain.)
2692 */
2693 if (defaultExpr == NULL ||
2695 {
2696 /* Default is NULL, drop it */
2697 defaultExpr = NULL;
2702 }
2703 else
2704 {
2705 /*
2706 * Expression must be stored as a nodeToString result, but we also
2707 * require a valid textual representation (mainly to make life
2708 * easier for pg_dump).
2709 */
2711 NIL, false, false);
2712
2713 /*
2714 * Form an updated tuple with the new default and write it back.
2715 */
2717
2721 }
2722 }
2723 else
2724 {
2725 /* ALTER ... DROP DEFAULT */
2730 }
2731
2732 newtuple = heap_modify_tuple(tup, RelationGetDescr(rel),
2735
2736 CatalogTupleUpdate(rel, &tup->t_self, newtuple);
2737
2738 /* Rebuild dependencies */
2739 GenerateTypeDependencies(newtuple,
2740 rel,
2742 NULL, /* don't have typacl handy */
2743 0, /* relation kind is n/a */
2744 false, /* a domain isn't an implicit array */
2745 false, /* nor is it any kind of dependent type */
2746 false, /* don't touch extension membership */
2747 true); /* We do need to rebuild dependencies */
2748
2750
2752
2753 /* Clean up */
2755 heap_freetuple(newtuple);
2756
2757 return address;
2758}
#define CStringGetTextDatum(s)
Definition builtins.h:97
Node * cookDefault(ParseState *pstate, Node *raw_default, Oid atttypid, int32 atttypmod, const char *attname, char attgenerated)
Definition heap.c:3320
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition heaptuple.c:1210
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1435
#define InvokeObjectPostAlterHook(classId, objectId, subId)
char * nodeToString(const void *obj)
Definition outfuncs.c:802
ParseState * make_parsestate(ParseState *parentParseState)
Definition parse_node.c:39
#define NIL
Definition pg_list.h:68
void GenerateTypeDependencies(HeapTuple typeTuple, Relation typeCatalog, Node *defaultExpr, void *typacl, char relationKind, bool isImplicitArray, bool isDependentType, bool makeExtensionDep, bool rebuild)
Definition pg_type.c:555
uint64_t Datum
Definition postgres.h:70
#define RelationGetDescr(relation)
Definition rel.h:540
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition ruleutils.c:3648
Definition nodes.h:135

References CatalogTupleUpdate(), checkDomainOwner(), cookDefault(), CStringGetTextDatum, deparse_expression(), elog, ERROR, fb(), GenerateTypeDependencies(), GETSTRUCT(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, InvokeObjectPostAlterHook, IsA, make_parsestate(), makeTypeNameFromNameList(), NameStr, NIL, nodeToString(), ObjectAddressSet, ObjectIdGetDatum(), RelationGetDescr, RowExclusiveLock, SearchSysCacheCopy1, table_close(), table_open(), and typenameTypeId().

Referenced by ProcessUtilitySlow().

◆ AlterDomainDropConstraint()

ObjectAddress AlterDomainDropConstraint ( List names,
const char constrName,
DropBehavior  behavior,
bool  missing_ok 
)
extern

Definition at line 2854 of file typecmds.c.

2856{
2857 TypeName *typename;
2858 Oid domainoid;
2859 HeapTuple tup;
2860 Relation rel;
2863 ScanKeyData skey[3];
2865 bool found = false;
2866 ObjectAddress address;
2867
2868 /* Make a TypeName so we can use standard type lookup machinery */
2869 typename = makeTypeNameFromNameList(names);
2870 domainoid = typenameTypeId(NULL, typename);
2871
2872 /* Look up the domain in the type table */
2874
2876 if (!HeapTupleIsValid(tup))
2877 elog(ERROR, "cache lookup failed for type %u", domainoid);
2878
2879 /* Check it's a domain and check user has permission for ALTER DOMAIN */
2881
2882 /* Grab an appropriate lock on the pg_constraint relation */
2884
2885 /* Find and remove the target constraint */
2886 ScanKeyInit(&skey[0],
2890 ScanKeyInit(&skey[1],
2894 ScanKeyInit(&skey[2],
2898
2900 NULL, 3, skey);
2901
2902 /* There can be at most one matching row */
2903 if ((contup = systable_getnext(conscan)) != NULL)
2904 {
2907
2908 if (construct->contype == CONSTRAINT_NOTNULL)
2909 {
2910 ((Form_pg_type) GETSTRUCT(tup))->typnotnull = false;
2911 CatalogTupleUpdate(rel, &tup->t_self, tup);
2912 }
2913
2914 conobj.classId = ConstraintRelationId;
2915 conobj.objectId = construct->oid;
2916 conobj.objectSubId = 0;
2917
2918 performDeletion(&conobj, behavior, 0);
2919 found = true;
2920 }
2921
2922 /* Clean up after the scan */
2925
2926 if (!found)
2927 {
2928 if (!missing_ok)
2929 ereport(ERROR,
2931 errmsg("constraint \"%s\" of domain \"%s\" does not exist",
2932 constrName, TypeNameToString(typename))));
2933 else
2935 (errmsg("constraint \"%s\" of domain \"%s\" does not exist, skipping",
2936 constrName, TypeNameToString(typename))));
2937 }
2938
2939 /*
2940 * We must send out an sinval message for the domain, to ensure that any
2941 * dependent plans get rebuilt. Since this command doesn't change the
2942 * domain's pg_type row, that won't happen automatically; do it manually.
2943 */
2945
2947
2948 /* Clean up */
2950
2951 return address;
2952}
void performDeletion(const ObjectAddress *object, DropBehavior behavior, int flags)
Definition dependency.c:274
int errcode(int sqlerrcode)
Definition elog.c:863
int errmsg(const char *fmt,...)
Definition elog.c:1080
#define NOTICE
Definition elog.h:35
#define ereport(elevel,...)
Definition elog.h:150
void systable_endscan(SysScanDesc sysscan)
Definition genam.c:603
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition genam.c:514
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition genam.c:388
char * TypeNameToString(const TypeName *typeName)
Definition parse_type.c:478
FormData_pg_constraint * Form_pg_constraint
static Datum CStringGetDatum(const char *X)
Definition postgres.h:380
#define InvalidOid
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition scankey.c:76
#define BTEqualStrategyNumber
Definition stratnum.h:31

References BTEqualStrategyNumber, CacheInvalidateHeapTuple(), CatalogTupleUpdate(), checkDomainOwner(), CStringGetDatum(), elog, ereport, errcode(), errmsg(), ERROR, fb(), GETSTRUCT(), HeapTupleIsValid, InvalidOid, makeTypeNameFromNameList(), NOTICE, ObjectAddressSet, ObjectIdGetDatum(), performDeletion(), RowExclusiveLock, ScanKeyInit(), SearchSysCacheCopy1, systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), table_open(), TypeNameToString(), and typenameTypeId().

Referenced by ProcessUtilitySlow().

◆ AlterDomainNotNull()

ObjectAddress AlterDomainNotNull ( List names,
bool  notNull 
)
extern

Definition at line 2768 of file typecmds.c.

2769{
2770 TypeName *typename;
2771 Oid domainoid;
2773 HeapTuple tup;
2776
2777 /* Make a TypeName so we can use standard type lookup machinery */
2778 typename = makeTypeNameFromNameList(names);
2779 domainoid = typenameTypeId(NULL, typename);
2780
2781 /* Look up the domain in the type table */
2783
2785 if (!HeapTupleIsValid(tup))
2786 elog(ERROR, "cache lookup failed for type %u", domainoid);
2788
2789 /* Check it's a domain and check user has permission for ALTER DOMAIN */
2791
2792 /* Is the domain already set to the desired constraint? */
2793 if (typTup->typnotnull == notNull)
2794 {
2796 return address;
2797 }
2798
2799 if (notNull)
2800 {
2801 Constraint *constr;
2802
2803 constr = makeNode(Constraint);
2804 constr->contype = CONSTR_NOTNULL;
2805 constr->initially_valid = true;
2806 constr->location = -1;
2807
2809 typTup->typbasetype, typTup->typtypmod,
2810 constr, NameStr(typTup->typname), NULL);
2811
2813 }
2814 else
2815 {
2818
2820 if (conTup == NULL)
2821 elog(ERROR, "could not find not-null constraint on domain \"%s\"", NameStr(typTup->typname));
2822
2825 }
2826
2827 /*
2828 * Okay to update pg_type row. We can scribble on typTup because it's a
2829 * copy.
2830 */
2831 typTup->typnotnull = notNull;
2832
2833 CatalogTupleUpdate(typrel, &tup->t_self, tup);
2834
2836
2838
2839 /* Clean up */
2842
2843 return address;
2844}
#define makeNode(_type_)
Definition nodes.h:161
@ DROP_RESTRICT
HeapTuple findDomainNotNullConstraint(Oid typid)
ParseLoc location
bool initially_valid

References CatalogTupleUpdate(), checkDomainOwner(), CONSTR_NOTNULL, Constraint::contype, domainAddNotNullConstraint(), DROP_RESTRICT, elog, ERROR, fb(), findDomainNotNullConstraint(), GETSTRUCT(), heap_freetuple(), HeapTupleIsValid, Constraint::initially_valid, InvalidObjectAddress, InvokeObjectPostAlterHook, Constraint::location, makeNode, makeTypeNameFromNameList(), NameStr, ObjectAddressSet, ObjectIdGetDatum(), performDeletion(), RowExclusiveLock, SearchSysCacheCopy1, table_close(), table_open(), typenameTypeId(), and validateDomainNotNullConstraint().

Referenced by ProcessUtilitySlow().

◆ AlterDomainValidateConstraint()

ObjectAddress AlterDomainValidateConstraint ( List names,
const char constrName 
)
extern

Definition at line 3057 of file typecmds.c.

3058{
3059 TypeName *typename;
3060 Oid domainoid;
3063 HeapTuple tup;
3066 char *conbin;
3067 SysScanDesc scan;
3068 Datum val;
3069 HeapTuple tuple;
3071 ScanKeyData skey[3];
3072 ObjectAddress address;
3073
3074 /* Make a TypeName so we can use standard type lookup machinery */
3075 typename = makeTypeNameFromNameList(names);
3076 domainoid = typenameTypeId(NULL, typename);
3077
3078 /* Look up the domain in the type table */
3080
3082 if (!HeapTupleIsValid(tup))
3083 elog(ERROR, "cache lookup failed for type %u", domainoid);
3084
3085 /* Check it's a domain and check user has permission for ALTER DOMAIN */
3087
3088 /*
3089 * Find and check the target constraint
3090 */
3092
3093 ScanKeyInit(&skey[0],
3097 ScanKeyInit(&skey[1],
3101 ScanKeyInit(&skey[2],
3105
3107 NULL, 3, skey);
3108
3109 /* There can be at most one matching row */
3110 if (!HeapTupleIsValid(tuple = systable_getnext(scan)))
3111 ereport(ERROR,
3113 errmsg("constraint \"%s\" of domain \"%s\" does not exist",
3114 constrName, TypeNameToString(typename))));
3115
3116 con = (Form_pg_constraint) GETSTRUCT(tuple);
3117 if (con->contype != CONSTRAINT_CHECK)
3118 ereport(ERROR,
3120 errmsg("constraint \"%s\" of domain \"%s\" is not a check constraint",
3121 constrName, TypeNameToString(typename))));
3122
3125
3126 /*
3127 * Locking related relations with ShareUpdateExclusiveLock is ok because
3128 * not-yet-valid constraints are still enforced against concurrent inserts
3129 * or updates.
3130 */
3132
3133 /*
3134 * Now update the catalog, while we have the door open.
3135 */
3136 copyTuple = heap_copytuple(tuple);
3138 copy_con->convalidated = true;
3140
3142
3144
3146
3147 systable_endscan(scan);
3148
3151
3153
3154 return address;
3155}
#define TextDatumGetCString(d)
Definition builtins.h:98
HeapTuple heap_copytuple(HeapTuple tuple)
Definition heaptuple.c:778
long val
Definition informix.c:689
#define AccessShareLock
Definition lockdefs.h:36
#define ShareUpdateExclusiveLock
Definition lockdefs.h:39
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition syscache.c:220
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition syscache.c:625

References AccessShareLock, BTEqualStrategyNumber, CatalogTupleUpdate(), checkDomainOwner(), CStringGetDatum(), elog, ereport, errcode(), errmsg(), ERROR, fb(), GETSTRUCT(), heap_copytuple(), heap_freetuple(), HeapTupleIsValid, InvalidOid, InvokeObjectPostAlterHook, makeTypeNameFromNameList(), ObjectAddressSet, ObjectIdGetDatum(), ReleaseSysCache(), RowExclusiveLock, ScanKeyInit(), SearchSysCache1(), ShareUpdateExclusiveLock, SysCacheGetAttrNotNull(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), table_open(), TextDatumGetCString, TypeNameToString(), typenameTypeId(), val, and validateDomainCheckConstraint().

Referenced by ProcessUtilitySlow().

◆ AlterEnum()

ObjectAddress AlterEnum ( AlterEnumStmt stmt)
extern

Definition at line 1307 of file typecmds.c.

1308{
1310 TypeName *typename;
1311 HeapTuple tup;
1312 ObjectAddress address;
1313
1314 /* Make a TypeName so we can use standard type lookup machinery */
1315 typename = makeTypeNameFromNameList(stmt->typeName);
1316 enum_type_oid = typenameTypeId(NULL, typename);
1317
1319 if (!HeapTupleIsValid(tup))
1320 elog(ERROR, "cache lookup failed for type %u", enum_type_oid);
1321
1322 /* Check it's an enum and check user has permission to ALTER the enum */
1324
1326
1327 if (stmt->oldVal)
1328 {
1329 /* Rename an existing label */
1330 RenameEnumLabel(enum_type_oid, stmt->oldVal, stmt->newVal);
1331 }
1332 else
1333 {
1334 /* Add a new label */
1336 stmt->newValNeighbor, stmt->newValIsAfter,
1337 stmt->skipIfNewValExists);
1338 }
1339
1341
1343
1344 return address;
1345}
#define stmt
void RenameEnumLabel(Oid enumTypeOid, const char *oldVal, const char *newVal)
Definition pg_enum.c:620
void AddEnumLabel(Oid enumTypeOid, const char *newVal, const char *neighbor, bool newValIsAfter, bool skipIfExists)
Definition pg_enum.c:305
static void checkEnumOwner(HeapTuple tup)
Definition typecmds.c:1355

References AddEnumLabel(), checkEnumOwner(), elog, ERROR, fb(), HeapTupleIsValid, InvokeObjectPostAlterHook, makeTypeNameFromNameList(), ObjectAddressSet, ObjectIdGetDatum(), ReleaseSysCache(), RenameEnumLabel(), SearchSysCache1(), stmt, and typenameTypeId().

Referenced by ProcessUtilitySlow().

◆ AlterType()

ObjectAddress AlterType ( AlterTypeStmt stmt)
extern

Definition at line 4347 of file typecmds.c.

4348{
4349 ObjectAddress address;
4351 TypeName *typename;
4352 HeapTuple tup;
4353 Oid typeOid;
4355 bool requireSuper = false;
4357 ListCell *pl;
4358
4360
4361 /* Make a TypeName so we can use standard type lookup machinery */
4362 typename = makeTypeNameFromNameList(stmt->typeName);
4363 tup = typenameType(NULL, typename, NULL);
4364
4365 typeOid = typeTypeId(tup);
4367
4368 /* Process options */
4369 memset(&atparams, 0, sizeof(atparams));
4370 foreach(pl, stmt->options)
4371 {
4372 DefElem *defel = (DefElem *) lfirst(pl);
4373
4374 if (strcmp(defel->defname, "storage") == 0)
4375 {
4376 char *a = defGetString(defel);
4377
4378 if (pg_strcasecmp(a, "plain") == 0)
4379 atparams.storage = TYPSTORAGE_PLAIN;
4380 else if (pg_strcasecmp(a, "external") == 0)
4381 atparams.storage = TYPSTORAGE_EXTERNAL;
4382 else if (pg_strcasecmp(a, "extended") == 0)
4383 atparams.storage = TYPSTORAGE_EXTENDED;
4384 else if (pg_strcasecmp(a, "main") == 0)
4385 atparams.storage = TYPSTORAGE_MAIN;
4386 else
4387 ereport(ERROR,
4389 errmsg("storage \"%s\" not recognized", a)));
4390
4391 /*
4392 * Validate the storage request. If the type isn't varlena, it
4393 * certainly doesn't support non-PLAIN storage.
4394 */
4395 if (atparams.storage != TYPSTORAGE_PLAIN && typForm->typlen != -1)
4396 ereport(ERROR,
4398 errmsg("fixed-size types must have storage PLAIN")));
4399
4400 /*
4401 * Switching from PLAIN to non-PLAIN is allowed, but it requires
4402 * superuser, since we can't validate that the type's C functions
4403 * will support it. Switching from non-PLAIN to PLAIN is
4404 * disallowed outright, because it's not practical to ensure that
4405 * no tables have toasted values of the type. Switching among
4406 * different non-PLAIN settings is OK, since it just constitutes a
4407 * change in the strategy requested for columns created in the
4408 * future.
4409 */
4410 if (atparams.storage != TYPSTORAGE_PLAIN &&
4411 typForm->typstorage == TYPSTORAGE_PLAIN)
4412 requireSuper = true;
4413 else if (atparams.storage == TYPSTORAGE_PLAIN &&
4414 typForm->typstorage != TYPSTORAGE_PLAIN)
4415 ereport(ERROR,
4417 errmsg("cannot change type's storage to PLAIN")));
4418
4419 atparams.updateStorage = true;
4420 }
4421 else if (strcmp(defel->defname, "receive") == 0)
4422 {
4423 if (defel->arg != NULL)
4424 atparams.receiveOid =
4426 typeOid);
4427 else
4428 atparams.receiveOid = InvalidOid; /* NONE, remove function */
4429 atparams.updateReceive = true;
4430 /* Replacing an I/O function requires superuser. */
4431 requireSuper = true;
4432 }
4433 else if (strcmp(defel->defname, "send") == 0)
4434 {
4435 if (defel->arg != NULL)
4436 atparams.sendOid =
4438 typeOid);
4439 else
4440 atparams.sendOid = InvalidOid; /* NONE, remove function */
4441 atparams.updateSend = true;
4442 /* Replacing an I/O function requires superuser. */
4443 requireSuper = true;
4444 }
4445 else if (strcmp(defel->defname, "typmod_in") == 0)
4446 {
4447 if (defel->arg != NULL)
4448 atparams.typmodinOid =
4450 else
4451 atparams.typmodinOid = InvalidOid; /* NONE, remove function */
4452 atparams.updateTypmodin = true;
4453 /* Replacing an I/O function requires superuser. */
4454 requireSuper = true;
4455 }
4456 else if (strcmp(defel->defname, "typmod_out") == 0)
4457 {
4458 if (defel->arg != NULL)
4459 atparams.typmodoutOid =
4461 else
4462 atparams.typmodoutOid = InvalidOid; /* NONE, remove function */
4463 atparams.updateTypmodout = true;
4464 /* Replacing an I/O function requires superuser. */
4465 requireSuper = true;
4466 }
4467 else if (strcmp(defel->defname, "analyze") == 0)
4468 {
4469 if (defel->arg != NULL)
4470 atparams.analyzeOid =
4472 typeOid);
4473 else
4474 atparams.analyzeOid = InvalidOid; /* NONE, remove function */
4475 atparams.updateAnalyze = true;
4476 /* Replacing an analyze function requires superuser. */
4477 requireSuper = true;
4478 }
4479 else if (strcmp(defel->defname, "subscript") == 0)
4480 {
4481 if (defel->arg != NULL)
4482 atparams.subscriptOid =
4484 typeOid);
4485 else
4486 atparams.subscriptOid = InvalidOid; /* NONE, remove function */
4487 atparams.updateSubscript = true;
4488 /* Replacing a subscript function requires superuser. */
4489 requireSuper = true;
4490 }
4491
4492 /*
4493 * The rest of the options that CREATE accepts cannot be changed.
4494 * Check for them so that we can give a meaningful error message.
4495 */
4496 else if (strcmp(defel->defname, "input") == 0 ||
4497 strcmp(defel->defname, "output") == 0 ||
4498 strcmp(defel->defname, "internallength") == 0 ||
4499 strcmp(defel->defname, "passedbyvalue") == 0 ||
4500 strcmp(defel->defname, "alignment") == 0 ||
4501 strcmp(defel->defname, "like") == 0 ||
4502 strcmp(defel->defname, "category") == 0 ||
4503 strcmp(defel->defname, "preferred") == 0 ||
4504 strcmp(defel->defname, "default") == 0 ||
4505 strcmp(defel->defname, "element") == 0 ||
4506 strcmp(defel->defname, "delimiter") == 0 ||
4507 strcmp(defel->defname, "collatable") == 0)
4508 ereport(ERROR,
4510 errmsg("type attribute \"%s\" cannot be changed",
4511 defel->defname)));
4512 else
4513 ereport(ERROR,
4515 errmsg("type attribute \"%s\" not recognized",
4516 defel->defname)));
4517 }
4518
4519 /*
4520 * Permissions check. Require superuser if we decided the command
4521 * requires that, else must own the type.
4522 */
4523 if (requireSuper)
4524 {
4525 if (!superuser())
4526 ereport(ERROR,
4528 errmsg("must be superuser to alter a type")));
4529 }
4530 else
4531 {
4532 if (!object_ownercheck(TypeRelationId, typeOid, GetUserId()))
4534 }
4535
4536 /*
4537 * We disallow all forms of ALTER TYPE SET on types that aren't plain base
4538 * types. It would for example be highly unsafe, not to mention
4539 * pointless, to change the send/receive functions for a composite type.
4540 * Moreover, pg_dump has no support for changing these properties on
4541 * non-base types. We might weaken this someday, but not now.
4542 *
4543 * Note: if you weaken this enough to allow composite types, be sure to
4544 * adjust the GenerateTypeDependencies call in AlterTypeRecurse.
4545 */
4546 if (typForm->typtype != TYPTYPE_BASE)
4547 ereport(ERROR,
4549 errmsg("%s is not a base type",
4550 format_type_be(typeOid))));
4551
4552 /*
4553 * For the same reasons, don't allow direct alteration of array types.
4554 */
4556 ereport(ERROR,
4558 errmsg("%s is not a base type",
4559 format_type_be(typeOid))));
4560
4561 /* OK, recursively update this type and any arrays/domains over it */
4562 AlterTypeRecurse(typeOid, false, tup, catalog, &atparams);
4563
4564 /* Clean up */
4566
4568
4569 ObjectAddressSet(address, TypeRelationId, typeOid);
4570
4571 return address;
4572}
@ ACLCHECK_NOT_OWNER
Definition acl.h:185
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition aclchk.c:4090
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition aclchk.c:2973
char * defGetString(DefElem *def)
Definition define.c:34
List * defGetQualifiedName(DefElem *def)
Definition define.c:238
char * format_type_be(Oid type_oid)
int a
Definition isn.c:73
Oid GetUserId(void)
Definition miscinit.c:469
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition parse_type.c:264
Oid typeTypeId(Type tp)
Definition parse_type.c:590
#define lfirst(lc)
Definition pg_list.h:172
int pg_strcasecmp(const char *s1, const char *s2)
bool superuser(void)
Definition superuser.c:46
static Oid findTypeReceiveFunction(List *procname, Oid typeOid)
Definition typecmds.c:2114
static void AlterTypeRecurse(Oid typeOid, bool isImplicitArray, HeapTuple tup, Relation catalog, AlterTypeRecurseParams *atparams)
Definition typecmds.c:4598
static Oid findTypeAnalyzeFunction(List *procname, Oid typeOid)
Definition typecmds.c:2271
static Oid findTypeSendFunction(List *procname, Oid typeOid)
Definition typecmds.c:2168
static Oid findTypeSubscriptingFunction(List *procname, Oid typeOid)
Definition typecmds.c:2298
static Oid findTypeTypmodoutFunction(List *procname)
Definition typecmds.c:2237
static Oid findTypeTypmodinFunction(List *procname)
Definition typecmds.c:2203

References a, aclcheck_error_type(), ACLCHECK_NOT_OWNER, AlterTypeRecurse(), defGetQualifiedName(), defGetString(), ereport, errcode(), errmsg(), ERROR, fb(), findTypeAnalyzeFunction(), findTypeReceiveFunction(), findTypeSendFunction(), findTypeSubscriptingFunction(), findTypeTypmodinFunction(), findTypeTypmodoutFunction(), format_type_be(), GETSTRUCT(), GetUserId(), InvalidOid, lfirst, makeTypeNameFromNameList(), object_ownercheck(), ObjectAddressSet, pg_strcasecmp(), ReleaseSysCache(), RowExclusiveLock, stmt, superuser(), table_close(), table_open(), typenameType(), and typeTypeId().

Referenced by ProcessUtilitySlow().

◆ AlterTypeNamespace()

ObjectAddress AlterTypeNamespace ( List names,
const char newschema,
ObjectType  objecttype,
Oid oldschema 
)
extern

Definition at line 4090 of file typecmds.c.

4092{
4093 TypeName *typename;
4094 Oid typeOid;
4095 Oid nspOid;
4096 Oid oldNspOid;
4099
4100 /* Make a TypeName so we can use standard type lookup machinery */
4101 typename = makeTypeNameFromNameList(names);
4102 typeOid = typenameTypeId(NULL, typename);
4103
4104 /* Don't allow ALTER DOMAIN on a non-domain type */
4105 if (objecttype == OBJECT_DOMAIN && get_typtype(typeOid) != TYPTYPE_DOMAIN)
4106 ereport(ERROR,
4108 errmsg("%s is not a domain",
4109 format_type_be(typeOid))));
4110
4111 /* get schema OID and check its permissions */
4112 nspOid = LookupCreationNamespace(newschema);
4113
4117
4118 if (oldschema)
4120
4122
4123 return myself;
4124}
ObjectAddresses * new_object_addresses(void)
void free_object_addresses(ObjectAddresses *addrs)
char get_typtype(Oid typid)
Definition lsyscache.c:2779
Oid LookupCreationNamespace(const char *nspname)
Definition namespace.c:3498
@ OBJECT_DOMAIN
Oid AlterTypeNamespace_oid(Oid typeOid, Oid nspOid, bool ignoreDependent, ObjectAddresses *objsMoved)
Definition typecmds.c:4139

References AlterTypeNamespace_oid(), ereport, errcode(), errmsg(), ERROR, fb(), format_type_be(), free_object_addresses(), get_typtype(), LookupCreationNamespace(), makeTypeNameFromNameList(), new_object_addresses(), OBJECT_DOMAIN, ObjectAddressSet, and typenameTypeId().

Referenced by ExecAlterObjectSchemaStmt().

◆ AlterTypeNamespace_oid()

Oid AlterTypeNamespace_oid ( Oid  typeOid,
Oid  nspOid,
bool  ignoreDependent,
ObjectAddresses objsMoved 
)
extern

Definition at line 4139 of file typecmds.c.

4141{
4142 Oid elemOid;
4143
4144 /* check permissions on type */
4145 if (!object_ownercheck(TypeRelationId, typeOid, GetUserId()))
4147
4148 /* don't allow direct alteration of array types */
4149 elemOid = get_element_type(typeOid);
4150 if (OidIsValid(elemOid) && get_array_type(elemOid) == typeOid)
4151 {
4152 if (ignoreDependent)
4153 return InvalidOid;
4154 ereport(ERROR,
4156 errmsg("cannot alter array type %s",
4157 format_type_be(typeOid)),
4158 errhint("You can alter type %s, which will alter the array type as well.",
4160 }
4161
4162 /* and do the work */
4163 return AlterTypeNamespaceInternal(typeOid, nspOid,
4164 false, /* isImplicitArray */
4165 ignoreDependent, /* ignoreDependent */
4166 true, /* errorOnTableType */
4167 objsMoved);
4168}
#define OidIsValid(objectId)
Definition c.h:788
int errhint(const char *fmt,...)
Definition elog.c:1330
Oid get_element_type(Oid typid)
Definition lsyscache.c:2909
Oid get_array_type(Oid typid)
Definition lsyscache.c:2937
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool ignoreDependent, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition typecmds.c:4191

References aclcheck_error_type(), ACLCHECK_NOT_OWNER, AlterTypeNamespaceInternal(), ereport, errcode(), errhint(), errmsg(), ERROR, fb(), format_type_be(), get_array_type(), get_element_type(), GetUserId(), InvalidOid, object_ownercheck(), and OidIsValid.

Referenced by AlterObjectNamespace_oid(), and AlterTypeNamespace().

◆ AlterTypeNamespaceInternal()

Oid AlterTypeNamespaceInternal ( Oid  typeOid,
Oid  nspOid,
bool  isImplicitArray,
bool  ignoreDependent,
bool  errorOnTableType,
ObjectAddresses objsMoved 
)
extern

Definition at line 4191 of file typecmds.c.

4196{
4197 Relation rel;
4198 HeapTuple tup;
4200 Oid oldNspOid;
4201 Oid arrayOid;
4202 bool isCompositeType;
4204
4205 /*
4206 * Make sure we haven't moved this object previously.
4207 */
4209 thisobj.objectId = typeOid;
4210 thisobj.objectSubId = 0;
4211
4213 return InvalidOid;
4214
4216
4218 if (!HeapTupleIsValid(tup))
4219 elog(ERROR, "cache lookup failed for type %u", typeOid);
4221
4222 oldNspOid = typform->typnamespace;
4223 arrayOid = typform->typarray;
4224
4225 /* If the type is already there, we scan skip these next few checks. */
4226 if (oldNspOid != nspOid)
4227 {
4228 /* common checks on switching namespaces */
4230
4231 /* check for duplicate name (more friendly than unique-index failure) */
4233 NameGetDatum(&typform->typname),
4235 ereport(ERROR,
4237 errmsg("type \"%s\" already exists in schema \"%s\"",
4238 NameStr(typform->typname),
4240 }
4241
4242 /* Detect whether type is a composite type (but not a table rowtype) */
4244 (typform->typtype == TYPTYPE_COMPOSITE &&
4246
4247 /* Enforce not-table-type if requested */
4248 if (typform->typtype == TYPTYPE_COMPOSITE && !isCompositeType)
4249 {
4250 if (ignoreDependent)
4251 {
4253 return InvalidOid;
4254 }
4255 if (errorOnTableType)
4256 ereport(ERROR,
4258 errmsg("%s is a table's row type",
4259 format_type_be(typeOid)),
4260 /* translator: %s is an SQL ALTER command */
4261 errhint("Use %s instead.", "ALTER TABLE")));
4262 }
4263
4264 if (oldNspOid != nspOid)
4265 {
4266 /* OK, modify the pg_type row */
4267
4268 /* tup is a copy, so we can scribble directly on it */
4269 typform->typnamespace = nspOid;
4270
4271 CatalogTupleUpdate(rel, &tup->t_self, tup);
4272 }
4273
4274 /*
4275 * Composite types have pg_class entries.
4276 *
4277 * We need to modify the pg_class tuple as well to reflect the change of
4278 * schema.
4279 */
4280 if (isCompositeType)
4281 {
4283
4285
4288 false, objsMoved);
4289
4291
4292 /*
4293 * Check for constraints associated with the composite type (we don't
4294 * currently support this, but probably will someday).
4295 */
4297 nspOid, false, objsMoved);
4298 }
4299 else
4300 {
4301 /* If it's a domain, it might have constraints */
4302 if (typform->typtype == TYPTYPE_DOMAIN)
4304 objsMoved);
4305 }
4306
4307 /*
4308 * Update dependency on schema, if any --- a table rowtype has not got
4309 * one, and neither does an implicit array.
4310 */
4311 if (oldNspOid != nspOid &&
4312 (isCompositeType || typform->typtype != TYPTYPE_COMPOSITE) &&
4316 elog(ERROR, "could not change schema dependency for type \"%s\"",
4317 format_type_be(typeOid));
4318
4320
4322
4324
4326
4327 /* Recursively alter the associated array type, if any */
4328 if (OidIsValid(arrayOid))
4330 true, /* isImplicitArray */
4331 false, /* ignoreDependent */
4332 true, /* errorOnTableType */
4333 objsMoved);
4334
4335 return oldNspOid;
4336}
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
char get_rel_relkind(Oid relid)
Definition lsyscache.c:2153
char * get_namespace_name(Oid nspid)
Definition lsyscache.c:3516
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition namespace.c:3529
static bool isCompositeType(Oid typid)
void AlterConstraintNamespaces(Oid ownerId, Oid oldNspId, Oid newNspId, bool isType, ObjectAddresses *objsMoved)
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition pg_depend.c:457
static Datum NameGetDatum(const NameData *X)
Definition postgres.h:403
#define ERRCODE_DUPLICATE_OBJECT
Definition streamutil.c:30
#define SearchSysCacheExists2(cacheId, key1, key2)
Definition syscache.h:102
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)

References add_exact_object_address(), AlterConstraintNamespaces(), AlterRelationNamespaceInternal(), AlterTypeNamespaceInternal(), CatalogTupleUpdate(), changeDependencyFor(), CheckSetNamespace(), ObjectAddress::classId, elog, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errhint(), errmsg(), ERROR, fb(), format_type_be(), get_namespace_name(), get_rel_relkind(), GETSTRUCT(), heap_freetuple(), HeapTupleIsValid, InvalidOid, InvokeObjectPostAlterHook, isCompositeType(), NameGetDatum(), NameStr, object_address_present(), ObjectIdGetDatum(), OidIsValid, RowExclusiveLock, SearchSysCacheCopy1, SearchSysCacheExists2, table_close(), and table_open().

Referenced by AlterTableNamespaceInternal(), AlterTypeNamespace_oid(), and AlterTypeNamespaceInternal().

◆ AlterTypeOwner()

ObjectAddress AlterTypeOwner ( List names,
Oid  newOwnerId,
ObjectType  objecttype 
)
extern

Definition at line 3857 of file typecmds.c.

3858{
3859 TypeName *typename;
3860 Oid typeOid;
3861 Relation rel;
3862 HeapTuple tup;
3866 ObjectAddress address;
3867
3869
3870 /* Make a TypeName so we can use standard type lookup machinery */
3871 typename = makeTypeNameFromNameList(names);
3872
3873 /* Use LookupTypeName here so that shell types can be processed */
3874 tup = LookupTypeName(NULL, typename, NULL, false);
3875 if (tup == NULL)
3876 ereport(ERROR,
3878 errmsg("type \"%s\" does not exist",
3879 TypeNameToString(typename))));
3880 typeOid = typeTypeId(tup);
3881
3882 /* Copy the syscache entry so we can scribble on it below */
3885 tup = newtup;
3887
3888 /* Don't allow ALTER DOMAIN on a type */
3889 if (objecttype == OBJECT_DOMAIN && typTup->typtype != TYPTYPE_DOMAIN)
3890 ereport(ERROR,
3892 errmsg("%s is not a domain",
3893 format_type_be(typeOid))));
3894
3895 /*
3896 * If it's a composite type, we need to check that it really is a
3897 * free-standing composite type, and not a table's rowtype. We want people
3898 * to use ALTER TABLE not ALTER TYPE for that case.
3899 */
3900 if (typTup->typtype == TYPTYPE_COMPOSITE &&
3902 ereport(ERROR,
3904 errmsg("%s is a table's row type",
3905 format_type_be(typeOid)),
3906 /* translator: %s is an SQL ALTER command */
3907 errhint("Use %s instead.",
3908 "ALTER TABLE")));
3909
3910 /* don't allow direct alteration of array types, either */
3912 ereport(ERROR,
3914 errmsg("cannot alter array type %s",
3915 format_type_be(typeOid)),
3916 errhint("You can alter type %s, which will alter the array type as well.",
3917 format_type_be(typTup->typelem))));
3918
3919 /* don't allow direct alteration of multirange types, either */
3920 if (typTup->typtype == TYPTYPE_MULTIRANGE)
3921 {
3923
3924 /* We don't expect get_multirange_range to fail, but cope if so */
3925 ereport(ERROR,
3927 errmsg("cannot alter multirange type %s",
3928 format_type_be(typeOid)),
3930 errhint("You can alter type %s, which will alter the multirange type as well.",
3931 format_type_be(rangetype)) : 0));
3932 }
3933
3934 /*
3935 * If the new owner is the same as the existing owner, consider the
3936 * command to have succeeded. This is for dump restoration purposes.
3937 */
3938 if (typTup->typowner != newOwnerId)
3939 {
3940 /* Superusers can always do it */
3941 if (!superuser())
3942 {
3943 /* Otherwise, must be owner of the existing object */
3946
3947 /* Must be able to become new owner */
3949
3950 /* New owner must have CREATE privilege on namespace */
3952 newOwnerId,
3953 ACL_CREATE);
3954 if (aclresult != ACLCHECK_OK)
3956 get_namespace_name(typTup->typnamespace));
3957 }
3958
3959 AlterTypeOwner_oid(typeOid, newOwnerId, true);
3960 }
3961
3962 ObjectAddressSet(address, TypeRelationId, typeOid);
3963
3964 /* Clean up */
3966
3967 return address;
3968}
void check_can_set_role(Oid member, Oid role)
Definition acl.c:5341
AclResult
Definition acl.h:182
@ ACLCHECK_OK
Definition acl.h:183
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition aclchk.c:2654
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition aclchk.c:3836
Oid get_multirange_range(Oid multirangeOid)
Definition lsyscache.c:3633
Type LookupTypeName(ParseState *pstate, const TypeName *typeName, int32 *typmod_p, bool missing_ok)
Definition parse_type.c:38
@ OBJECT_SCHEMA
#define ACL_CREATE
Definition parsenodes.h:85
void AlterTypeOwner_oid(Oid typeOid, Oid newOwnerId, bool hasDependEntry)
Definition typecmds.c:3982

References ACL_CREATE, aclcheck_error(), aclcheck_error_type(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, AlterTypeOwner_oid(), check_can_set_role(), ereport, errcode(), errhint(), errmsg(), ERROR, fb(), format_type_be(), get_multirange_range(), get_namespace_name(), get_rel_relkind(), GETSTRUCT(), GetUserId(), heap_copytuple(), LookupTypeName(), makeTypeNameFromNameList(), object_aclcheck(), OBJECT_DOMAIN, object_ownercheck(), OBJECT_SCHEMA, ObjectAddressSet, OidIsValid, ReleaseSysCache(), RowExclusiveLock, superuser(), table_close(), table_open(), TypeNameToString(), and typeTypeId().

Referenced by ExecAlterOwnerStmt().

◆ AlterTypeOwner_oid()

void AlterTypeOwner_oid ( Oid  typeOid,
Oid  newOwnerId,
bool  hasDependEntry 
)
extern

Definition at line 3982 of file typecmds.c.

3983{
3984 Relation rel;
3985 HeapTuple tup;
3987
3989
3991 if (!HeapTupleIsValid(tup))
3992 elog(ERROR, "cache lookup failed for type %u", typeOid);
3994
3995 /*
3996 * If it's a composite type, invoke ATExecChangeOwner so that we fix up
3997 * the pg_class entry properly. That will call back to
3998 * AlterTypeOwnerInternal to take care of the pg_type entry(s).
3999 */
4000 if (typTup->typtype == TYPTYPE_COMPOSITE)
4002 else
4004
4005 /* Update owner dependency reference */
4006 if (hasDependEntry)
4008
4010
4013}
#define AccessExclusiveLock
Definition lockdefs.h:43
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
void ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
void AlterTypeOwnerInternal(Oid typeOid, Oid newOwnerId)
Definition typecmds.c:4022

References AccessExclusiveLock, AlterTypeOwnerInternal(), ATExecChangeOwner(), changeDependencyOnOwner(), elog, ERROR, fb(), GETSTRUCT(), HeapTupleIsValid, InvokeObjectPostAlterHook, ObjectIdGetDatum(), ReleaseSysCache(), RowExclusiveLock, SearchSysCache1(), table_close(), and table_open().

Referenced by AlterTypeOwner(), and shdepReassignOwned_Owner().

◆ AlterTypeOwnerInternal()

void AlterTypeOwnerInternal ( Oid  typeOid,
Oid  newOwnerId 
)
extern

Definition at line 4022 of file typecmds.c.

4023{
4024 Relation rel;
4025 HeapTuple tup;
4030 Acl *newAcl;
4032 bool isNull;
4033
4035
4037 if (!HeapTupleIsValid(tup))
4038 elog(ERROR, "cache lookup failed for type %u", typeOid);
4040
4041 memset(repl_null, false, sizeof(repl_null));
4042 memset(repl_repl, false, sizeof(repl_repl));
4043
4044 repl_repl[Anum_pg_type_typowner - 1] = true;
4046
4049 RelationGetDescr(rel),
4050 &isNull);
4051 /* Null ACLs do not require changes */
4052 if (!isNull)
4053 {
4055 typTup->typowner, newOwnerId);
4056 repl_repl[Anum_pg_type_typacl - 1] = true;
4058 }
4059
4061 repl_repl);
4062
4063 CatalogTupleUpdate(rel, &tup->t_self, tup);
4064
4065 /* If it has an array type, update that too */
4066 if (OidIsValid(typTup->typarray))
4068
4069 /* If it is a range type, update the associated multirange too */
4070 if (typTup->typtype == TYPTYPE_RANGE)
4071 {
4073
4075 ereport(ERROR,
4077 errmsg("could not find multirange type for data type %s",
4078 format_type_be(typeOid))));
4080 }
4081
4082 /* Clean up */
4084}
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition acl.c:1119
#define DatumGetAclP(X)
Definition acl.h:120
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Oid get_range_multirange(Oid rangeOid)
Definition lsyscache.c:3608
static Datum PointerGetDatum(const void *X)
Definition postgres.h:352

References aclnewowner(), AlterTypeOwnerInternal(), CatalogTupleUpdate(), DatumGetAclP, elog, ereport, errcode(), errmsg(), ERROR, fb(), format_type_be(), get_range_multirange(), GETSTRUCT(), heap_getattr(), heap_modify_tuple(), HeapTupleIsValid, ObjectIdGetDatum(), OidIsValid, PointerGetDatum(), RelationGetDescr, RowExclusiveLock, SearchSysCacheCopy1, table_close(), and table_open().

Referenced by AlterTypeOwner_oid(), AlterTypeOwnerInternal(), and ATExecChangeOwner().

◆ AssignTypeArrayOid()

Oid AssignTypeArrayOid ( void  )
extern

Definition at line 2473 of file typecmds.c.

2474{
2476
2477 /* Use binary-upgrade override for pg_type.typarray? */
2478 if (IsBinaryUpgrade)
2479 {
2481 ereport(ERROR,
2483 errmsg("pg_type array OID value not set when in binary upgrade mode")));
2484
2487 }
2488 else
2489 {
2491
2495 }
2496
2497 return type_array_oid;
2498}
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition catalog.c:448
bool IsBinaryUpgrade
Definition globals.c:121
Oid binary_upgrade_next_array_pg_type_oid
Definition typecmds.c:109

References AccessShareLock, binary_upgrade_next_array_pg_type_oid, ereport, errcode(), errmsg(), ERROR, fb(), GetNewOidWithIndex(), InvalidOid, IsBinaryUpgrade, OidIsValid, table_close(), and table_open().

Referenced by DefineDomain(), DefineEnum(), DefineRange(), DefineType(), and heap_create_with_catalog().

◆ AssignTypeMultirangeArrayOid()

Oid AssignTypeMultirangeArrayOid ( void  )
extern

Definition at line 2539 of file typecmds.c.

2540{
2542
2543 /* Use binary-upgrade override for pg_type.oid? */
2544 if (IsBinaryUpgrade)
2545 {
2547 ereport(ERROR,
2549 errmsg("pg_type multirange array OID value not set when in binary upgrade mode")));
2550
2553 }
2554 else
2555 {
2557
2561 }
2562
2564}
Oid binary_upgrade_next_mrng_array_pg_type_oid
Definition typecmds.c:111

References AccessShareLock, binary_upgrade_next_mrng_array_pg_type_oid, ereport, errcode(), errmsg(), ERROR, fb(), GetNewOidWithIndex(), InvalidOid, IsBinaryUpgrade, OidIsValid, table_close(), and table_open().

Referenced by DefineRange().

◆ AssignTypeMultirangeOid()

Oid AssignTypeMultirangeOid ( void  )
extern

Definition at line 2506 of file typecmds.c.

2507{
2509
2510 /* Use binary-upgrade override for pg_type.oid? */
2511 if (IsBinaryUpgrade)
2512 {
2514 ereport(ERROR,
2516 errmsg("pg_type multirange OID value not set when in binary upgrade mode")));
2517
2520 }
2521 else
2522 {
2524
2528 }
2529
2530 return type_multirange_oid;
2531}
Oid binary_upgrade_next_mrng_pg_type_oid
Definition typecmds.c:110

References AccessShareLock, binary_upgrade_next_mrng_pg_type_oid, ereport, errcode(), errmsg(), ERROR, fb(), GetNewOidWithIndex(), InvalidOid, IsBinaryUpgrade, OidIsValid, table_close(), and table_open().

Referenced by DefineRange().

◆ checkDomainOwner()

void checkDomainOwner ( HeapTuple  tup)
extern

Definition at line 3521 of file typecmds.c.

3522{
3524
3525 /* Check that this is actually a domain */
3526 if (typTup->typtype != TYPTYPE_DOMAIN)
3527 ereport(ERROR,
3529 errmsg("%s is not a domain",
3530 format_type_be(typTup->oid))));
3531
3532 /* Permission check: must own type */
3535}

References aclcheck_error_type(), ACLCHECK_NOT_OWNER, ereport, errcode(), errmsg(), ERROR, fb(), format_type_be(), GETSTRUCT(), GetUserId(), and object_ownercheck().

Referenced by AlterDomainAddConstraint(), AlterDomainDefault(), AlterDomainDropConstraint(), AlterDomainNotNull(), AlterDomainValidateConstraint(), and RenameConstraint().

◆ DefineCompositeType()

ObjectAddress DefineCompositeType ( RangeVar typevar,
List coldeflist 
)
extern

Definition at line 2581 of file typecmds.c.

2582{
2583 CreateStmt *createStmt = makeNode(CreateStmt);
2586 ObjectAddress address;
2587
2588 /*
2589 * now set the parameters for keys/inheritance etc. All of these are
2590 * uninteresting for composite types...
2591 */
2592 createStmt->relation = typevar;
2593 createStmt->tableElts = coldeflist;
2594 createStmt->inhRelations = NIL;
2595 createStmt->constraints = NIL;
2596 createStmt->options = NIL;
2597 createStmt->oncommit = ONCOMMIT_NOOP;
2598 createStmt->tablespacename = NULL;
2599 createStmt->if_not_exists = false;
2600
2601 /*
2602 * Check for collision with an existing type name. If there is one and
2603 * it's an autogenerated array, we can rename it out of the way. This
2604 * check is here mainly to get a better error message about a "type"
2605 * instead of below about a "relation".
2606 */
2608 NoLock, NULL);
2610 old_type_oid =
2612 CStringGetDatum(createStmt->relation->relname),
2615 {
2617 ereport(ERROR,
2619 errmsg("type \"%s\" already exists", createStmt->relation->relname)));
2620 }
2621
2622 /*
2623 * Finally create the relation. This also creates the type.
2624 */
2625 DefineRelation(createStmt, RELKIND_COMPOSITE_TYPE, InvalidOid, &address,
2626 NULL);
2627
2628 return address;
2629}
#define NoLock
Definition lockdefs.h:34
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition namespace.c:738
void RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
Definition namespace.c:845
bool moveArrayTypeName(Oid typeOid, const char *typeName, Oid typeNamespace)
Definition pg_type.c:903
@ ONCOMMIT_NOOP
Definition primnodes.h:58
List * tableElts
OnCommitAction oncommit
List * options
bool if_not_exists
List * inhRelations
RangeVar * relation
char * tablespacename
List * constraints
char * relname
Definition primnodes.h:83
#define GetSysCacheOid2(cacheId, oidcol, key1, key2)
Definition syscache.h:111
ObjectAddress DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId, ObjectAddress *typaddress, const char *queryString)
Definition tablecmds.c:769

References CreateStmt::constraints, CStringGetDatum(), DefineRelation(), ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, fb(), GetSysCacheOid2, CreateStmt::if_not_exists, CreateStmt::inhRelations, InvalidOid, makeNode, moveArrayTypeName(), NIL, NoLock, ObjectIdGetDatum(), OidIsValid, CreateStmt::oncommit, ONCOMMIT_NOOP, CreateStmt::options, RangeVarAdjustRelationPersistence(), RangeVarGetAndCheckCreationNamespace(), CreateStmt::relation, RangeVar::relname, CreateStmt::tableElts, and CreateStmt::tablespacename.

Referenced by ProcessUtilitySlow().

◆ DefineDomain()

ObjectAddress DefineDomain ( ParseState pstate,
CreateDomainStmt stmt 
)
extern

Definition at line 699 of file typecmds.c.

700{
701 char *domainName;
702 char *domainArrayName;
711 bool byValue;
712 char category;
713 char delimiter;
714 char alignment;
715 char storage;
716 char typtype;
717 Datum datum;
718 bool isnull;
719 char *defaultValue = NULL;
720 char *defaultValueBin = NULL;
721 bool saw_default = false;
722 bool typNotNull = false;
723 bool nullDefined = false;
724 int32 typNDims = list_length(stmt->typeName->arrayBounds);
726 List *schema = stmt->constraints;
732 Form_pg_type baseType;
735 ObjectAddress address;
736
737 /* Convert list of names to a name and namespace */
739 &domainName);
740
741 /* Check we have creation rights in target namespace */
743 ACL_CREATE);
744 if (aclresult != ACLCHECK_OK)
747
748 /*
749 * Check for collision with an existing type name. If there is one and
750 * it's an autogenerated array, we can rename it out of the way.
751 */
756 {
760 errmsg("type \"%s\" already exists", domainName)));
761 }
762
763 /*
764 * Look up the base type.
765 */
766 typeTup = typenameType(pstate, stmt->typeName, &basetypeMod);
767 baseType = (Form_pg_type) GETSTRUCT(typeTup);
768 basetypeoid = baseType->oid;
769
770 /*
771 * Base type must be a plain base type, a composite type, another domain,
772 * an enum or a range type. Domains over pseudotypes would create a
773 * security hole. (It would be shorter to code this to just check for
774 * pseudotypes; but it seems safer to call out the specific typtypes that
775 * are supported, rather than assume that all future typtypes would be
776 * automatically supported.)
777 */
778 typtype = baseType->typtype;
779 if (typtype != TYPTYPE_BASE &&
780 typtype != TYPTYPE_COMPOSITE &&
781 typtype != TYPTYPE_DOMAIN &&
782 typtype != TYPTYPE_ENUM &&
783 typtype != TYPTYPE_RANGE &&
784 typtype != TYPTYPE_MULTIRANGE)
787 errmsg("\"%s\" is not a valid base type for a domain",
788 TypeNameToString(stmt->typeName)),
789 parser_errposition(pstate, stmt->typeName->location)));
790
792 if (aclresult != ACLCHECK_OK)
794
795 /*
796 * Collect the properties of the new domain. Some are inherited from the
797 * base type, some are not. If you change any of this inheritance
798 * behavior, be sure to update AlterTypeRecurse() to match!
799 */
800
801 /*
802 * Identify the collation if any
803 */
804 baseColl = baseType->typcollation;
805 if (stmt->collClause)
806 domaincoll = get_collation_oid(stmt->collClause->collname, false);
807 else
809
810 /* Complain if COLLATE is applied to an uncollatable type */
814 errmsg("collations are not supported by type %s",
816 parser_errposition(pstate, stmt->typeName->location)));
817
818 /* passed by value */
819 byValue = baseType->typbyval;
820
821 /* Required Alignment */
822 alignment = baseType->typalign;
823
824 /* TOAST Strategy */
825 storage = baseType->typstorage;
826
827 /* Storage Length */
828 internalLength = baseType->typlen;
829
830 /* Type Category */
831 category = baseType->typcategory;
832
833 /* Array element Delimiter */
834 delimiter = baseType->typdelim;
835
836 /* I/O Functions */
838 outputProcedure = baseType->typoutput;
840 sendProcedure = baseType->typsend;
841
842 /* Domains never accept typmods, so no typmodin/typmodout needed */
843
844 /* Analysis function */
845 analyzeProcedure = baseType->typanalyze;
846
847 /*
848 * Domains don't need a subscript function, since they are not
849 * subscriptable on their own. If the base type is subscriptable, the
850 * parser will reduce the type to the base type before subscripting.
851 */
852
853 /* Inherited default value */
855 Anum_pg_type_typdefault, &isnull);
856 if (!isnull)
858
859 /* Inherited default binary value */
862 if (!isnull)
864
865 /*
866 * Run through constraints manually to avoid the additional processing
867 * conducted by DefineRelation() and friends.
868 */
869 foreach(listptr, schema)
870 {
871 Constraint *constr = lfirst(listptr);
872
873 if (!IsA(constr, Constraint))
874 elog(ERROR, "unrecognized node type: %d",
875 (int) nodeTag(constr));
876 switch (constr->contype)
877 {
878 case CONSTR_DEFAULT:
879
880 /*
881 * The inherited default value may be overridden by the user
882 * with the DEFAULT <expr> clause ... but only once.
883 */
884 if (saw_default)
887 errmsg("multiple default expressions"),
888 parser_errposition(pstate, constr->location));
889 saw_default = true;
890
891 if (constr->raw_expr)
892 {
894
895 /*
896 * Cook the constr->raw_expr into an expression. Note:
897 * name is strictly for error message
898 */
899 defaultExpr = cookDefault(pstate, constr->raw_expr,
903 0);
904
905 /*
906 * If the expression is just a NULL constant, we treat it
907 * like not having a default.
908 *
909 * Note that if the basetype is another domain, we'll see
910 * a CoerceToDomain expr here and not discard the default.
911 * This is critical because the domain default needs to be
912 * retained to override any default that the base domain
913 * might have.
914 */
915 if (defaultExpr == NULL ||
916 (IsA(defaultExpr, Const) &&
918 {
921 }
922 else
923 {
924 /*
925 * Expression must be stored as a nodeToString result,
926 * but we also require a valid textual representation
927 * (mainly to make life easier for pg_dump).
928 */
931 NIL, false, false);
933 }
934 }
935 else
936 {
937 /* No default (can this still happen?) */
940 }
941 break;
942
943 case CONSTR_NOTNULL:
944 if (nullDefined)
945 {
946 if (!typNotNull)
949 errmsg("conflicting NULL/NOT NULL constraints"),
950 parser_errposition(pstate, constr->location));
951
954 errmsg("redundant NOT NULL constraint definition"),
955 parser_errposition(pstate, constr->location));
956 }
957 if (constr->is_no_inherit)
960 errmsg("not-null constraints for domains cannot be marked NO INHERIT"),
961 parser_errposition(pstate, constr->location));
962 typNotNull = true;
963 nullDefined = true;
964 break;
965
966 case CONSTR_NULL:
967 if (nullDefined && typNotNull)
970 errmsg("conflicting NULL/NOT NULL constraints"),
971 parser_errposition(pstate, constr->location));
972 typNotNull = false;
973 nullDefined = true;
974 break;
975
976 case CONSTR_CHECK:
977
978 /*
979 * Check constraints are handled after domain creation, as
980 * they require the Oid of the domain; at this point we can
981 * only check that they're not marked NO INHERIT, because that
982 * would be bogus.
983 */
984 if (constr->is_no_inherit)
987 errmsg("check constraints for domains cannot be marked NO INHERIT"),
988 parser_errposition(pstate, constr->location));
989
990 break;
991
992 /*
993 * All else are error cases
994 */
995 case CONSTR_UNIQUE:
998 errmsg("unique constraints not possible for domains"),
999 parser_errposition(pstate, constr->location));
1000 break;
1001
1002 case CONSTR_PRIMARY:
1003 ereport(ERROR,
1005 errmsg("primary key constraints not possible for domains"),
1006 parser_errposition(pstate, constr->location)));
1007 break;
1008
1009 case CONSTR_EXCLUSION:
1010 ereport(ERROR,
1012 errmsg("exclusion constraints not possible for domains"),
1013 parser_errposition(pstate, constr->location)));
1014 break;
1015
1016 case CONSTR_FOREIGN:
1017 ereport(ERROR,
1019 errmsg("foreign key constraints not possible for domains"),
1020 parser_errposition(pstate, constr->location)));
1021 break;
1022
1027 ereport(ERROR,
1029 errmsg("specifying constraint deferrability not supported for domains"),
1030 parser_errposition(pstate, constr->location)));
1031 break;
1032
1033 case CONSTR_GENERATED:
1034 case CONSTR_IDENTITY:
1035 ereport(ERROR,
1037 errmsg("specifying GENERATED not supported for domains"),
1038 parser_errposition(pstate, constr->location)));
1039 break;
1040
1043 ereport(ERROR,
1045 errmsg("specifying constraint enforceability not supported for domains"),
1046 parser_errposition(pstate, constr->location)));
1047 break;
1048
1049 /* no default, to let compiler warn about missing case */
1050 }
1051 }
1052
1053 /* Allocate OID for array type */
1055
1056 /*
1057 * Have TypeCreate do all the real work.
1058 */
1059 address =
1060 TypeCreate(InvalidOid, /* no predetermined type OID */
1061 domainName, /* type name */
1062 domainNamespace, /* namespace */
1063 InvalidOid, /* relation oid (n/a here) */
1064 0, /* relation kind (ditto) */
1065 GetUserId(), /* owner's ID */
1066 internalLength, /* internal size */
1067 TYPTYPE_DOMAIN, /* type-type (domain type) */
1068 category, /* type-category */
1069 false, /* domain types are never preferred */
1070 delimiter, /* array element delimiter */
1071 inputProcedure, /* input procedure */
1072 outputProcedure, /* output procedure */
1073 receiveProcedure, /* receive procedure */
1074 sendProcedure, /* send procedure */
1075 InvalidOid, /* typmodin procedure - none */
1076 InvalidOid, /* typmodout procedure - none */
1077 analyzeProcedure, /* analyze procedure */
1078 InvalidOid, /* subscript procedure - none */
1079 InvalidOid, /* no array element type */
1080 false, /* this isn't an array */
1081 domainArrayOid, /* array type we are about to create */
1082 basetypeoid, /* base type ID */
1083 defaultValue, /* default type value (text) */
1084 defaultValueBin, /* default type value (binary) */
1085 byValue, /* passed by value */
1086 alignment, /* required alignment */
1087 storage, /* TOAST strategy */
1088 basetypeMod, /* typeMod value */
1089 typNDims, /* Array dimensions for base type */
1090 typNotNull, /* Type NOT NULL */
1091 domaincoll); /* type's collation */
1092
1093 /*
1094 * Create the array type that goes with it.
1095 */
1097
1098 /* alignment must be TYPALIGN_INT or TYPALIGN_DOUBLE for arrays */
1100
1101 TypeCreate(domainArrayOid, /* force assignment of this type OID */
1102 domainArrayName, /* type name */
1103 domainNamespace, /* namespace */
1104 InvalidOid, /* relation oid (n/a here) */
1105 0, /* relation kind (ditto) */
1106 GetUserId(), /* owner's ID */
1107 -1, /* internal size (always varlena) */
1108 TYPTYPE_BASE, /* type-type (base type) */
1109 TYPCATEGORY_ARRAY, /* type-category (array) */
1110 false, /* array types are never preferred */
1111 delimiter, /* array element delimiter */
1112 F_ARRAY_IN, /* input procedure */
1113 F_ARRAY_OUT, /* output procedure */
1114 F_ARRAY_RECV, /* receive procedure */
1115 F_ARRAY_SEND, /* send procedure */
1116 InvalidOid, /* typmodin procedure - none */
1117 InvalidOid, /* typmodout procedure - none */
1118 F_ARRAY_TYPANALYZE, /* analyze procedure */
1119 F_ARRAY_SUBSCRIPT_HANDLER, /* array subscript procedure */
1120 address.objectId, /* element type ID */
1121 true, /* yes this is an array type */
1122 InvalidOid, /* no further array type */
1123 InvalidOid, /* base type ID */
1124 NULL, /* never a default type value */
1125 NULL, /* binary default isn't sent either */
1126 false, /* never passed by value */
1127 alignment, /* see above */
1128 TYPSTORAGE_EXTENDED, /* ARRAY is always toastable */
1129 -1, /* typMod (Domains only) */
1130 0, /* Array dimensions of typbasetype */
1131 false, /* Type NOT NULL */
1132 domaincoll); /* type's collation */
1133
1135
1136 /*
1137 * Process constraints which refer to the domain ID returned by TypeCreate
1138 */
1139 foreach(listptr, schema)
1140 {
1141 Constraint *constr = lfirst(listptr);
1142
1143 /* it must be a Constraint, per check above */
1144
1145 switch (constr->contype)
1146 {
1147 case CONSTR_CHECK:
1150 constr, domainName, NULL);
1151 break;
1152
1153 case CONSTR_NOTNULL:
1156 constr, domainName, NULL);
1157 break;
1158
1159 /* Other constraint types were fully processed above */
1160
1161 default:
1162 break;
1163 }
1164
1165 /* CCI so we can detect duplicate constraint names */
1167 }
1168
1169 /*
1170 * Now we can clean up.
1171 */
1173
1174 return address;
1175}
int16_t int16
Definition c.h:541
int32_t int32
Definition c.h:542
#define storage
void pfree(void *pointer)
Definition mcxt.c:1616
Oid QualifiedNameGetCreationNamespace(const List *names, char **objname_p)
Definition namespace.c:3557
Oid get_collation_oid(List *collname, bool missing_ok)
Definition namespace.c:4041
int parser_errposition(ParseState *pstate, int location)
Definition parse_node.c:106
#define ACL_USAGE
Definition parsenodes.h:84
@ CONSTR_ATTR_ENFORCED
@ CONSTR_FOREIGN
@ CONSTR_ATTR_DEFERRED
@ CONSTR_IDENTITY
@ CONSTR_UNIQUE
@ CONSTR_ATTR_NOT_DEFERRABLE
@ CONSTR_DEFAULT
@ CONSTR_ATTR_IMMEDIATE
@ CONSTR_NULL
@ CONSTR_GENERATED
@ CONSTR_EXCLUSION
@ CONSTR_ATTR_DEFERRABLE
@ CONSTR_ATTR_NOT_ENFORCED
@ CONSTR_PRIMARY
static int list_length(const List *l)
Definition pg_list.h:152
ObjectAddress TypeCreate(Oid newTypeOid, const char *typeName, Oid typeNamespace, Oid relationOid, char relationKind, Oid ownerId, int16 internalSize, char typeType, char typeCategory, bool typePreferred, char typDelim, Oid inputProcedure, Oid outputProcedure, Oid receiveProcedure, Oid sendProcedure, Oid typmodinProcedure, Oid typmodoutProcedure, Oid analyzeProcedure, Oid subscriptProcedure, Oid elementType, bool isImplicitArray, Oid arrayType, Oid baseType, const char *defaultTypeValue, char *defaultTypeBin, bool passedByValue, char alignment, char storage, int32 typeMod, int32 typNDims, bool typeNotNull, Oid typeCollation)
Definition pg_type.c:195
char * makeArrayTypeName(const char *typeName, Oid typeNamespace)
Definition pg_type.c:838
bool is_no_inherit
Node * raw_expr
Definition pg_list.h:54
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:595
Oid AssignTypeArrayOid(void)
Definition typecmds.c:2473
void CommandCounterIncrement(void)
Definition xact.c:1101

References ACL_CREATE, ACL_USAGE, aclcheck_error(), aclcheck_error_type(), ACLCHECK_OK, AssignTypeArrayOid(), CommandCounterIncrement(), CONSTR_ATTR_DEFERRABLE, CONSTR_ATTR_DEFERRED, CONSTR_ATTR_ENFORCED, CONSTR_ATTR_IMMEDIATE, CONSTR_ATTR_NOT_DEFERRABLE, CONSTR_ATTR_NOT_ENFORCED, CONSTR_CHECK, CONSTR_DEFAULT, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_GENERATED, CONSTR_IDENTITY, CONSTR_NOTNULL, CONSTR_NULL, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, cookDefault(), CStringGetDatum(), deparse_expression(), domainAddCheckConstraint(), domainAddNotNullConstraint(), elog, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, fb(), format_type_be(), get_collation_oid(), get_namespace_name(), GETSTRUCT(), GetSysCacheOid2, GetUserId(), InvalidOid, Constraint::is_no_inherit, IsA, lfirst, list_length(), Constraint::location, makeArrayTypeName(), moveArrayTypeName(), NIL, nodeTag, nodeToString(), object_aclcheck(), OBJECT_SCHEMA, ObjectAddress::objectId, ObjectIdGetDatum(), OidIsValid, parser_errposition(), pfree(), QualifiedNameGetCreationNamespace(), Constraint::raw_expr, ReleaseSysCache(), stmt, storage, SysCacheGetAttr(), TextDatumGetCString, TypeCreate(), TypeNameToString(), and typenameType().

Referenced by ProcessUtilitySlow().

◆ DefineEnum()

ObjectAddress DefineEnum ( CreateEnumStmt stmt)
extern

Definition at line 1183 of file typecmds.c.

1184{
1185 char *enumName;
1186 char *enumArrayName;
1192
1193 /* Convert list of names to a name and namespace */
1195 &enumName);
1196
1197 /* Check we have creation rights in target namespace */
1199 if (aclresult != ACLCHECK_OK)
1202
1203 /*
1204 * Check for collision with an existing type name. If there is one and
1205 * it's an autogenerated array, we can rename it out of the way.
1206 */
1211 {
1213 ereport(ERROR,
1215 errmsg("type \"%s\" already exists", enumName)));
1216 }
1217
1218 /* Allocate OID for array type */
1220
1221 /* Create the pg_type entry */
1222 enumTypeAddr =
1223 TypeCreate(InvalidOid, /* no predetermined type OID */
1224 enumName, /* type name */
1225 enumNamespace, /* namespace */
1226 InvalidOid, /* relation oid (n/a here) */
1227 0, /* relation kind (ditto) */
1228 GetUserId(), /* owner's ID */
1229 sizeof(Oid), /* internal size */
1230 TYPTYPE_ENUM, /* type-type (enum type) */
1231 TYPCATEGORY_ENUM, /* type-category (enum type) */
1232 false, /* enum types are never preferred */
1233 DEFAULT_TYPDELIM, /* array element delimiter */
1234 F_ENUM_IN, /* input procedure */
1235 F_ENUM_OUT, /* output procedure */
1236 F_ENUM_RECV, /* receive procedure */
1237 F_ENUM_SEND, /* send procedure */
1238 InvalidOid, /* typmodin procedure - none */
1239 InvalidOid, /* typmodout procedure - none */
1240 InvalidOid, /* analyze procedure - default */
1241 InvalidOid, /* subscript procedure - none */
1242 InvalidOid, /* element type ID */
1243 false, /* this is not an array type */
1244 enumArrayOid, /* array type we are about to create */
1245 InvalidOid, /* base type ID (only for domains) */
1246 NULL, /* never a default type value */
1247 NULL, /* binary default isn't sent either */
1248 true, /* always passed by value */
1249 TYPALIGN_INT, /* int alignment */
1250 TYPSTORAGE_PLAIN, /* TOAST strategy always plain */
1251 -1, /* typMod (Domains only) */
1252 0, /* Array dimensions of typbasetype */
1253 false, /* Type NOT NULL */
1254 InvalidOid); /* type's collation */
1255
1256 /* Enter the enum's values into pg_enum */
1257 EnumValuesCreate(enumTypeAddr.objectId, stmt->vals);
1258
1259 /*
1260 * Create the array type that goes with it.
1261 */
1263
1264 TypeCreate(enumArrayOid, /* force assignment of this type OID */
1265 enumArrayName, /* type name */
1266 enumNamespace, /* namespace */
1267 InvalidOid, /* relation oid (n/a here) */
1268 0, /* relation kind (ditto) */
1269 GetUserId(), /* owner's ID */
1270 -1, /* internal size (always varlena) */
1271 TYPTYPE_BASE, /* type-type (base type) */
1272 TYPCATEGORY_ARRAY, /* type-category (array) */
1273 false, /* array types are never preferred */
1274 DEFAULT_TYPDELIM, /* array element delimiter */
1275 F_ARRAY_IN, /* input procedure */
1276 F_ARRAY_OUT, /* output procedure */
1277 F_ARRAY_RECV, /* receive procedure */
1278 F_ARRAY_SEND, /* send procedure */
1279 InvalidOid, /* typmodin procedure - none */
1280 InvalidOid, /* typmodout procedure - none */
1281 F_ARRAY_TYPANALYZE, /* analyze procedure */
1282 F_ARRAY_SUBSCRIPT_HANDLER, /* array subscript procedure */
1283 enumTypeAddr.objectId, /* element type ID */
1284 true, /* yes this is an array type */
1285 InvalidOid, /* no further array type */
1286 InvalidOid, /* base type ID */
1287 NULL, /* never a default type value */
1288 NULL, /* binary default isn't sent either */
1289 false, /* never passed by value */
1290 TYPALIGN_INT, /* enums have int align, so do their arrays */
1291 TYPSTORAGE_EXTENDED, /* ARRAY is always toastable */
1292 -1, /* typMod (Domains only) */
1293 0, /* Array dimensions of typbasetype */
1294 false, /* Type NOT NULL */
1295 InvalidOid); /* type's collation */
1296
1298
1299 return enumTypeAddr;
1300}
void EnumValuesCreate(Oid enumTypeOid, List *vals)
Definition pg_enum.c:84
#define DEFAULT_TYPDELIM
Definition typecmds.h:22

References ACL_CREATE, aclcheck_error(), ACLCHECK_OK, AssignTypeArrayOid(), CStringGetDatum(), DEFAULT_TYPDELIM, EnumValuesCreate(), ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, fb(), get_namespace_name(), GetSysCacheOid2, GetUserId(), InvalidOid, makeArrayTypeName(), moveArrayTypeName(), object_aclcheck(), OBJECT_SCHEMA, ObjectIdGetDatum(), OidIsValid, pfree(), QualifiedNameGetCreationNamespace(), stmt, and TypeCreate().

Referenced by ProcessUtilitySlow().

◆ DefineRange()

ObjectAddress DefineRange ( ParseState pstate,
CreateRangeStmt stmt 
)
extern

Definition at line 1382 of file typecmds.c.

1383{
1384 char *typeName;
1386 Oid typoid;
1387 char *rangeArrayName;
1388 char *multirangeTypeName = NULL;
1389 char *multirangeArrayName;
1404 bool subtypbyval;
1405 char subtypalign;
1406 char alignment;
1408 ListCell *lc;
1409 ObjectAddress address;
1417
1418 /* Convert list of names to a name and namespace */
1420 &typeName);
1421
1422 /* Check we have creation rights in target namespace */
1424 if (aclresult != ACLCHECK_OK)
1427
1428 /*
1429 * Look to see if type already exists.
1430 */
1432 CStringGetDatum(typeName),
1434
1435 /*
1436 * If it's not a shell, see if it's an autogenerated array type, and if so
1437 * rename it out of the way.
1438 */
1439 if (OidIsValid(typoid) && get_typisdefined(typoid))
1440 {
1441 if (moveArrayTypeName(typoid, typeName, typeNamespace))
1442 typoid = InvalidOid;
1443 else
1444 ereport(ERROR,
1446 errmsg("type \"%s\" already exists", typeName)));
1447 }
1448
1449 /*
1450 * Unlike DefineType(), we don't insist on a shell type existing first, as
1451 * it's only needed if the user wants to specify a canonical function.
1452 */
1453
1454 /* Extract the parameters from the parameter list */
1455 foreach(lc, stmt->params)
1456 {
1457 DefElem *defel = (DefElem *) lfirst(lc);
1458
1459 if (strcmp(defel->defname, "subtype") == 0)
1460 {
1463 /* we can look up the subtype name immediately */
1465 }
1466 else if (strcmp(defel->defname, "subtype_opclass") == 0)
1467 {
1468 if (rangeSubOpclassName != NIL)
1471 }
1472 else if (strcmp(defel->defname, "collation") == 0)
1473 {
1474 if (rangeCollationName != NIL)
1477 }
1478 else if (strcmp(defel->defname, "canonical") == 0)
1479 {
1480 if (rangeCanonicalName != NIL)
1483 }
1484 else if (strcmp(defel->defname, "subtype_diff") == 0)
1485 {
1489 }
1490 else if (strcmp(defel->defname, "multirange_type_name") == 0)
1491 {
1492 if (multirangeTypeName != NULL)
1494 /* we can look up the subtype name immediately */
1497 }
1498 else
1499 ereport(ERROR,
1501 errmsg("type attribute \"%s\" not recognized",
1502 defel->defname)));
1503 }
1504
1505 /* Must have a subtype */
1507 ereport(ERROR,
1509 errmsg("type attribute \"subtype\" is required")));
1510 /* disallow ranges of pseudotypes */
1512 ereport(ERROR,
1514 errmsg("range subtype cannot be %s",
1516
1517 /* Identify subopclass */
1519
1520 /* Identify collation to use, if any */
1522 {
1523 if (rangeCollationName != NIL)
1525 else
1527 }
1528 else
1529 {
1530 if (rangeCollationName != NIL)
1531 ereport(ERROR,
1533 errmsg("range collation specified but subtype does not support collation")));
1535 }
1536
1537 /* Identify support functions, if provided */
1538 if (rangeCanonicalName != NIL)
1539 {
1540 if (!OidIsValid(typoid))
1541 ereport(ERROR,
1543 errmsg("cannot specify a canonical function without a pre-created shell type"),
1544 errhint("Create the type as a shell type, then create its canonicalization function, then do a full CREATE TYPE.")));
1546 typoid);
1547 }
1548 else
1550
1553 rangeSubtype);
1554 else
1556
1559
1560 /* alignment must be TYPALIGN_INT or TYPALIGN_DOUBLE for ranges */
1562
1563 /* Allocate OID for array type, its multirange, and its multirange array */
1567
1568 /* Create the pg_type entry */
1569 address =
1570 TypeCreate(InvalidOid, /* no predetermined type OID */
1571 typeName, /* type name */
1572 typeNamespace, /* namespace */
1573 InvalidOid, /* relation oid (n/a here) */
1574 0, /* relation kind (ditto) */
1575 GetUserId(), /* owner's ID */
1576 -1, /* internal size (always varlena) */
1577 TYPTYPE_RANGE, /* type-type (range type) */
1578 TYPCATEGORY_RANGE, /* type-category (range type) */
1579 false, /* range types are never preferred */
1580 DEFAULT_TYPDELIM, /* array element delimiter */
1581 F_RANGE_IN, /* input procedure */
1582 F_RANGE_OUT, /* output procedure */
1583 F_RANGE_RECV, /* receive procedure */
1584 F_RANGE_SEND, /* send procedure */
1585 InvalidOid, /* typmodin procedure - none */
1586 InvalidOid, /* typmodout procedure - none */
1587 F_RANGE_TYPANALYZE, /* analyze procedure */
1588 InvalidOid, /* subscript procedure - none */
1589 InvalidOid, /* element type ID - none */
1590 false, /* this is not an array type */
1591 rangeArrayOid, /* array type we are about to create */
1592 InvalidOid, /* base type ID (only for domains) */
1593 NULL, /* never a default type value */
1594 NULL, /* no binary form available either */
1595 false, /* never passed by value */
1596 alignment, /* alignment */
1597 TYPSTORAGE_EXTENDED, /* TOAST strategy (always extended) */
1598 -1, /* typMod (Domains only) */
1599 0, /* Array dimensions of typbasetype */
1600 false, /* Type NOT NULL */
1601 InvalidOid); /* type's collation (ranges never have one) */
1602 Assert(typoid == InvalidOid || typoid == address.objectId);
1603 typoid = address.objectId;
1604
1605 /* Create the multirange that goes with it */
1607 {
1609
1610 /*
1611 * Look to see if multirange type already exists.
1612 */
1616
1617 /*
1618 * If it's not a shell, see if it's an autogenerated array type, and
1619 * if so rename it out of the way.
1620 */
1622 {
1624 ereport(ERROR,
1626 errmsg("type \"%s\" already exists", multirangeTypeName)));
1627 }
1628 }
1629 else
1630 {
1631 /* Generate multirange name automatically */
1634 }
1635
1637 TypeCreate(multirangeOid, /* force assignment of this type OID */
1638 multirangeTypeName, /* type name */
1639 multirangeNamespace, /* namespace */
1640 InvalidOid, /* relation oid (n/a here) */
1641 0, /* relation kind (ditto) */
1642 GetUserId(), /* owner's ID */
1643 -1, /* internal size (always varlena) */
1644 TYPTYPE_MULTIRANGE, /* type-type (multirange type) */
1645 TYPCATEGORY_RANGE, /* type-category (range type) */
1646 false, /* multirange types are never preferred */
1647 DEFAULT_TYPDELIM, /* array element delimiter */
1648 F_MULTIRANGE_IN, /* input procedure */
1649 F_MULTIRANGE_OUT, /* output procedure */
1650 F_MULTIRANGE_RECV, /* receive procedure */
1651 F_MULTIRANGE_SEND, /* send procedure */
1652 InvalidOid, /* typmodin procedure - none */
1653 InvalidOid, /* typmodout procedure - none */
1654 F_MULTIRANGE_TYPANALYZE, /* analyze procedure */
1655 InvalidOid, /* subscript procedure - none */
1656 InvalidOid, /* element type ID - none */
1657 false, /* this is not an array type */
1658 multirangeArrayOid, /* array type we are about to create */
1659 InvalidOid, /* base type ID (only for domains) */
1660 NULL, /* never a default type value */
1661 NULL, /* no binary form available either */
1662 false, /* never passed by value */
1663 alignment, /* alignment */
1664 'x', /* TOAST strategy (always extended) */
1665 -1, /* typMod (Domains only) */
1666 0, /* Array dimensions of typbasetype */
1667 false, /* Type NOT NULL */
1668 InvalidOid); /* type's collation (ranges never have one) */
1669 Assert(multirangeOid == mltrngaddress.objectId);
1670
1671 /*
1672 * Create the array type that goes with it.
1673 */
1675
1676 TypeCreate(rangeArrayOid, /* force assignment of this type OID */
1677 rangeArrayName, /* type name */
1678 typeNamespace, /* namespace */
1679 InvalidOid, /* relation oid (n/a here) */
1680 0, /* relation kind (ditto) */
1681 GetUserId(), /* owner's ID */
1682 -1, /* internal size (always varlena) */
1683 TYPTYPE_BASE, /* type-type (base type) */
1684 TYPCATEGORY_ARRAY, /* type-category (array) */
1685 false, /* array types are never preferred */
1686 DEFAULT_TYPDELIM, /* array element delimiter */
1687 F_ARRAY_IN, /* input procedure */
1688 F_ARRAY_OUT, /* output procedure */
1689 F_ARRAY_RECV, /* receive procedure */
1690 F_ARRAY_SEND, /* send procedure */
1691 InvalidOid, /* typmodin procedure - none */
1692 InvalidOid, /* typmodout procedure - none */
1693 F_ARRAY_TYPANALYZE, /* analyze procedure */
1694 F_ARRAY_SUBSCRIPT_HANDLER, /* array subscript procedure */
1695 typoid, /* element type ID */
1696 true, /* yes this is an array type */
1697 InvalidOid, /* no further array type */
1698 InvalidOid, /* base type ID */
1699 NULL, /* never a default type value */
1700 NULL, /* binary default isn't sent either */
1701 false, /* never passed by value */
1702 alignment, /* alignment - same as range's */
1703 TYPSTORAGE_EXTENDED, /* ARRAY is always toastable */
1704 -1, /* typMod (Domains only) */
1705 0, /* Array dimensions of typbasetype */
1706 false, /* Type NOT NULL */
1707 InvalidOid); /* typcollation */
1708
1710
1711 /* Create the multirange's array type */
1712
1714
1715 TypeCreate(multirangeArrayOid, /* force assignment of this type OID */
1716 multirangeArrayName, /* type name */
1717 multirangeNamespace, /* namespace */
1718 InvalidOid, /* relation oid (n/a here) */
1719 0, /* relation kind (ditto) */
1720 GetUserId(), /* owner's ID */
1721 -1, /* internal size (always varlena) */
1722 TYPTYPE_BASE, /* type-type (base type) */
1723 TYPCATEGORY_ARRAY, /* type-category (array) */
1724 false, /* array types are never preferred */
1725 DEFAULT_TYPDELIM, /* array element delimiter */
1726 F_ARRAY_IN, /* input procedure */
1727 F_ARRAY_OUT, /* output procedure */
1728 F_ARRAY_RECV, /* receive procedure */
1729 F_ARRAY_SEND, /* send procedure */
1730 InvalidOid, /* typmodin procedure - none */
1731 InvalidOid, /* typmodout procedure - none */
1732 F_ARRAY_TYPANALYZE, /* analyze procedure */
1733 F_ARRAY_SUBSCRIPT_HANDLER, /* array subscript procedure */
1734 multirangeOid, /* element type ID */
1735 true, /* yes this is an array type */
1736 InvalidOid, /* no further array type */
1737 InvalidOid, /* base type ID */
1738 NULL, /* never a default type value */
1739 NULL, /* binary default isn't sent either */
1740 false, /* never passed by value */
1741 alignment, /* alignment - same as range's */
1742 'x', /* ARRAY is always toastable */
1743 -1, /* typMod (Domains only) */
1744 0, /* Array dimensions of typbasetype */
1745 false, /* Type NOT NULL */
1746 InvalidOid); /* typcollation */
1747
1748 /* Ensure these new types are visible to ProcedureCreate */
1750
1751 /* And create the constructor functions for this range type */
1758
1759 /* Create the entry in pg_range */
1764
1765 /* Create cast from the range type to its multirange type */
1769
1771
1772 return address;
1773}
#define PG_USED_FOR_ASSERTS_ONLY
Definition c.h:223
Oid regproc
Definition c.h:663
TypeName * defGetTypeName(DefElem *def)
Definition define.c:270
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition define.c:370
@ DEPENDENCY_INTERNAL
Definition dependency.h:35
bool get_typisdefined(Oid typid)
Definition lsyscache.c:2323
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition lsyscache.c:2421
Oid get_typcollation(Oid typid)
Definition lsyscache.c:3206
bool type_is_collatable(Oid typid)
Definition lsyscache.c:3231
ObjectAddress CastCreate(Oid sourcetypeid, Oid targettypeid, Oid funcid, Oid incastid, Oid outcastid, char castcontext, char castmethod, DependencyType behavior)
Definition pg_cast.c:49
void RangeCreate(Oid rangeTypeOid, Oid rangeSubType, Oid rangeCollation, Oid rangeSubOpclass, RegProcedure rangeCanonical, RegProcedure rangeSubDiff, Oid multirangeTypeOid, RegProcedure rangeConstruct2, RegProcedure rangeConstruct3, RegProcedure mltrngConstruct0, RegProcedure mltrngConstruct1, RegProcedure mltrngConstruct2)
Definition pg_range.c:36
char * makeMultirangeTypeName(const char *rangeTypeName, Oid typeNamespace)
Definition pg_type.c:948
Oid AssignTypeMultirangeOid(void)
Definition typecmds.c:2506
static Oid findRangeSubOpclass(List *opcname, Oid subtype)
Definition typecmds.c:2345
static void makeMultirangeConstructors(const char *name, Oid namespace, Oid multirangeOid, Oid rangeOid, Oid rangeArrayOid, Oid *mltrngConstruct0_p, Oid *mltrngConstruct1_p, Oid *mltrngConstruct2_p)
Definition typecmds.c:1869
static Oid findRangeSubtypeDiffFunction(List *procname, Oid subtype)
Definition typecmds.c:2425
static Oid findRangeCanonicalFunction(List *procname, Oid typeOid)
Definition typecmds.c:2384
static void makeRangeConstructors(const char *name, Oid namespace, Oid rangeOid, Oid subtype, Oid *rangeConstruct2_p, Oid *rangeConstruct3_p)
Definition typecmds.c:1788
Oid AssignTypeMultirangeArrayOid(void)
Definition typecmds.c:2539

References ACL_CREATE, aclcheck_error(), ACLCHECK_OK, Assert, AssignTypeArrayOid(), AssignTypeMultirangeArrayOid(), AssignTypeMultirangeOid(), CastCreate(), CommandCounterIncrement(), CStringGetDatum(), DEFAULT_TYPDELIM, defGetQualifiedName(), defGetTypeName(), DEPENDENCY_INTERNAL, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errhint(), errmsg(), ERROR, errorConflictingDefElem(), fb(), findRangeCanonicalFunction(), findRangeSubOpclass(), findRangeSubtypeDiffFunction(), format_type_be(), get_collation_oid(), get_namespace_name(), get_typcollation(), get_typisdefined(), get_typlenbyvalalign(), get_typtype(), GetSysCacheOid2, GetUserId(), InvalidOid, lfirst, makeArrayTypeName(), makeMultirangeConstructors(), makeMultirangeTypeName(), makeRangeConstructors(), moveArrayTypeName(), NIL, object_aclcheck(), OBJECT_SCHEMA, ObjectAddress::objectId, ObjectIdGetDatum(), OidIsValid, pfree(), PG_USED_FOR_ASSERTS_ONLY, QualifiedNameGetCreationNamespace(), RangeCreate(), stmt, type_is_collatable(), TypeCreate(), and typenameTypeId().

Referenced by ProcessUtilitySlow().

◆ DefineType()

ObjectAddress DefineType ( ParseState pstate,
List names,
List parameters 
)
extern

Definition at line 154 of file typecmds.c.

155{
156 char *typeName;
158 int16 internalLength = -1; /* default: variable-length */
159 List *inputName = NIL;
162 List *sendName = NIL;
167 char category = TYPCATEGORY_USER;
168 bool preferred = false;
171 char *defaultValue = NULL;
172 bool byValue = false;
173 char alignment = TYPALIGN_INT; /* default alignment */
174 char storage = TYPSTORAGE_PLAIN; /* default TOAST storage method */
175 Oid collation = InvalidOid;
197 Oid receiveOid = InvalidOid;
198 Oid sendOid = InvalidOid;
199 Oid typmodinOid = InvalidOid;
200 Oid typmodoutOid = InvalidOid;
201 Oid analyzeOid = InvalidOid;
202 Oid subscriptOid = InvalidOid;
203 char *array_type;
205 Oid typoid;
206 ListCell *pl;
207 ObjectAddress address;
208
209 /*
210 * As of Postgres 8.4, we require superuser privilege to create a base
211 * type. This is simple paranoia: there are too many ways to mess up the
212 * system with an incorrect type definition (for instance, representation
213 * parameters that don't match what the C code expects). In practice it
214 * takes superuser privilege to create the I/O functions, and so the
215 * former requirement that you own the I/O functions pretty much forced
216 * superuserness anyway. We're just making doubly sure here.
217 *
218 * XXX re-enable NOT_USED code sections below if you remove this test.
219 */
220 if (!superuser())
223 errmsg("must be superuser to create a base type")));
224
225 /* Convert list of names to a name and namespace */
227
228#ifdef NOT_USED
229 /* XXX this is unnecessary given the superuser check above */
230 /* Check we have creation rights in target namespace */
232 if (aclresult != ACLCHECK_OK)
235#endif
236
237 /*
238 * Look to see if type already exists.
239 */
241 CStringGetDatum(typeName),
243
244 /*
245 * If it's not a shell, see if it's an autogenerated array type, and if so
246 * rename it out of the way.
247 */
248 if (OidIsValid(typoid) && get_typisdefined(typoid))
249 {
250 if (moveArrayTypeName(typoid, typeName, typeNamespace))
251 typoid = InvalidOid;
252 else
255 errmsg("type \"%s\" already exists", typeName)));
256 }
257
258 /*
259 * If this command is a parameterless CREATE TYPE, then we're just here to
260 * make a shell type, so do that (or fail if there already is a shell).
261 */
262 if (parameters == NIL)
263 {
264 if (OidIsValid(typoid))
267 errmsg("type \"%s\" already exists", typeName)));
268
269 address = TypeShellMake(typeName, typeNamespace, GetUserId());
270 return address;
271 }
272
273 /*
274 * Otherwise, we must already have a shell type, since there is no other
275 * way that the I/O functions could have been created.
276 */
277 if (!OidIsValid(typoid))
280 errmsg("type \"%s\" does not exist", typeName),
281 errhint("Create the type as a shell type, then create its I/O functions, then do a full CREATE TYPE.")));
282
283 /* Extract the parameters from the parameter list */
284 foreach(pl, parameters)
285 {
286 DefElem *defel = (DefElem *) lfirst(pl);
287 DefElem **defelp;
288
289 if (strcmp(defel->defname, "like") == 0)
291 else if (strcmp(defel->defname, "internallength") == 0)
293 else if (strcmp(defel->defname, "input") == 0)
295 else if (strcmp(defel->defname, "output") == 0)
297 else if (strcmp(defel->defname, "receive") == 0)
299 else if (strcmp(defel->defname, "send") == 0)
301 else if (strcmp(defel->defname, "typmod_in") == 0)
303 else if (strcmp(defel->defname, "typmod_out") == 0)
305 else if (strcmp(defel->defname, "analyze") == 0 ||
306 strcmp(defel->defname, "analyse") == 0)
308 else if (strcmp(defel->defname, "subscript") == 0)
310 else if (strcmp(defel->defname, "category") == 0)
312 else if (strcmp(defel->defname, "preferred") == 0)
314 else if (strcmp(defel->defname, "delimiter") == 0)
316 else if (strcmp(defel->defname, "element") == 0)
318 else if (strcmp(defel->defname, "default") == 0)
320 else if (strcmp(defel->defname, "passedbyvalue") == 0)
321 defelp = &byValueEl;
322 else if (strcmp(defel->defname, "alignment") == 0)
324 else if (strcmp(defel->defname, "storage") == 0)
325 defelp = &storageEl;
326 else if (strcmp(defel->defname, "collatable") == 0)
328 else
329 {
330 /* WARNING, not ERROR, for historical backwards-compatibility */
333 errmsg("type attribute \"%s\" not recognized",
334 defel->defname),
335 parser_errposition(pstate, defel->location)));
336 continue;
337 }
338 if (*defelp != NULL)
340 *defelp = defel;
341 }
342
343 /*
344 * Now interpret the options; we do this separately so that LIKE can be
345 * overridden by other options regardless of the ordering in the parameter
346 * list.
347 */
348 if (likeTypeEl)
349 {
352
355 internalLength = likeForm->typlen;
356 byValue = likeForm->typbyval;
357 alignment = likeForm->typalign;
358 storage = likeForm->typstorage;
360 }
363 if (inputNameEl)
365 if (outputNameEl)
367 if (receiveNameEl)
369 if (sendNameEl)
371 if (typmodinNameEl)
373 if (typmodoutNameEl)
375 if (analyzeNameEl)
377 if (subscriptNameEl)
379 if (categoryEl)
380 {
381 char *p = defGetString(categoryEl);
382
383 category = p[0];
384 /* restrict to non-control ASCII */
388 errmsg("invalid type category \"%s\": must be simple ASCII",
389 p)));
390 }
391 if (preferredEl)
393 if (delimiterEl)
394 {
395 char *p = defGetString(delimiterEl);
396
397 delimiter = p[0];
398 /* XXX shouldn't we restrict the delimiter? */
399 }
400 if (elemTypeEl)
401 {
403 /* disallow arrays of pseudotypes */
407 errmsg("array element type cannot be %s",
409 }
410 if (defaultValueEl)
412 if (byValueEl)
414 if (alignmentEl)
415 {
416 char *a = defGetString(alignmentEl);
417
418 /*
419 * Note: if argument was an unquoted identifier, parser will have
420 * applied translations to it, so be prepared to recognize translated
421 * type names as well as the nominal form.
422 */
423 if (pg_strcasecmp(a, "double") == 0 ||
424 pg_strcasecmp(a, "float8") == 0 ||
425 pg_strcasecmp(a, "pg_catalog.float8") == 0)
427 else if (pg_strcasecmp(a, "int4") == 0 ||
428 pg_strcasecmp(a, "pg_catalog.int4") == 0)
430 else if (pg_strcasecmp(a, "int2") == 0 ||
431 pg_strcasecmp(a, "pg_catalog.int2") == 0)
433 else if (pg_strcasecmp(a, "char") == 0 ||
434 pg_strcasecmp(a, "pg_catalog.bpchar") == 0)
436 else
439 errmsg("alignment \"%s\" not recognized", a)));
440 }
441 if (storageEl)
442 {
443 char *a = defGetString(storageEl);
444
445 if (pg_strcasecmp(a, "plain") == 0)
447 else if (pg_strcasecmp(a, "external") == 0)
449 else if (pg_strcasecmp(a, "extended") == 0)
451 else if (pg_strcasecmp(a, "main") == 0)
453 else
456 errmsg("storage \"%s\" not recognized", a)));
457 }
458 if (collatableEl)
460
461 /*
462 * make sure we have our required definitions
463 */
464 if (inputName == NIL)
467 errmsg("type input function must be specified")));
468 if (outputName == NIL)
471 errmsg("type output function must be specified")));
472
473 if (typmodinName == NIL && typmodoutName != NIL)
476 errmsg("type modifier output function is useless without a type modifier input function")));
477
478 /*
479 * Convert I/O proc names to OIDs
480 */
483 if (receiveName)
484 receiveOid = findTypeReceiveFunction(receiveName, typoid);
485 if (sendName)
486 sendOid = findTypeSendFunction(sendName, typoid);
487
488 /*
489 * Convert typmodin/out function proc names to OIDs.
490 */
491 if (typmodinName)
493 if (typmodoutName)
495
496 /*
497 * Convert analysis function proc name to an OID. If no analysis function
498 * is specified, we'll use zero to select the built-in default algorithm.
499 */
500 if (analyzeName)
501 analyzeOid = findTypeAnalyzeFunction(analyzeName, typoid);
502
503 /*
504 * Likewise look up the subscripting function if any. If it is not
505 * specified, but a typelem is specified, allow that if
506 * raw_array_subscript_handler can be used. (This is for backwards
507 * compatibility; maybe someday we should throw an error instead.)
508 */
509 if (subscriptName)
510 subscriptOid = findTypeSubscriptingFunction(subscriptName, typoid);
511 else if (OidIsValid(elemType))
512 {
513 if (internalLength > 0 && !byValue && get_typlen(elemType) > 0)
514 subscriptOid = F_RAW_ARRAY_SUBSCRIPT_HANDLER;
515 else
518 errmsg("element type cannot be specified without a subscripting function")));
519 }
520
521 /*
522 * Check permissions on functions. We choose to require the creator/owner
523 * of a type to also own the underlying functions. Since creating a type
524 * is tantamount to granting public execute access on the functions, the
525 * minimum sane check would be for execute-with-grant-option. But we
526 * don't have a way to make the type go away if the grant option is
527 * revoked, so ownership seems better.
528 *
529 * XXX For now, this is all unnecessary given the superuser check above.
530 * If we ever relax that, these calls likely should be moved into
531 * findTypeInputFunction et al, where they could be shared by AlterType.
532 */
533#ifdef NOT_USED
540 if (receiveOid && !object_ownercheck(ProcedureRelationId, receiveOid, GetUserId()))
543 if (sendOid && !object_ownercheck(ProcedureRelationId, sendOid, GetUserId()))
546 if (typmodinOid && !object_ownercheck(ProcedureRelationId, typmodinOid, GetUserId()))
549 if (typmodoutOid && !object_ownercheck(ProcedureRelationId, typmodoutOid, GetUserId()))
552 if (analyzeOid && !object_ownercheck(ProcedureRelationId, analyzeOid, GetUserId()))
555 if (subscriptOid && !object_ownercheck(ProcedureRelationId, subscriptOid, GetUserId()))
558#endif
559
560 /*
561 * OK, we're done checking, time to make the type. We must assign the
562 * array type OID ahead of calling TypeCreate, since the base type and
563 * array type each refer to the other.
564 */
566
567 /*
568 * now have TypeCreate do all the real work.
569 *
570 * Note: the pg_type.oid is stored in user tables as array elements (base
571 * types) in ArrayType and in composite types in DatumTupleFields. This
572 * oid must be preserved by binary upgrades.
573 */
574 address =
575 TypeCreate(InvalidOid, /* no predetermined type OID */
576 typeName, /* type name */
577 typeNamespace, /* namespace */
578 InvalidOid, /* relation oid (n/a here) */
579 0, /* relation kind (ditto) */
580 GetUserId(), /* owner's ID */
581 internalLength, /* internal size */
582 TYPTYPE_BASE, /* type-type (base type) */
583 category, /* type-category */
584 preferred, /* is it a preferred type? */
585 delimiter, /* array element delimiter */
586 inputOid, /* input procedure */
587 outputOid, /* output procedure */
588 receiveOid, /* receive procedure */
589 sendOid, /* send procedure */
590 typmodinOid, /* typmodin procedure */
591 typmodoutOid, /* typmodout procedure */
592 analyzeOid, /* analyze procedure */
593 subscriptOid, /* subscript procedure */
594 elemType, /* element type ID */
595 false, /* this is not an implicit array type */
596 array_oid, /* array type we are about to create */
597 InvalidOid, /* base type ID (only for domains) */
598 defaultValue, /* default type value */
599 NULL, /* no binary form available */
600 byValue, /* passed by value */
601 alignment, /* required alignment */
602 storage, /* TOAST strategy */
603 -1, /* typMod (Domains only) */
604 0, /* Array Dimensions of typbasetype */
605 false, /* Type NOT NULL */
606 collation); /* type's collation */
607 Assert(typoid == address.objectId);
608
609 /*
610 * Create the array type that goes with it.
611 */
612 array_type = makeArrayTypeName(typeName, typeNamespace);
613
614 /* alignment must be TYPALIGN_INT or TYPALIGN_DOUBLE for arrays */
616
617 TypeCreate(array_oid, /* force assignment of this type OID */
618 array_type, /* type name */
619 typeNamespace, /* namespace */
620 InvalidOid, /* relation oid (n/a here) */
621 0, /* relation kind (ditto) */
622 GetUserId(), /* owner's ID */
623 -1, /* internal size (always varlena) */
624 TYPTYPE_BASE, /* type-type (base type) */
625 TYPCATEGORY_ARRAY, /* type-category (array) */
626 false, /* array types are never preferred */
627 delimiter, /* array element delimiter */
628 F_ARRAY_IN, /* input procedure */
629 F_ARRAY_OUT, /* output procedure */
630 F_ARRAY_RECV, /* receive procedure */
631 F_ARRAY_SEND, /* send procedure */
632 typmodinOid, /* typmodin procedure */
633 typmodoutOid, /* typmodout procedure */
634 F_ARRAY_TYPANALYZE, /* analyze procedure */
635 F_ARRAY_SUBSCRIPT_HANDLER, /* array subscript procedure */
636 typoid, /* element type ID */
637 true, /* yes this is an array type */
638 InvalidOid, /* no further array type */
639 InvalidOid, /* base type ID */
640 NULL, /* never a default type value */
641 NULL, /* binary default isn't sent either */
642 false, /* never passed by value */
643 alignment, /* see above */
644 TYPSTORAGE_EXTENDED, /* ARRAY is always toastable */
645 -1, /* typMod (Domains only) */
646 0, /* Array dimensions of typbasetype */
647 false, /* Type NOT NULL */
648 collation); /* type's collation */
649
650 pfree(array_type);
651
652 return address;
653}
int defGetTypeLength(DefElem *def)
Definition define.c:298
bool defGetBoolean(DefElem *def)
Definition define.c:93
#define WARNING
Definition elog.h:36
int16 get_typlen(Oid typid)
Definition lsyscache.c:2347
char * NameListToString(const List *names)
Definition namespace.c:3664
@ OBJECT_FUNCTION
ObjectAddress TypeShellMake(const char *typeName, Oid typeNamespace, Oid ownerId)
Definition pg_type.c:57
static Oid findTypeOutputFunction(List *procname, Oid typeOid)
Definition typecmds.c:2079
static Oid findTypeInputFunction(List *procname, Oid typeOid)
Definition typecmds.c:2016

References a, ACL_CREATE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, Assert, AssignTypeArrayOid(), CStringGetDatum(), DEFAULT_TYPDELIM, defGetBoolean(), defGetQualifiedName(), defGetString(), defGetTypeLength(), defGetTypeName(), ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errhint(), errmsg(), ERROR, errorConflictingDefElem(), fb(), findTypeAnalyzeFunction(), findTypeInputFunction(), findTypeOutputFunction(), findTypeReceiveFunction(), findTypeSendFunction(), findTypeSubscriptingFunction(), findTypeTypmodinFunction(), findTypeTypmodoutFunction(), format_type_be(), get_namespace_name(), get_typisdefined(), get_typlen(), get_typtype(), GETSTRUCT(), GetSysCacheOid2, GetUserId(), InvalidOid, lfirst, makeArrayTypeName(), moveArrayTypeName(), NameListToString(), NIL, object_aclcheck(), OBJECT_FUNCTION, object_ownercheck(), OBJECT_SCHEMA, ObjectAddress::objectId, ObjectIdGetDatum(), OidIsValid, parser_errposition(), pfree(), pg_strcasecmp(), QualifiedNameGetCreationNamespace(), ReleaseSysCache(), storage, superuser(), TypeCreate(), typenameType(), typenameTypeId(), TypeShellMake(), and WARNING.

Referenced by ProcessUtilitySlow().

◆ RemoveTypeById()

void RemoveTypeById ( Oid  typeOid)
extern

Definition at line 659 of file typecmds.c.

660{
661 Relation relation;
663
665
667 if (!HeapTupleIsValid(tup))
668 elog(ERROR, "cache lookup failed for type %u", typeOid);
669
670 CatalogTupleDelete(relation, &tup->t_self);
671
672 /*
673 * If it is an enum, delete the pg_enum entries too; we don't bother with
674 * making dependency entries for those, so it has to be done "by hand"
675 * here.
676 */
677 if (((Form_pg_type) GETSTRUCT(tup))->typtype == TYPTYPE_ENUM)
678 EnumValuesDelete(typeOid);
679
680 /*
681 * If it is a range type, delete the pg_range entry too; we don't bother
682 * with making a dependency entry for that, so it has to be done "by hand"
683 * here.
684 */
685 if (((Form_pg_type) GETSTRUCT(tup))->typtype == TYPTYPE_RANGE)
686 RangeDelete(typeOid);
687
689
690 table_close(relation, RowExclusiveLock);
691}
void CatalogTupleDelete(Relation heapRel, const ItemPointerData *tid)
Definition indexing.c:365
void EnumValuesDelete(Oid enumTypeOid)
Definition pg_enum.c:237
void RangeDelete(Oid rangeTypeOid)
Definition pg_range.c:120

References CatalogTupleDelete(), elog, EnumValuesDelete(), ERROR, fb(), GETSTRUCT(), HeapTupleIsValid, ObjectIdGetDatum(), RangeDelete(), ReleaseSysCache(), RowExclusiveLock, SearchSysCache1(), table_close(), and table_open().

Referenced by doDeletion().

◆ RenameType()

ObjectAddress RenameType ( RenameStmt stmt)
extern

Definition at line 3776 of file typecmds.c.

3777{
3778 List *names = castNode(List, stmt->object);
3779 const char *newTypeName = stmt->newname;
3780 TypeName *typename;
3781 Oid typeOid;
3782 Relation rel;
3783 HeapTuple tup;
3785 ObjectAddress address;
3786
3787 /* Make a TypeName so we can use standard type lookup machinery */
3788 typename = makeTypeNameFromNameList(names);
3789 typeOid = typenameTypeId(NULL, typename);
3790
3791 /* Look up the type in the type table */
3793
3795 if (!HeapTupleIsValid(tup))
3796 elog(ERROR, "cache lookup failed for type %u", typeOid);
3798
3799 /* check permissions on type */
3800 if (!object_ownercheck(TypeRelationId, typeOid, GetUserId()))
3802
3803 /* ALTER DOMAIN used on a non-domain? */
3804 if (stmt->renameType == OBJECT_DOMAIN && typTup->typtype != TYPTYPE_DOMAIN)
3805 ereport(ERROR,
3807 errmsg("%s is not a domain",
3808 format_type_be(typeOid))));
3809
3810 /*
3811 * If it's a composite type, we need to check that it really is a
3812 * free-standing composite type, and not a table's rowtype. We want people
3813 * to use ALTER TABLE not ALTER TYPE for that case.
3814 */
3815 if (typTup->typtype == TYPTYPE_COMPOSITE &&
3817 ereport(ERROR,
3819 errmsg("%s is a table's row type",
3820 format_type_be(typeOid)),
3821 /* translator: %s is an SQL ALTER command */
3822 errhint("Use %s instead.",
3823 "ALTER TABLE")));
3824
3825 /* don't allow direct alteration of array types, either */
3827 ereport(ERROR,
3829 errmsg("cannot alter array type %s",
3830 format_type_be(typeOid)),
3831 errhint("You can alter type %s, which will alter the array type as well.",
3832 format_type_be(typTup->typelem))));
3833
3834 /* we do allow separate renaming of multirange types, though */
3835
3836 /*
3837 * If type is composite we need to rename associated pg_class entry too.
3838 * RenameRelationInternal will call RenameTypeInternal automatically.
3839 */
3840 if (typTup->typtype == TYPTYPE_COMPOSITE)
3841 RenameRelationInternal(typTup->typrelid, newTypeName, false, false);
3842 else
3844 typTup->typnamespace);
3845
3846 ObjectAddressSet(address, TypeRelationId, typeOid);
3847 /* Clean up */
3849
3850 return address;
3851}
#define castNode(_type_, nodeptr)
Definition nodes.h:182
void RenameTypeInternal(Oid typeOid, const char *newTypeName, Oid typeNamespace)
Definition pg_type.c:763
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
Definition tablecmds.c:4268

References aclcheck_error_type(), ACLCHECK_NOT_OWNER, castNode, elog, ereport, errcode(), errhint(), errmsg(), ERROR, fb(), format_type_be(), get_rel_relkind(), GETSTRUCT(), GetUserId(), HeapTupleIsValid, makeTypeNameFromNameList(), OBJECT_DOMAIN, object_ownercheck(), ObjectAddressSet, ObjectIdGetDatum(), RenameRelationInternal(), RenameTypeInternal(), RowExclusiveLock, SearchSysCacheCopy1, stmt, table_close(), table_open(), and typenameTypeId().

Referenced by ExecRenameStmt().