00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032 #include "postgres.h"
00033
00034 #include "access/genam.h"
00035 #include "access/heapam.h"
00036 #include "access/htup_details.h"
00037 #include "access/xact.h"
00038 #include "catalog/catalog.h"
00039 #include "catalog/dependency.h"
00040 #include "catalog/heap.h"
00041 #include "catalog/indexing.h"
00042 #include "catalog/objectaccess.h"
00043 #include "catalog/pg_authid.h"
00044 #include "catalog/pg_collation.h"
00045 #include "catalog/pg_constraint.h"
00046 #include "catalog/pg_depend.h"
00047 #include "catalog/pg_enum.h"
00048 #include "catalog/pg_language.h"
00049 #include "catalog/pg_namespace.h"
00050 #include "catalog/pg_proc.h"
00051 #include "catalog/pg_proc_fn.h"
00052 #include "catalog/pg_range.h"
00053 #include "catalog/pg_type.h"
00054 #include "catalog/pg_type_fn.h"
00055 #include "commands/defrem.h"
00056 #include "commands/tablecmds.h"
00057 #include "commands/typecmds.h"
00058 #include "executor/executor.h"
00059 #include "miscadmin.h"
00060 #include "nodes/makefuncs.h"
00061 #include "optimizer/planner.h"
00062 #include "optimizer/var.h"
00063 #include "parser/parse_coerce.h"
00064 #include "parser/parse_collate.h"
00065 #include "parser/parse_expr.h"
00066 #include "parser/parse_func.h"
00067 #include "parser/parse_type.h"
00068 #include "utils/acl.h"
00069 #include "utils/builtins.h"
00070 #include "utils/fmgroids.h"
00071 #include "utils/lsyscache.h"
00072 #include "utils/memutils.h"
00073 #include "utils/rel.h"
00074 #include "utils/syscache.h"
00075 #include "utils/tqual.h"
00076
00077
00078
00079 typedef struct
00080 {
00081 Relation rel;
00082 int natts;
00083 int *atts;
00084
00085 } RelToCheck;
00086
00087
00088 Oid binary_upgrade_next_array_pg_type_oid = InvalidOid;
00089
00090 static void makeRangeConstructors(const char *name, Oid namespace,
00091 Oid rangeOid, Oid subtype);
00092 static Oid findTypeInputFunction(List *procname, Oid typeOid);
00093 static Oid findTypeOutputFunction(List *procname, Oid typeOid);
00094 static Oid findTypeReceiveFunction(List *procname, Oid typeOid);
00095 static Oid findTypeSendFunction(List *procname, Oid typeOid);
00096 static Oid findTypeTypmodinFunction(List *procname);
00097 static Oid findTypeTypmodoutFunction(List *procname);
00098 static Oid findTypeAnalyzeFunction(List *procname, Oid typeOid);
00099 static Oid findRangeSubOpclass(List *opcname, Oid subtype);
00100 static Oid findRangeCanonicalFunction(List *procname, Oid typeOid);
00101 static Oid findRangeSubtypeDiffFunction(List *procname, Oid subtype);
00102 static void validateDomainConstraint(Oid domainoid, char *ccbin);
00103 static List *get_rels_with_domain(Oid domainOid, LOCKMODE lockmode);
00104 static void checkEnumOwner(HeapTuple tup);
00105 static char *domainAddConstraint(Oid domainOid, Oid domainNamespace,
00106 Oid baseTypeOid,
00107 int typMod, Constraint *constr,
00108 char *domainName);
00109
00110
00111
00112
00113
00114
00115 Oid
00116 DefineType(List *names, List *parameters)
00117 {
00118 char *typeName;
00119 Oid typeNamespace;
00120 int16 internalLength = -1;
00121 List *inputName = NIL;
00122 List *outputName = NIL;
00123 List *receiveName = NIL;
00124 List *sendName = NIL;
00125 List *typmodinName = NIL;
00126 List *typmodoutName = NIL;
00127 List *analyzeName = NIL;
00128 char category = TYPCATEGORY_USER;
00129 bool preferred = false;
00130 char delimiter = DEFAULT_TYPDELIM;
00131 Oid elemType = InvalidOid;
00132 char *defaultValue = NULL;
00133 bool byValue = false;
00134 char alignment = 'i';
00135 char storage = 'p';
00136 Oid collation = InvalidOid;
00137 DefElem *likeTypeEl = NULL;
00138 DefElem *internalLengthEl = NULL;
00139 DefElem *inputNameEl = NULL;
00140 DefElem *outputNameEl = NULL;
00141 DefElem *receiveNameEl = NULL;
00142 DefElem *sendNameEl = NULL;
00143 DefElem *typmodinNameEl = NULL;
00144 DefElem *typmodoutNameEl = NULL;
00145 DefElem *analyzeNameEl = NULL;
00146 DefElem *categoryEl = NULL;
00147 DefElem *preferredEl = NULL;
00148 DefElem *delimiterEl = NULL;
00149 DefElem *elemTypeEl = NULL;
00150 DefElem *defaultValueEl = NULL;
00151 DefElem *byValueEl = NULL;
00152 DefElem *alignmentEl = NULL;
00153 DefElem *storageEl = NULL;
00154 DefElem *collatableEl = NULL;
00155 Oid inputOid;
00156 Oid outputOid;
00157 Oid receiveOid = InvalidOid;
00158 Oid sendOid = InvalidOid;
00159 Oid typmodinOid = InvalidOid;
00160 Oid typmodoutOid = InvalidOid;
00161 Oid analyzeOid = InvalidOid;
00162 char *array_type;
00163 Oid array_oid;
00164 Oid typoid;
00165 Oid resulttype;
00166 ListCell *pl;
00167
00168
00169
00170
00171
00172
00173
00174
00175
00176
00177
00178
00179 if (!superuser())
00180 ereport(ERROR,
00181 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
00182 errmsg("must be superuser to create a base type")));
00183
00184
00185 typeNamespace = QualifiedNameGetCreationNamespace(names, &typeName);
00186
00187 #ifdef NOT_USED
00188
00189
00190 aclresult = pg_namespace_aclcheck(typeNamespace, GetUserId(), ACL_CREATE);
00191 if (aclresult != ACLCHECK_OK)
00192 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
00193 get_namespace_name(typeNamespace));
00194 #endif
00195
00196
00197
00198
00199
00200 typoid = GetSysCacheOid2(TYPENAMENSP,
00201 CStringGetDatum(typeName),
00202 ObjectIdGetDatum(typeNamespace));
00203
00204
00205
00206
00207
00208 if (OidIsValid(typoid) && get_typisdefined(typoid))
00209 {
00210 if (moveArrayTypeName(typoid, typeName, typeNamespace))
00211 typoid = InvalidOid;
00212 }
00213
00214
00215
00216
00217
00218 if (!OidIsValid(typoid))
00219 {
00220 typoid = TypeShellMake(typeName, typeNamespace, GetUserId());
00221
00222 CommandCounterIncrement();
00223
00224
00225
00226
00227
00228 if (parameters == NIL)
00229 return InvalidOid;
00230 }
00231 else
00232 {
00233
00234 if (parameters == NIL)
00235 ereport(ERROR,
00236 (errcode(ERRCODE_DUPLICATE_OBJECT),
00237 errmsg("type \"%s\" already exists", typeName)));
00238 }
00239
00240
00241 foreach(pl, parameters)
00242 {
00243 DefElem *defel = (DefElem *) lfirst(pl);
00244 DefElem **defelp;
00245
00246 if (pg_strcasecmp(defel->defname, "like") == 0)
00247 defelp = &likeTypeEl;
00248 else if (pg_strcasecmp(defel->defname, "internallength") == 0)
00249 defelp = &internalLengthEl;
00250 else if (pg_strcasecmp(defel->defname, "input") == 0)
00251 defelp = &inputNameEl;
00252 else if (pg_strcasecmp(defel->defname, "output") == 0)
00253 defelp = &outputNameEl;
00254 else if (pg_strcasecmp(defel->defname, "receive") == 0)
00255 defelp = &receiveNameEl;
00256 else if (pg_strcasecmp(defel->defname, "send") == 0)
00257 defelp = &sendNameEl;
00258 else if (pg_strcasecmp(defel->defname, "typmod_in") == 0)
00259 defelp = &typmodinNameEl;
00260 else if (pg_strcasecmp(defel->defname, "typmod_out") == 0)
00261 defelp = &typmodoutNameEl;
00262 else if (pg_strcasecmp(defel->defname, "analyze") == 0 ||
00263 pg_strcasecmp(defel->defname, "analyse") == 0)
00264 defelp = &analyzeNameEl;
00265 else if (pg_strcasecmp(defel->defname, "category") == 0)
00266 defelp = &categoryEl;
00267 else if (pg_strcasecmp(defel->defname, "preferred") == 0)
00268 defelp = &preferredEl;
00269 else if (pg_strcasecmp(defel->defname, "delimiter") == 0)
00270 defelp = &delimiterEl;
00271 else if (pg_strcasecmp(defel->defname, "element") == 0)
00272 defelp = &elemTypeEl;
00273 else if (pg_strcasecmp(defel->defname, "default") == 0)
00274 defelp = &defaultValueEl;
00275 else if (pg_strcasecmp(defel->defname, "passedbyvalue") == 0)
00276 defelp = &byValueEl;
00277 else if (pg_strcasecmp(defel->defname, "alignment") == 0)
00278 defelp = &alignmentEl;
00279 else if (pg_strcasecmp(defel->defname, "storage") == 0)
00280 defelp = &storageEl;
00281 else if (pg_strcasecmp(defel->defname, "collatable") == 0)
00282 defelp = &collatableEl;
00283 else
00284 {
00285
00286 ereport(WARNING,
00287 (errcode(ERRCODE_SYNTAX_ERROR),
00288 errmsg("type attribute \"%s\" not recognized",
00289 defel->defname)));
00290 continue;
00291 }
00292 if (*defelp != NULL)
00293 ereport(ERROR,
00294 (errcode(ERRCODE_SYNTAX_ERROR),
00295 errmsg("conflicting or redundant options")));
00296 *defelp = defel;
00297 }
00298
00299
00300
00301
00302
00303
00304 if (likeTypeEl)
00305 {
00306 Type likeType;
00307 Form_pg_type likeForm;
00308
00309 likeType = typenameType(NULL, defGetTypeName(likeTypeEl), NULL);
00310 likeForm = (Form_pg_type) GETSTRUCT(likeType);
00311 internalLength = likeForm->typlen;
00312 byValue = likeForm->typbyval;
00313 alignment = likeForm->typalign;
00314 storage = likeForm->typstorage;
00315 ReleaseSysCache(likeType);
00316 }
00317 if (internalLengthEl)
00318 internalLength = defGetTypeLength(internalLengthEl);
00319 if (inputNameEl)
00320 inputName = defGetQualifiedName(inputNameEl);
00321 if (outputNameEl)
00322 outputName = defGetQualifiedName(outputNameEl);
00323 if (receiveNameEl)
00324 receiveName = defGetQualifiedName(receiveNameEl);
00325 if (sendNameEl)
00326 sendName = defGetQualifiedName(sendNameEl);
00327 if (typmodinNameEl)
00328 typmodinName = defGetQualifiedName(typmodinNameEl);
00329 if (typmodoutNameEl)
00330 typmodoutName = defGetQualifiedName(typmodoutNameEl);
00331 if (analyzeNameEl)
00332 analyzeName = defGetQualifiedName(analyzeNameEl);
00333 if (categoryEl)
00334 {
00335 char *p = defGetString(categoryEl);
00336
00337 category = p[0];
00338
00339 if (category < 32 || category > 126)
00340 ereport(ERROR,
00341 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
00342 errmsg("invalid type category \"%s\": must be simple ASCII",
00343 p)));
00344 }
00345 if (preferredEl)
00346 preferred = defGetBoolean(preferredEl);
00347 if (delimiterEl)
00348 {
00349 char *p = defGetString(delimiterEl);
00350
00351 delimiter = p[0];
00352
00353 }
00354 if (elemTypeEl)
00355 {
00356 elemType = typenameTypeId(NULL, defGetTypeName(elemTypeEl));
00357
00358 if (get_typtype(elemType) == TYPTYPE_PSEUDO)
00359 ereport(ERROR,
00360 (errcode(ERRCODE_DATATYPE_MISMATCH),
00361 errmsg("array element type cannot be %s",
00362 format_type_be(elemType))));
00363 }
00364 if (defaultValueEl)
00365 defaultValue = defGetString(defaultValueEl);
00366 if (byValueEl)
00367 byValue = defGetBoolean(byValueEl);
00368 if (alignmentEl)
00369 {
00370 char *a = defGetString(alignmentEl);
00371
00372
00373
00374
00375
00376
00377 if (pg_strcasecmp(a, "double") == 0 ||
00378 pg_strcasecmp(a, "float8") == 0 ||
00379 pg_strcasecmp(a, "pg_catalog.float8") == 0)
00380 alignment = 'd';
00381 else if (pg_strcasecmp(a, "int4") == 0 ||
00382 pg_strcasecmp(a, "pg_catalog.int4") == 0)
00383 alignment = 'i';
00384 else if (pg_strcasecmp(a, "int2") == 0 ||
00385 pg_strcasecmp(a, "pg_catalog.int2") == 0)
00386 alignment = 's';
00387 else if (pg_strcasecmp(a, "char") == 0 ||
00388 pg_strcasecmp(a, "pg_catalog.bpchar") == 0)
00389 alignment = 'c';
00390 else
00391 ereport(ERROR,
00392 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
00393 errmsg("alignment \"%s\" not recognized", a)));
00394 }
00395 if (storageEl)
00396 {
00397 char *a = defGetString(storageEl);
00398
00399 if (pg_strcasecmp(a, "plain") == 0)
00400 storage = 'p';
00401 else if (pg_strcasecmp(a, "external") == 0)
00402 storage = 'e';
00403 else if (pg_strcasecmp(a, "extended") == 0)
00404 storage = 'x';
00405 else if (pg_strcasecmp(a, "main") == 0)
00406 storage = 'm';
00407 else
00408 ereport(ERROR,
00409 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
00410 errmsg("storage \"%s\" not recognized", a)));
00411 }
00412 if (collatableEl)
00413 collation = defGetBoolean(collatableEl) ? DEFAULT_COLLATION_OID : InvalidOid;
00414
00415
00416
00417
00418 if (inputName == NIL)
00419 ereport(ERROR,
00420 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
00421 errmsg("type input function must be specified")));
00422 if (outputName == NIL)
00423 ereport(ERROR,
00424 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
00425 errmsg("type output function must be specified")));
00426
00427 if (typmodinName == NIL && typmodoutName != NIL)
00428 ereport(ERROR,
00429 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
00430 errmsg("type modifier output function is useless without a type modifier input function")));
00431
00432
00433
00434
00435 inputOid = findTypeInputFunction(inputName, typoid);
00436 outputOid = findTypeOutputFunction(outputName, typoid);
00437 if (receiveName)
00438 receiveOid = findTypeReceiveFunction(receiveName, typoid);
00439 if (sendName)
00440 sendOid = findTypeSendFunction(sendName, typoid);
00441
00442
00443
00444
00445
00446 resulttype = get_func_rettype(inputOid);
00447 if (resulttype != typoid)
00448 {
00449 if (resulttype == OPAQUEOID)
00450 {
00451
00452 ereport(WARNING,
00453 (errmsg("changing return type of function %s from \"opaque\" to %s",
00454 NameListToString(inputName), typeName)));
00455 SetFunctionReturnType(inputOid, typoid);
00456 }
00457 else
00458 ereport(ERROR,
00459 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
00460 errmsg("type input function %s must return type %s",
00461 NameListToString(inputName), typeName)));
00462 }
00463 resulttype = get_func_rettype(outputOid);
00464 if (resulttype != CSTRINGOID)
00465 {
00466 if (resulttype == OPAQUEOID)
00467 {
00468
00469 ereport(WARNING,
00470 (errmsg("changing return type of function %s from \"opaque\" to \"cstring\"",
00471 NameListToString(outputName))));
00472 SetFunctionReturnType(outputOid, CSTRINGOID);
00473 }
00474 else
00475 ereport(ERROR,
00476 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
00477 errmsg("type output function %s must return type \"cstring\"",
00478 NameListToString(outputName))));
00479 }
00480 if (receiveOid)
00481 {
00482 resulttype = get_func_rettype(receiveOid);
00483 if (resulttype != typoid)
00484 ereport(ERROR,
00485 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
00486 errmsg("type receive function %s must return type %s",
00487 NameListToString(receiveName), typeName)));
00488 }
00489 if (sendOid)
00490 {
00491 resulttype = get_func_rettype(sendOid);
00492 if (resulttype != BYTEAOID)
00493 ereport(ERROR,
00494 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
00495 errmsg("type send function %s must return type \"bytea\"",
00496 NameListToString(sendName))));
00497 }
00498
00499
00500
00501
00502 if (typmodinName)
00503 typmodinOid = findTypeTypmodinFunction(typmodinName);
00504 if (typmodoutName)
00505 typmodoutOid = findTypeTypmodoutFunction(typmodoutName);
00506
00507
00508
00509
00510
00511 if (analyzeName)
00512 analyzeOid = findTypeAnalyzeFunction(analyzeName, typoid);
00513
00514
00515
00516
00517
00518
00519
00520
00521
00522 #ifdef NOT_USED
00523
00524 if (inputOid && !pg_proc_ownercheck(inputOid, GetUserId()))
00525 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
00526 NameListToString(inputName));
00527 if (outputOid && !pg_proc_ownercheck(outputOid, GetUserId()))
00528 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
00529 NameListToString(outputName));
00530 if (receiveOid && !pg_proc_ownercheck(receiveOid, GetUserId()))
00531 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
00532 NameListToString(receiveName));
00533 if (sendOid && !pg_proc_ownercheck(sendOid, GetUserId()))
00534 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
00535 NameListToString(sendName));
00536 if (typmodinOid && !pg_proc_ownercheck(typmodinOid, GetUserId()))
00537 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
00538 NameListToString(typmodinName));
00539 if (typmodoutOid && !pg_proc_ownercheck(typmodoutOid, GetUserId()))
00540 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
00541 NameListToString(typmodoutName));
00542 if (analyzeOid && !pg_proc_ownercheck(analyzeOid, GetUserId()))
00543 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
00544 NameListToString(analyzeName));
00545 #endif
00546
00547 array_oid = AssignTypeArrayOid();
00548
00549
00550
00551
00552
00553
00554
00555
00556 typoid =
00557 TypeCreate(InvalidOid,
00558 typeName,
00559 typeNamespace,
00560 InvalidOid,
00561 0,
00562 GetUserId(),
00563 internalLength,
00564 TYPTYPE_BASE,
00565 category,
00566 preferred,
00567 delimiter,
00568 inputOid,
00569 outputOid,
00570 receiveOid,
00571 sendOid,
00572 typmodinOid,
00573 typmodoutOid,
00574 analyzeOid,
00575 elemType,
00576 false,
00577 array_oid,
00578 InvalidOid,
00579 defaultValue,
00580 NULL,
00581 byValue,
00582 alignment,
00583 storage,
00584 -1,
00585 0,
00586 false,
00587 collation);
00588
00589
00590
00591
00592 array_type = makeArrayTypeName(typeName, typeNamespace);
00593
00594
00595 alignment = (alignment == 'd') ? 'd' : 'i';
00596
00597 typoid = TypeCreate(array_oid,
00598 array_type,
00599 typeNamespace,
00600 InvalidOid,
00601 0,
00602 GetUserId(),
00603 -1,
00604 TYPTYPE_BASE,
00605 TYPCATEGORY_ARRAY,
00606 false,
00607 delimiter,
00608 F_ARRAY_IN,
00609 F_ARRAY_OUT,
00610 F_ARRAY_RECV,
00611 F_ARRAY_SEND,
00612 typmodinOid,
00613 typmodoutOid,
00614 F_ARRAY_TYPANALYZE,
00615 typoid,
00616 true,
00617 InvalidOid,
00618 InvalidOid,
00619 NULL,
00620 NULL,
00621 false,
00622 alignment,
00623 'x',
00624 -1,
00625 0,
00626 false,
00627 collation);
00628
00629 pfree(array_type);
00630
00631 return typoid;
00632 }
00633
00634
00635
00636
00637 void
00638 RemoveTypeById(Oid typeOid)
00639 {
00640 Relation relation;
00641 HeapTuple tup;
00642
00643 relation = heap_open(TypeRelationId, RowExclusiveLock);
00644
00645 tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typeOid));
00646 if (!HeapTupleIsValid(tup))
00647 elog(ERROR, "cache lookup failed for type %u", typeOid);
00648
00649 simple_heap_delete(relation, &tup->t_self);
00650
00651
00652
00653
00654
00655
00656 if (((Form_pg_type) GETSTRUCT(tup))->typtype == TYPTYPE_ENUM)
00657 EnumValuesDelete(typeOid);
00658
00659
00660
00661
00662
00663
00664 if (((Form_pg_type) GETSTRUCT(tup))->typtype == TYPTYPE_RANGE)
00665 RangeDelete(typeOid);
00666
00667 ReleaseSysCache(tup);
00668
00669 heap_close(relation, RowExclusiveLock);
00670 }
00671
00672
00673
00674
00675
00676
00677 Oid
00678 DefineDomain(CreateDomainStmt *stmt)
00679 {
00680 char *domainName;
00681 Oid domainNamespace;
00682 AclResult aclresult;
00683 int16 internalLength;
00684 Oid inputProcedure;
00685 Oid outputProcedure;
00686 Oid receiveProcedure;
00687 Oid sendProcedure;
00688 Oid analyzeProcedure;
00689 bool byValue;
00690 char category;
00691 char delimiter;
00692 char alignment;
00693 char storage;
00694 char typtype;
00695 Datum datum;
00696 bool isnull;
00697 char *defaultValue = NULL;
00698 char *defaultValueBin = NULL;
00699 bool saw_default = false;
00700 bool typNotNull = false;
00701 bool nullDefined = false;
00702 int32 typNDims = list_length(stmt->typeName->arrayBounds);
00703 HeapTuple typeTup;
00704 List *schema = stmt->constraints;
00705 ListCell *listptr;
00706 Oid basetypeoid;
00707 Oid domainoid;
00708 Oid old_type_oid;
00709 Oid domaincoll;
00710 Form_pg_type baseType;
00711 int32 basetypeMod;
00712 Oid baseColl;
00713
00714
00715 domainNamespace = QualifiedNameGetCreationNamespace(stmt->domainname,
00716 &domainName);
00717
00718
00719 aclresult = pg_namespace_aclcheck(domainNamespace, GetUserId(),
00720 ACL_CREATE);
00721 if (aclresult != ACLCHECK_OK)
00722 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
00723 get_namespace_name(domainNamespace));
00724
00725
00726
00727
00728
00729 old_type_oid = GetSysCacheOid2(TYPENAMENSP,
00730 CStringGetDatum(domainName),
00731 ObjectIdGetDatum(domainNamespace));
00732 if (OidIsValid(old_type_oid))
00733 {
00734 if (!moveArrayTypeName(old_type_oid, domainName, domainNamespace))
00735 ereport(ERROR,
00736 (errcode(ERRCODE_DUPLICATE_OBJECT),
00737 errmsg("type \"%s\" already exists", domainName)));
00738 }
00739
00740
00741
00742
00743 typeTup = typenameType(NULL, stmt->typeName, &basetypeMod);
00744 baseType = (Form_pg_type) GETSTRUCT(typeTup);
00745 basetypeoid = HeapTupleGetOid(typeTup);
00746
00747
00748
00749
00750
00751
00752
00753 typtype = baseType->typtype;
00754 if (typtype != TYPTYPE_BASE &&
00755 typtype != TYPTYPE_DOMAIN &&
00756 typtype != TYPTYPE_ENUM &&
00757 typtype != TYPTYPE_RANGE)
00758 ereport(ERROR,
00759 (errcode(ERRCODE_DATATYPE_MISMATCH),
00760 errmsg("\"%s\" is not a valid base type for a domain",
00761 TypeNameToString(stmt->typeName))));
00762
00763 aclresult = pg_type_aclcheck(basetypeoid, GetUserId(), ACL_USAGE);
00764 if (aclresult != ACLCHECK_OK)
00765 aclcheck_error_type(aclresult, basetypeoid);
00766
00767
00768
00769
00770 baseColl = baseType->typcollation;
00771 if (stmt->collClause)
00772 domaincoll = get_collation_oid(stmt->collClause->collname, false);
00773 else
00774 domaincoll = baseColl;
00775
00776
00777 if (OidIsValid(domaincoll) && !OidIsValid(baseColl))
00778 ereport(ERROR,
00779 (errcode(ERRCODE_DATATYPE_MISMATCH),
00780 errmsg("collations are not supported by type %s",
00781 format_type_be(basetypeoid))));
00782
00783
00784 byValue = baseType->typbyval;
00785
00786
00787 alignment = baseType->typalign;
00788
00789
00790 storage = baseType->typstorage;
00791
00792
00793 internalLength = baseType->typlen;
00794
00795
00796 category = baseType->typcategory;
00797
00798
00799 delimiter = baseType->typdelim;
00800
00801
00802 inputProcedure = F_DOMAIN_IN;
00803 outputProcedure = baseType->typoutput;
00804 receiveProcedure = F_DOMAIN_RECV;
00805 sendProcedure = baseType->typsend;
00806
00807
00808
00809
00810 analyzeProcedure = baseType->typanalyze;
00811
00812
00813 datum = SysCacheGetAttr(TYPEOID, typeTup,
00814 Anum_pg_type_typdefault, &isnull);
00815 if (!isnull)
00816 defaultValue = TextDatumGetCString(datum);
00817
00818
00819 datum = SysCacheGetAttr(TYPEOID, typeTup,
00820 Anum_pg_type_typdefaultbin, &isnull);
00821 if (!isnull)
00822 defaultValueBin = TextDatumGetCString(datum);
00823
00824
00825
00826
00827
00828 foreach(listptr, schema)
00829 {
00830 Constraint *constr = lfirst(listptr);
00831
00832 if (!IsA(constr, Constraint))
00833 elog(ERROR, "unrecognized node type: %d",
00834 (int) nodeTag(constr));
00835 switch (constr->contype)
00836 {
00837 case CONSTR_DEFAULT:
00838
00839
00840
00841
00842
00843 if (saw_default)
00844 ereport(ERROR,
00845 (errcode(ERRCODE_SYNTAX_ERROR),
00846 errmsg("multiple default expressions")));
00847 saw_default = true;
00848
00849 if (constr->raw_expr)
00850 {
00851 ParseState *pstate;
00852 Node *defaultExpr;
00853
00854
00855 pstate = make_parsestate(NULL);
00856
00857
00858
00859
00860
00861 defaultExpr = cookDefault(pstate, constr->raw_expr,
00862 basetypeoid,
00863 basetypeMod,
00864 domainName);
00865
00866
00867
00868
00869
00870
00871
00872
00873
00874
00875
00876 if (defaultExpr == NULL ||
00877 (IsA(defaultExpr, Const) &&
00878 ((Const *) defaultExpr)->constisnull))
00879 {
00880 defaultValue = NULL;
00881 defaultValueBin = NULL;
00882 }
00883 else
00884 {
00885
00886
00887
00888
00889
00890 defaultValue =
00891 deparse_expression(defaultExpr,
00892 NIL, false, false);
00893 defaultValueBin = nodeToString(defaultExpr);
00894 }
00895 }
00896 else
00897 {
00898
00899 defaultValue = NULL;
00900 defaultValueBin = NULL;
00901 }
00902 break;
00903
00904 case CONSTR_NOTNULL:
00905 if (nullDefined && !typNotNull)
00906 ereport(ERROR,
00907 (errcode(ERRCODE_SYNTAX_ERROR),
00908 errmsg("conflicting NULL/NOT NULL constraints")));
00909 typNotNull = true;
00910 nullDefined = true;
00911 break;
00912
00913 case CONSTR_NULL:
00914 if (nullDefined && typNotNull)
00915 ereport(ERROR,
00916 (errcode(ERRCODE_SYNTAX_ERROR),
00917 errmsg("conflicting NULL/NOT NULL constraints")));
00918 typNotNull = false;
00919 nullDefined = true;
00920 break;
00921
00922 case CONSTR_CHECK:
00923
00924
00925
00926
00927
00928
00929
00930 if (constr->is_no_inherit)
00931 ereport(ERROR,
00932 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
00933 errmsg("check constraints for domains cannot be marked NO INHERIT")));
00934 break;
00935
00936
00937
00938
00939 case CONSTR_UNIQUE:
00940 ereport(ERROR,
00941 (errcode(ERRCODE_SYNTAX_ERROR),
00942 errmsg("unique constraints not possible for domains")));
00943 break;
00944
00945 case CONSTR_PRIMARY:
00946 ereport(ERROR,
00947 (errcode(ERRCODE_SYNTAX_ERROR),
00948 errmsg("primary key constraints not possible for domains")));
00949 break;
00950
00951 case CONSTR_EXCLUSION:
00952 ereport(ERROR,
00953 (errcode(ERRCODE_SYNTAX_ERROR),
00954 errmsg("exclusion constraints not possible for domains")));
00955 break;
00956
00957 case CONSTR_FOREIGN:
00958 ereport(ERROR,
00959 (errcode(ERRCODE_SYNTAX_ERROR),
00960 errmsg("foreign key constraints not possible for domains")));
00961 break;
00962
00963 case CONSTR_ATTR_DEFERRABLE:
00964 case CONSTR_ATTR_NOT_DEFERRABLE:
00965 case CONSTR_ATTR_DEFERRED:
00966 case CONSTR_ATTR_IMMEDIATE:
00967 ereport(ERROR,
00968 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
00969 errmsg("specifying constraint deferrability not supported for domains")));
00970 break;
00971
00972 default:
00973 elog(ERROR, "unrecognized constraint subtype: %d",
00974 (int) constr->contype);
00975 break;
00976 }
00977 }
00978
00979
00980
00981
00982 domainoid =
00983 TypeCreate(InvalidOid,
00984 domainName,
00985 domainNamespace,
00986 InvalidOid,
00987 0,
00988 GetUserId(),
00989 internalLength,
00990 TYPTYPE_DOMAIN,
00991 category,
00992 false,
00993 delimiter,
00994 inputProcedure,
00995 outputProcedure,
00996 receiveProcedure,
00997 sendProcedure,
00998 InvalidOid,
00999 InvalidOid,
01000 analyzeProcedure,
01001 InvalidOid,
01002 false,
01003 InvalidOid,
01004 basetypeoid,
01005 defaultValue,
01006 defaultValueBin,
01007 byValue,
01008 alignment,
01009 storage,
01010 basetypeMod,
01011 typNDims,
01012 typNotNull,
01013 domaincoll);
01014
01015
01016
01017
01018 foreach(listptr, schema)
01019 {
01020 Constraint *constr = lfirst(listptr);
01021
01022
01023
01024 switch (constr->contype)
01025 {
01026 case CONSTR_CHECK:
01027 domainAddConstraint(domainoid, domainNamespace,
01028 basetypeoid, basetypeMod,
01029 constr, domainName);
01030 break;
01031
01032
01033
01034 default:
01035 break;
01036 }
01037
01038
01039 CommandCounterIncrement();
01040 }
01041
01042
01043
01044
01045 ReleaseSysCache(typeTup);
01046
01047 return domainoid;
01048 }
01049
01050
01051
01052
01053
01054
01055 Oid
01056 DefineEnum(CreateEnumStmt *stmt)
01057 {
01058 char *enumName;
01059 char *enumArrayName;
01060 Oid enumNamespace;
01061 Oid enumTypeOid;
01062 AclResult aclresult;
01063 Oid old_type_oid;
01064 Oid enumArrayOid;
01065
01066
01067 enumNamespace = QualifiedNameGetCreationNamespace(stmt->typeName,
01068 &enumName);
01069
01070
01071 aclresult = pg_namespace_aclcheck(enumNamespace, GetUserId(), ACL_CREATE);
01072 if (aclresult != ACLCHECK_OK)
01073 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
01074 get_namespace_name(enumNamespace));
01075
01076
01077
01078
01079
01080 old_type_oid = GetSysCacheOid2(TYPENAMENSP,
01081 CStringGetDatum(enumName),
01082 ObjectIdGetDatum(enumNamespace));
01083 if (OidIsValid(old_type_oid))
01084 {
01085 if (!moveArrayTypeName(old_type_oid, enumName, enumNamespace))
01086 ereport(ERROR,
01087 (errcode(ERRCODE_DUPLICATE_OBJECT),
01088 errmsg("type \"%s\" already exists", enumName)));
01089 }
01090
01091 enumArrayOid = AssignTypeArrayOid();
01092
01093
01094 enumTypeOid =
01095 TypeCreate(InvalidOid,
01096 enumName,
01097 enumNamespace,
01098 InvalidOid,
01099 0,
01100 GetUserId(),
01101 sizeof(Oid),
01102 TYPTYPE_ENUM,
01103 TYPCATEGORY_ENUM,
01104 false,
01105 DEFAULT_TYPDELIM,
01106 F_ENUM_IN,
01107 F_ENUM_OUT,
01108 F_ENUM_RECV,
01109 F_ENUM_SEND,
01110 InvalidOid,
01111 InvalidOid,
01112 InvalidOid,
01113 InvalidOid,
01114 false,
01115 enumArrayOid,
01116 InvalidOid,
01117 NULL,
01118 NULL,
01119 true,
01120 'i',
01121 'p',
01122 -1,
01123 0,
01124 false,
01125 InvalidOid);
01126
01127
01128 EnumValuesCreate(enumTypeOid, stmt->vals);
01129
01130
01131
01132
01133 enumArrayName = makeArrayTypeName(enumName, enumNamespace);
01134
01135 TypeCreate(enumArrayOid,
01136 enumArrayName,
01137 enumNamespace,
01138 InvalidOid,
01139 0,
01140 GetUserId(),
01141 -1,
01142 TYPTYPE_BASE,
01143 TYPCATEGORY_ARRAY,
01144 false,
01145 DEFAULT_TYPDELIM,
01146 F_ARRAY_IN,
01147 F_ARRAY_OUT,
01148 F_ARRAY_RECV,
01149 F_ARRAY_SEND,
01150 InvalidOid,
01151 InvalidOid,
01152 F_ARRAY_TYPANALYZE,
01153 enumTypeOid,
01154 true,
01155 InvalidOid,
01156 InvalidOid,
01157 NULL,
01158 NULL,
01159 false,
01160 'i',
01161 'x',
01162 -1,
01163 0,
01164 false,
01165 InvalidOid);
01166
01167 pfree(enumArrayName);
01168
01169 return enumTypeOid;
01170 }
01171
01172
01173
01174
01175
01176 Oid
01177 AlterEnum(AlterEnumStmt *stmt, bool isTopLevel)
01178 {
01179 Oid enum_type_oid;
01180 TypeName *typename;
01181 HeapTuple tup;
01182
01183
01184 typename = makeTypeNameFromNameList(stmt->typeName);
01185 enum_type_oid = typenameTypeId(NULL, typename);
01186
01187 tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(enum_type_oid));
01188 if (!HeapTupleIsValid(tup))
01189 elog(ERROR, "cache lookup failed for type %u", enum_type_oid);
01190
01191
01192
01193
01194
01195
01196
01197
01198
01199
01200
01201
01202
01203
01204 if (HeapTupleHeaderGetXmin(tup->t_data) == GetCurrentTransactionId() &&
01205 !(tup->t_data->t_infomask & HEAP_UPDATED))
01206 ;
01207 else
01208 PreventTransactionChain(isTopLevel, "ALTER TYPE ... ADD");
01209
01210
01211 checkEnumOwner(tup);
01212
01213
01214 AddEnumLabel(enum_type_oid, stmt->newVal,
01215 stmt->newValNeighbor, stmt->newValIsAfter,
01216 stmt->skipIfExists);
01217
01218 InvokeObjectPostAlterHook(TypeRelationId, enum_type_oid, 0);
01219
01220 ReleaseSysCache(tup);
01221
01222 return enum_type_oid;
01223 }
01224
01225
01226
01227
01228
01229
01230
01231
01232 static void
01233 checkEnumOwner(HeapTuple tup)
01234 {
01235 Form_pg_type typTup = (Form_pg_type) GETSTRUCT(tup);
01236
01237
01238 if (typTup->typtype != TYPTYPE_ENUM)
01239 ereport(ERROR,
01240 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
01241 errmsg("%s is not an enum",
01242 format_type_be(HeapTupleGetOid(tup)))));
01243
01244
01245 if (!pg_type_ownercheck(HeapTupleGetOid(tup), GetUserId()))
01246 aclcheck_error_type(ACLCHECK_NOT_OWNER, HeapTupleGetOid(tup));
01247 }
01248
01249
01250
01251
01252
01253
01254 Oid
01255 DefineRange(CreateRangeStmt *stmt)
01256 {
01257 char *typeName;
01258 Oid typeNamespace;
01259 Oid typoid;
01260 char *rangeArrayName;
01261 Oid rangeArrayOid;
01262 Oid rangeSubtype = InvalidOid;
01263 List *rangeSubOpclassName = NIL;
01264 List *rangeCollationName = NIL;
01265 List *rangeCanonicalName = NIL;
01266 List *rangeSubtypeDiffName = NIL;
01267 Oid rangeSubOpclass;
01268 Oid rangeCollation;
01269 regproc rangeCanonical;
01270 regproc rangeSubtypeDiff;
01271 int16 subtyplen;
01272 bool subtypbyval;
01273 char subtypalign;
01274 char alignment;
01275 AclResult aclresult;
01276 ListCell *lc;
01277
01278
01279 typeNamespace = QualifiedNameGetCreationNamespace(stmt->typeName,
01280 &typeName);
01281
01282
01283 aclresult = pg_namespace_aclcheck(typeNamespace, GetUserId(), ACL_CREATE);
01284 if (aclresult != ACLCHECK_OK)
01285 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
01286 get_namespace_name(typeNamespace));
01287
01288
01289
01290
01291 typoid = GetSysCacheOid2(TYPENAMENSP,
01292 CStringGetDatum(typeName),
01293 ObjectIdGetDatum(typeNamespace));
01294
01295
01296
01297
01298
01299 if (OidIsValid(typoid) && get_typisdefined(typoid))
01300 {
01301 if (moveArrayTypeName(typoid, typeName, typeNamespace))
01302 typoid = InvalidOid;
01303 else
01304 ereport(ERROR,
01305 (errcode(ERRCODE_DUPLICATE_OBJECT),
01306 errmsg("type \"%s\" already exists", typeName)));
01307 }
01308
01309
01310
01311
01312
01313 if (!OidIsValid(typoid))
01314 {
01315 typoid = TypeShellMake(typeName, typeNamespace, GetUserId());
01316
01317 CommandCounterIncrement();
01318 }
01319
01320
01321 foreach(lc, stmt->params)
01322 {
01323 DefElem *defel = (DefElem *) lfirst(lc);
01324
01325 if (pg_strcasecmp(defel->defname, "subtype") == 0)
01326 {
01327 if (OidIsValid(rangeSubtype))
01328 ereport(ERROR,
01329 (errcode(ERRCODE_SYNTAX_ERROR),
01330 errmsg("conflicting or redundant options")));
01331
01332 rangeSubtype = typenameTypeId(NULL, defGetTypeName(defel));
01333 }
01334 else if (pg_strcasecmp(defel->defname, "subtype_opclass") == 0)
01335 {
01336 if (rangeSubOpclassName != NIL)
01337 ereport(ERROR,
01338 (errcode(ERRCODE_SYNTAX_ERROR),
01339 errmsg("conflicting or redundant options")));
01340 rangeSubOpclassName = defGetQualifiedName(defel);
01341 }
01342 else if (pg_strcasecmp(defel->defname, "collation") == 0)
01343 {
01344 if (rangeCollationName != NIL)
01345 ereport(ERROR,
01346 (errcode(ERRCODE_SYNTAX_ERROR),
01347 errmsg("conflicting or redundant options")));
01348 rangeCollationName = defGetQualifiedName(defel);
01349 }
01350 else if (pg_strcasecmp(defel->defname, "canonical") == 0)
01351 {
01352 if (rangeCanonicalName != NIL)
01353 ereport(ERROR,
01354 (errcode(ERRCODE_SYNTAX_ERROR),
01355 errmsg("conflicting or redundant options")));
01356 rangeCanonicalName = defGetQualifiedName(defel);
01357 }
01358 else if (pg_strcasecmp(defel->defname, "subtype_diff") == 0)
01359 {
01360 if (rangeSubtypeDiffName != NIL)
01361 ereport(ERROR,
01362 (errcode(ERRCODE_SYNTAX_ERROR),
01363 errmsg("conflicting or redundant options")));
01364 rangeSubtypeDiffName = defGetQualifiedName(defel);
01365 }
01366 else
01367 ereport(ERROR,
01368 (errcode(ERRCODE_SYNTAX_ERROR),
01369 errmsg("type attribute \"%s\" not recognized",
01370 defel->defname)));
01371 }
01372
01373
01374 if (!OidIsValid(rangeSubtype))
01375 ereport(ERROR,
01376 (errcode(ERRCODE_SYNTAX_ERROR),
01377 errmsg("type attribute \"subtype\" is required")));
01378
01379 if (get_typtype(rangeSubtype) == TYPTYPE_PSEUDO)
01380 ereport(ERROR,
01381 (errcode(ERRCODE_DATATYPE_MISMATCH),
01382 errmsg("range subtype cannot be %s",
01383 format_type_be(rangeSubtype))));
01384
01385
01386 rangeSubOpclass = findRangeSubOpclass(rangeSubOpclassName, rangeSubtype);
01387
01388
01389 if (type_is_collatable(rangeSubtype))
01390 {
01391 if (rangeCollationName != NIL)
01392 rangeCollation = get_collation_oid(rangeCollationName, false);
01393 else
01394 rangeCollation = get_typcollation(rangeSubtype);
01395 }
01396 else
01397 {
01398 if (rangeCollationName != NIL)
01399 ereport(ERROR,
01400 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
01401 errmsg("range collation specified but subtype does not support collation")));
01402 rangeCollation = InvalidOid;
01403 }
01404
01405
01406 if (rangeCanonicalName != NIL)
01407 rangeCanonical = findRangeCanonicalFunction(rangeCanonicalName,
01408 typoid);
01409 else
01410 rangeCanonical = InvalidOid;
01411
01412 if (rangeSubtypeDiffName != NIL)
01413 rangeSubtypeDiff = findRangeSubtypeDiffFunction(rangeSubtypeDiffName,
01414 rangeSubtype);
01415 else
01416 rangeSubtypeDiff = InvalidOid;
01417
01418 get_typlenbyvalalign(rangeSubtype,
01419 &subtyplen, &subtypbyval, &subtypalign);
01420
01421
01422 alignment = (subtypalign == 'd') ? 'd' : 'i';
01423
01424
01425 rangeArrayOid = AssignTypeArrayOid();
01426
01427
01428 typoid =
01429 TypeCreate(InvalidOid,
01430 typeName,
01431 typeNamespace,
01432 InvalidOid,
01433 0,
01434 GetUserId(),
01435 -1,
01436 TYPTYPE_RANGE,
01437 TYPCATEGORY_RANGE,
01438 false,
01439 DEFAULT_TYPDELIM,
01440 F_RANGE_IN,
01441 F_RANGE_OUT,
01442 F_RANGE_RECV,
01443 F_RANGE_SEND,
01444 InvalidOid,
01445 InvalidOid,
01446 F_RANGE_TYPANALYZE,
01447 InvalidOid,
01448 false,
01449 rangeArrayOid,
01450 InvalidOid,
01451 NULL,
01452 NULL,
01453 false,
01454 alignment,
01455 'x',
01456 -1,
01457 0,
01458 false,
01459 InvalidOid);
01460
01461
01462 RangeCreate(typoid, rangeSubtype, rangeCollation, rangeSubOpclass,
01463 rangeCanonical, rangeSubtypeDiff);
01464
01465
01466
01467
01468 rangeArrayName = makeArrayTypeName(typeName, typeNamespace);
01469
01470 TypeCreate(rangeArrayOid,
01471 rangeArrayName,
01472 typeNamespace,
01473 InvalidOid,
01474 0,
01475 GetUserId(),
01476 -1,
01477 TYPTYPE_BASE,
01478 TYPCATEGORY_ARRAY,
01479 false,
01480 DEFAULT_TYPDELIM,
01481 F_ARRAY_IN,
01482 F_ARRAY_OUT,
01483 F_ARRAY_RECV,
01484 F_ARRAY_SEND,
01485 InvalidOid,
01486 InvalidOid,
01487 F_ARRAY_TYPANALYZE,
01488 typoid,
01489 true,
01490 InvalidOid,
01491 InvalidOid,
01492 NULL,
01493 NULL,
01494 false,
01495 alignment,
01496 'x',
01497 -1,
01498 0,
01499 false,
01500 InvalidOid);
01501
01502 pfree(rangeArrayName);
01503
01504
01505 makeRangeConstructors(typeName, typeNamespace, typoid, rangeSubtype);
01506
01507 return typoid;
01508 }
01509
01510
01511
01512
01513
01514
01515
01516
01517
01518
01519 static void
01520 makeRangeConstructors(const char *name, Oid namespace,
01521 Oid rangeOid, Oid subtype)
01522 {
01523 static const char *const prosrc[2] = {"range_constructor2",
01524 "range_constructor3"};
01525 static const int pronargs[2] = {2, 3};
01526
01527 Oid constructorArgTypes[3];
01528 ObjectAddress myself,
01529 referenced;
01530 int i;
01531
01532 constructorArgTypes[0] = subtype;
01533 constructorArgTypes[1] = subtype;
01534 constructorArgTypes[2] = TEXTOID;
01535
01536 referenced.classId = TypeRelationId;
01537 referenced.objectId = rangeOid;
01538 referenced.objectSubId = 0;
01539
01540 for (i = 0; i < lengthof(prosrc); i++)
01541 {
01542 oidvector *constructorArgTypesVector;
01543 Oid procOid;
01544
01545 constructorArgTypesVector = buildoidvector(constructorArgTypes,
01546 pronargs[i]);
01547
01548 procOid = ProcedureCreate(name,
01549 namespace,
01550 false,
01551 false,
01552 rangeOid,
01553 BOOTSTRAP_SUPERUSERID,
01554 INTERNALlanguageId,
01555 F_FMGR_INTERNAL_VALIDATOR,
01556 prosrc[i],
01557 NULL,
01558 false,
01559 false,
01560 false,
01561 false,
01562 false,
01563 PROVOLATILE_IMMUTABLE,
01564 constructorArgTypesVector,
01565 PointerGetDatum(NULL),
01566 PointerGetDatum(NULL),
01567 PointerGetDatum(NULL),
01568 NIL,
01569 PointerGetDatum(NULL),
01570 1.0,
01571 0.0);
01572
01573
01574
01575
01576
01577
01578 myself.classId = ProcedureRelationId;
01579 myself.objectId = procOid;
01580 myself.objectSubId = 0;
01581
01582 recordDependencyOn(&myself, &referenced, DEPENDENCY_INTERNAL);
01583 }
01584 }
01585
01586
01587
01588
01589
01590
01591
01592
01593
01594 static Oid
01595 findTypeInputFunction(List *procname, Oid typeOid)
01596 {
01597 Oid argList[3];
01598 Oid procOid;
01599
01600
01601
01602
01603
01604
01605
01606
01607 argList[0] = CSTRINGOID;
01608
01609 procOid = LookupFuncName(procname, 1, argList, true);
01610 if (OidIsValid(procOid))
01611 return procOid;
01612
01613 argList[1] = OIDOID;
01614 argList[2] = INT4OID;
01615
01616 procOid = LookupFuncName(procname, 3, argList, true);
01617 if (OidIsValid(procOid))
01618 return procOid;
01619
01620
01621 argList[0] = OPAQUEOID;
01622
01623 procOid = LookupFuncName(procname, 1, argList, true);
01624
01625 if (!OidIsValid(procOid))
01626 {
01627 argList[1] = OIDOID;
01628 argList[2] = INT4OID;
01629
01630 procOid = LookupFuncName(procname, 3, argList, true);
01631 }
01632
01633 if (OidIsValid(procOid))
01634 {
01635
01636 ereport(WARNING,
01637 (errmsg("changing argument type of function %s from \"opaque\" to \"cstring\"",
01638 NameListToString(procname))));
01639 SetFunctionArgType(procOid, 0, CSTRINGOID);
01640
01641
01642
01643
01644
01645 CommandCounterIncrement();
01646
01647 return procOid;
01648 }
01649
01650
01651 argList[0] = CSTRINGOID;
01652
01653 ereport(ERROR,
01654 (errcode(ERRCODE_UNDEFINED_FUNCTION),
01655 errmsg("function %s does not exist",
01656 func_signature_string(procname, 1, NIL, argList))));
01657
01658 return InvalidOid;
01659 }
01660
01661 static Oid
01662 findTypeOutputFunction(List *procname, Oid typeOid)
01663 {
01664 Oid argList[1];
01665 Oid procOid;
01666
01667
01668
01669
01670
01671
01672
01673 argList[0] = typeOid;
01674
01675 procOid = LookupFuncName(procname, 1, argList, true);
01676 if (OidIsValid(procOid))
01677 return procOid;
01678
01679
01680 argList[0] = OPAQUEOID;
01681
01682 procOid = LookupFuncName(procname, 1, argList, true);
01683
01684 if (OidIsValid(procOid))
01685 {
01686
01687 ereport(WARNING,
01688 (errmsg("changing argument type of function %s from \"opaque\" to %s",
01689 NameListToString(procname), format_type_be(typeOid))));
01690 SetFunctionArgType(procOid, 0, typeOid);
01691
01692
01693
01694
01695
01696 CommandCounterIncrement();
01697
01698 return procOid;
01699 }
01700
01701
01702 argList[0] = typeOid;
01703
01704 ereport(ERROR,
01705 (errcode(ERRCODE_UNDEFINED_FUNCTION),
01706 errmsg("function %s does not exist",
01707 func_signature_string(procname, 1, NIL, argList))));
01708
01709 return InvalidOid;
01710 }
01711
01712 static Oid
01713 findTypeReceiveFunction(List *procname, Oid typeOid)
01714 {
01715 Oid argList[3];
01716 Oid procOid;
01717
01718
01719
01720
01721
01722 argList[0] = INTERNALOID;
01723
01724 procOid = LookupFuncName(procname, 1, argList, true);
01725 if (OidIsValid(procOid))
01726 return procOid;
01727
01728 argList[1] = OIDOID;
01729 argList[2] = INT4OID;
01730
01731 procOid = LookupFuncName(procname, 3, argList, true);
01732 if (OidIsValid(procOid))
01733 return procOid;
01734
01735 ereport(ERROR,
01736 (errcode(ERRCODE_UNDEFINED_FUNCTION),
01737 errmsg("function %s does not exist",
01738 func_signature_string(procname, 1, NIL, argList))));
01739
01740 return InvalidOid;
01741 }
01742
01743 static Oid
01744 findTypeSendFunction(List *procname, Oid typeOid)
01745 {
01746 Oid argList[1];
01747 Oid procOid;
01748
01749
01750
01751
01752 argList[0] = typeOid;
01753
01754 procOid = LookupFuncName(procname, 1, argList, true);
01755 if (OidIsValid(procOid))
01756 return procOid;
01757
01758 ereport(ERROR,
01759 (errcode(ERRCODE_UNDEFINED_FUNCTION),
01760 errmsg("function %s does not exist",
01761 func_signature_string(procname, 1, NIL, argList))));
01762
01763 return InvalidOid;
01764 }
01765
01766 static Oid
01767 findTypeTypmodinFunction(List *procname)
01768 {
01769 Oid argList[1];
01770 Oid procOid;
01771
01772
01773
01774
01775 argList[0] = CSTRINGARRAYOID;
01776
01777 procOid = LookupFuncName(procname, 1, argList, true);
01778 if (!OidIsValid(procOid))
01779 ereport(ERROR,
01780 (errcode(ERRCODE_UNDEFINED_FUNCTION),
01781 errmsg("function %s does not exist",
01782 func_signature_string(procname, 1, NIL, argList))));
01783
01784 if (get_func_rettype(procOid) != INT4OID)
01785 ereport(ERROR,
01786 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
01787 errmsg("typmod_in function %s must return type \"integer\"",
01788 NameListToString(procname))));
01789
01790 return procOid;
01791 }
01792
01793 static Oid
01794 findTypeTypmodoutFunction(List *procname)
01795 {
01796 Oid argList[1];
01797 Oid procOid;
01798
01799
01800
01801
01802 argList[0] = INT4OID;
01803
01804 procOid = LookupFuncName(procname, 1, argList, true);
01805 if (!OidIsValid(procOid))
01806 ereport(ERROR,
01807 (errcode(ERRCODE_UNDEFINED_FUNCTION),
01808 errmsg("function %s does not exist",
01809 func_signature_string(procname, 1, NIL, argList))));
01810
01811 if (get_func_rettype(procOid) != CSTRINGOID)
01812 ereport(ERROR,
01813 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
01814 errmsg("typmod_out function %s must return type \"cstring\"",
01815 NameListToString(procname))));
01816
01817 return procOid;
01818 }
01819
01820 static Oid
01821 findTypeAnalyzeFunction(List *procname, Oid typeOid)
01822 {
01823 Oid argList[1];
01824 Oid procOid;
01825
01826
01827
01828
01829 argList[0] = INTERNALOID;
01830
01831 procOid = LookupFuncName(procname, 1, argList, true);
01832 if (!OidIsValid(procOid))
01833 ereport(ERROR,
01834 (errcode(ERRCODE_UNDEFINED_FUNCTION),
01835 errmsg("function %s does not exist",
01836 func_signature_string(procname, 1, NIL, argList))));
01837
01838 if (get_func_rettype(procOid) != BOOLOID)
01839 ereport(ERROR,
01840 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
01841 errmsg("type analyze function %s must return type \"boolean\"",
01842 NameListToString(procname))));
01843
01844 return procOid;
01845 }
01846
01847
01848
01849
01850
01851
01852
01853
01854
01855 static Oid
01856 findRangeSubOpclass(List *opcname, Oid subtype)
01857 {
01858 Oid opcid;
01859 Oid opInputType;
01860
01861 if (opcname != NIL)
01862 {
01863 opcid = get_opclass_oid(BTREE_AM_OID, opcname, false);
01864
01865
01866
01867
01868
01869 opInputType = get_opclass_input_type(opcid);
01870 if (!IsBinaryCoercible(subtype, opInputType))
01871 ereport(ERROR,
01872 (errcode(ERRCODE_DATATYPE_MISMATCH),
01873 errmsg("operator class \"%s\" does not accept data type %s",
01874 NameListToString(opcname),
01875 format_type_be(subtype))));
01876 }
01877 else
01878 {
01879 opcid = GetDefaultOpClass(subtype, BTREE_AM_OID);
01880 if (!OidIsValid(opcid))
01881 {
01882
01883 ereport(ERROR,
01884 (errcode(ERRCODE_UNDEFINED_OBJECT),
01885 errmsg("data type %s has no default operator class for access method \"%s\"",
01886 format_type_be(subtype), "btree"),
01887 errhint("You must specify an operator class for the range type or define a default operator class for the subtype.")));
01888 }
01889 }
01890
01891 return opcid;
01892 }
01893
01894 static Oid
01895 findRangeCanonicalFunction(List *procname, Oid typeOid)
01896 {
01897 Oid argList[1];
01898 Oid procOid;
01899 AclResult aclresult;
01900
01901
01902
01903
01904
01905 argList[0] = typeOid;
01906
01907 procOid = LookupFuncName(procname, 1, argList, true);
01908
01909 if (!OidIsValid(procOid))
01910 ereport(ERROR,
01911 (errcode(ERRCODE_UNDEFINED_FUNCTION),
01912 errmsg("function %s does not exist",
01913 func_signature_string(procname, 1, NIL, argList))));
01914
01915 if (get_func_rettype(procOid) != typeOid)
01916 ereport(ERROR,
01917 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
01918 errmsg("range canonical function %s must return range type",
01919 func_signature_string(procname, 1, NIL, argList))));
01920
01921 if (func_volatile(procOid) != PROVOLATILE_IMMUTABLE)
01922 ereport(ERROR,
01923 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
01924 errmsg("range canonical function %s must be immutable",
01925 func_signature_string(procname, 1, NIL, argList))));
01926
01927
01928 aclresult = pg_proc_aclcheck(procOid, GetUserId(), ACL_EXECUTE);
01929 if (aclresult != ACLCHECK_OK)
01930 aclcheck_error(aclresult, ACL_KIND_PROC, get_func_name(procOid));
01931
01932 return procOid;
01933 }
01934
01935 static Oid
01936 findRangeSubtypeDiffFunction(List *procname, Oid subtype)
01937 {
01938 Oid argList[2];
01939 Oid procOid;
01940 AclResult aclresult;
01941
01942
01943
01944
01945
01946 argList[0] = subtype;
01947 argList[1] = subtype;
01948
01949 procOid = LookupFuncName(procname, 2, argList, true);
01950
01951 if (!OidIsValid(procOid))
01952 ereport(ERROR,
01953 (errcode(ERRCODE_UNDEFINED_FUNCTION),
01954 errmsg("function %s does not exist",
01955 func_signature_string(procname, 2, NIL, argList))));
01956
01957 if (get_func_rettype(procOid) != FLOAT8OID)
01958 ereport(ERROR,
01959 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
01960 errmsg("range subtype diff function %s must return type double precision",
01961 func_signature_string(procname, 2, NIL, argList))));
01962
01963 if (func_volatile(procOid) != PROVOLATILE_IMMUTABLE)
01964 ereport(ERROR,
01965 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
01966 errmsg("range subtype diff function %s must be immutable",
01967 func_signature_string(procname, 2, NIL, argList))));
01968
01969
01970 aclresult = pg_proc_aclcheck(procOid, GetUserId(), ACL_EXECUTE);
01971 if (aclresult != ACLCHECK_OK)
01972 aclcheck_error(aclresult, ACL_KIND_PROC, get_func_name(procOid));
01973
01974 return procOid;
01975 }
01976
01977
01978
01979
01980
01981
01982 Oid
01983 AssignTypeArrayOid(void)
01984 {
01985 Oid type_array_oid;
01986
01987
01988 if (IsBinaryUpgrade && OidIsValid(binary_upgrade_next_array_pg_type_oid))
01989 {
01990 type_array_oid = binary_upgrade_next_array_pg_type_oid;
01991 binary_upgrade_next_array_pg_type_oid = InvalidOid;
01992 }
01993 else
01994 {
01995 Relation pg_type = heap_open(TypeRelationId, AccessShareLock);
01996
01997 type_array_oid = GetNewOid(pg_type);
01998 heap_close(pg_type, AccessShareLock);
01999 }
02000
02001 return type_array_oid;
02002 }
02003
02004
02005
02006
02007
02008
02009
02010
02011
02012
02013
02014
02015
02016
02017
02018
02019 Oid
02020 DefineCompositeType(RangeVar *typevar, List *coldeflist)
02021 {
02022 CreateStmt *createStmt = makeNode(CreateStmt);
02023 Oid old_type_oid;
02024 Oid typeNamespace;
02025 Oid relid;
02026
02027
02028
02029
02030
02031 createStmt->relation = typevar;
02032 createStmt->tableElts = coldeflist;
02033 createStmt->inhRelations = NIL;
02034 createStmt->constraints = NIL;
02035 createStmt->options = NIL;
02036 createStmt->oncommit = ONCOMMIT_NOOP;
02037 createStmt->tablespacename = NULL;
02038 createStmt->if_not_exists = false;
02039
02040
02041
02042
02043
02044
02045
02046 typeNamespace = RangeVarGetAndCheckCreationNamespace(createStmt->relation,
02047 NoLock, NULL);
02048 RangeVarAdjustRelationPersistence(createStmt->relation, typeNamespace);
02049 old_type_oid =
02050 GetSysCacheOid2(TYPENAMENSP,
02051 CStringGetDatum(createStmt->relation->relname),
02052 ObjectIdGetDatum(typeNamespace));
02053 if (OidIsValid(old_type_oid))
02054 {
02055 if (!moveArrayTypeName(old_type_oid, createStmt->relation->relname, typeNamespace))
02056 ereport(ERROR,
02057 (errcode(ERRCODE_DUPLICATE_OBJECT),
02058 errmsg("type \"%s\" already exists", createStmt->relation->relname)));
02059 }
02060
02061
02062
02063
02064 relid = DefineRelation(createStmt, RELKIND_COMPOSITE_TYPE, InvalidOid);
02065 Assert(relid != InvalidOid);
02066 return relid;
02067 }
02068
02069
02070
02071
02072
02073
02074 Oid
02075 AlterDomainDefault(List *names, Node *defaultRaw)
02076 {
02077 TypeName *typename;
02078 Oid domainoid;
02079 HeapTuple tup;
02080 ParseState *pstate;
02081 Relation rel;
02082 char *defaultValue;
02083 Node *defaultExpr = NULL;
02084 Datum new_record[Natts_pg_type];
02085 bool new_record_nulls[Natts_pg_type];
02086 bool new_record_repl[Natts_pg_type];
02087 HeapTuple newtuple;
02088 Form_pg_type typTup;
02089
02090
02091 typename = makeTypeNameFromNameList(names);
02092 domainoid = typenameTypeId(NULL, typename);
02093
02094
02095 rel = heap_open(TypeRelationId, RowExclusiveLock);
02096
02097 tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(domainoid));
02098 if (!HeapTupleIsValid(tup))
02099 elog(ERROR, "cache lookup failed for type %u", domainoid);
02100 typTup = (Form_pg_type) GETSTRUCT(tup);
02101
02102
02103 checkDomainOwner(tup);
02104
02105
02106 MemSet(new_record, (Datum) 0, sizeof(new_record));
02107 MemSet(new_record_nulls, false, sizeof(new_record_nulls));
02108 MemSet(new_record_repl, false, sizeof(new_record_repl));
02109
02110
02111 if (defaultRaw)
02112 {
02113
02114 pstate = make_parsestate(NULL);
02115
02116
02117
02118
02119
02120 defaultExpr = cookDefault(pstate, defaultRaw,
02121 typTup->typbasetype,
02122 typTup->typtypmod,
02123 NameStr(typTup->typname));
02124
02125
02126
02127
02128
02129
02130 if (defaultExpr == NULL ||
02131 (IsA(defaultExpr, Const) &&((Const *) defaultExpr)->constisnull))
02132 {
02133
02134 new_record_nulls[Anum_pg_type_typdefaultbin - 1] = true;
02135 new_record_repl[Anum_pg_type_typdefaultbin - 1] = true;
02136 new_record_nulls[Anum_pg_type_typdefault - 1] = true;
02137 new_record_repl[Anum_pg_type_typdefault - 1] = true;
02138 }
02139 else
02140 {
02141
02142
02143
02144
02145
02146 defaultValue = deparse_expression(defaultExpr,
02147 NIL, false, false);
02148
02149
02150
02151
02152 new_record[Anum_pg_type_typdefaultbin - 1] = CStringGetTextDatum(nodeToString(defaultExpr));
02153
02154 new_record_repl[Anum_pg_type_typdefaultbin - 1] = true;
02155 new_record[Anum_pg_type_typdefault - 1] = CStringGetTextDatum(defaultValue);
02156 new_record_repl[Anum_pg_type_typdefault - 1] = true;
02157 }
02158 }
02159 else
02160 {
02161
02162 new_record_nulls[Anum_pg_type_typdefaultbin - 1] = true;
02163 new_record_repl[Anum_pg_type_typdefaultbin - 1] = true;
02164 new_record_nulls[Anum_pg_type_typdefault - 1] = true;
02165 new_record_repl[Anum_pg_type_typdefault - 1] = true;
02166 }
02167
02168 newtuple = heap_modify_tuple(tup, RelationGetDescr(rel),
02169 new_record, new_record_nulls,
02170 new_record_repl);
02171
02172 simple_heap_update(rel, &tup->t_self, newtuple);
02173
02174 CatalogUpdateIndexes(rel, newtuple);
02175
02176
02177 GenerateTypeDependencies(typTup->typnamespace,
02178 domainoid,
02179 InvalidOid,
02180 0,
02181 typTup->typowner,
02182 typTup->typinput,
02183 typTup->typoutput,
02184 typTup->typreceive,
02185 typTup->typsend,
02186 typTup->typmodin,
02187 typTup->typmodout,
02188 typTup->typanalyze,
02189 InvalidOid,
02190 false,
02191 typTup->typbasetype,
02192 typTup->typcollation,
02193 defaultExpr,
02194 true);
02195
02196 InvokeObjectPostAlterHook(TypeRelationId, domainoid, 0);
02197
02198
02199 heap_close(rel, NoLock);
02200 heap_freetuple(newtuple);
02201
02202 return domainoid;
02203 }
02204
02205
02206
02207
02208
02209
02210 Oid
02211 AlterDomainNotNull(List *names, bool notNull)
02212 {
02213 TypeName *typename;
02214 Oid domainoid;
02215 Relation typrel;
02216 HeapTuple tup;
02217 Form_pg_type typTup;
02218
02219
02220 typename = makeTypeNameFromNameList(names);
02221 domainoid = typenameTypeId(NULL, typename);
02222
02223
02224 typrel = heap_open(TypeRelationId, RowExclusiveLock);
02225
02226 tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(domainoid));
02227 if (!HeapTupleIsValid(tup))
02228 elog(ERROR, "cache lookup failed for type %u", domainoid);
02229 typTup = (Form_pg_type) GETSTRUCT(tup);
02230
02231
02232 checkDomainOwner(tup);
02233
02234
02235 if (typTup->typnotnull == notNull)
02236 {
02237 heap_close(typrel, RowExclusiveLock);
02238 return InvalidOid;
02239 }
02240
02241
02242 if (notNull)
02243 {
02244 List *rels;
02245 ListCell *rt;
02246
02247
02248
02249
02250 rels = get_rels_with_domain(domainoid, ShareLock);
02251
02252 foreach(rt, rels)
02253 {
02254 RelToCheck *rtc = (RelToCheck *) lfirst(rt);
02255 Relation testrel = rtc->rel;
02256 TupleDesc tupdesc = RelationGetDescr(testrel);
02257 HeapScanDesc scan;
02258 HeapTuple tuple;
02259
02260
02261 scan = heap_beginscan(testrel, SnapshotNow, 0, NULL);
02262 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
02263 {
02264 int i;
02265
02266
02267 for (i = 0; i < rtc->natts; i++)
02268 {
02269 int attnum = rtc->atts[i];
02270
02271 if (heap_attisnull(tuple, attnum))
02272 {
02273
02274
02275
02276
02277
02278
02279
02280
02281 ereport(ERROR,
02282 (errcode(ERRCODE_NOT_NULL_VIOLATION),
02283 errmsg("column \"%s\" of table \"%s\" contains null values",
02284 NameStr(tupdesc->attrs[attnum - 1]->attname),
02285 RelationGetRelationName(testrel)),
02286 errtablecol(testrel, attnum)));
02287 }
02288 }
02289 }
02290 heap_endscan(scan);
02291
02292
02293 heap_close(testrel, NoLock);
02294 }
02295 }
02296
02297
02298
02299
02300
02301 typTup->typnotnull = notNull;
02302
02303 simple_heap_update(typrel, &tup->t_self, tup);
02304
02305 CatalogUpdateIndexes(typrel, tup);
02306
02307 InvokeObjectPostAlterHook(TypeRelationId, domainoid, 0);
02308
02309
02310 heap_freetuple(tup);
02311 heap_close(typrel, RowExclusiveLock);
02312
02313 return domainoid;
02314 }
02315
02316
02317
02318
02319
02320
02321 Oid
02322 AlterDomainDropConstraint(List *names, const char *constrName,
02323 DropBehavior behavior, bool missing_ok)
02324 {
02325 TypeName *typename;
02326 Oid domainoid;
02327 HeapTuple tup;
02328 Relation rel;
02329 Relation conrel;
02330 SysScanDesc conscan;
02331 ScanKeyData key[1];
02332 HeapTuple contup;
02333 bool found = false;
02334
02335
02336 typename = makeTypeNameFromNameList(names);
02337 domainoid = typenameTypeId(NULL, typename);
02338
02339
02340 rel = heap_open(TypeRelationId, RowExclusiveLock);
02341
02342 tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(domainoid));
02343 if (!HeapTupleIsValid(tup))
02344 elog(ERROR, "cache lookup failed for type %u", domainoid);
02345
02346
02347 checkDomainOwner(tup);
02348
02349
02350 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
02351
02352
02353 ScanKeyInit(&key[0],
02354 Anum_pg_constraint_contypid,
02355 BTEqualStrategyNumber, F_OIDEQ,
02356 ObjectIdGetDatum(HeapTupleGetOid(tup)));
02357
02358 conscan = systable_beginscan(conrel, ConstraintTypidIndexId, true,
02359 SnapshotNow, 1, key);
02360
02361
02362
02363
02364 while ((contup = systable_getnext(conscan)) != NULL)
02365 {
02366 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(contup);
02367
02368 if (strcmp(NameStr(con->conname), constrName) == 0)
02369 {
02370 ObjectAddress conobj;
02371
02372 conobj.classId = ConstraintRelationId;
02373 conobj.objectId = HeapTupleGetOid(contup);
02374 conobj.objectSubId = 0;
02375
02376 performDeletion(&conobj, behavior, 0);
02377 found = true;
02378 }
02379 }
02380
02381 systable_endscan(conscan);
02382 heap_close(conrel, RowExclusiveLock);
02383
02384 heap_close(rel, NoLock);
02385
02386 if (!found)
02387 {
02388 if (!missing_ok)
02389 ereport(ERROR,
02390 (errcode(ERRCODE_UNDEFINED_OBJECT),
02391 errmsg("constraint \"%s\" of domain \"%s\" does not exist",
02392 constrName, TypeNameToString(typename))));
02393 else
02394 ereport(NOTICE,
02395 (errmsg("constraint \"%s\" of domain \"%s\" does not exist, skipping",
02396 constrName, TypeNameToString(typename))));
02397 }
02398
02399 return domainoid;
02400 }
02401
02402
02403
02404
02405
02406
02407 Oid
02408 AlterDomainAddConstraint(List *names, Node *newConstraint)
02409 {
02410 TypeName *typename;
02411 Oid domainoid;
02412 Relation typrel;
02413 HeapTuple tup;
02414 Form_pg_type typTup;
02415 Constraint *constr;
02416 char *ccbin;
02417
02418
02419 typename = makeTypeNameFromNameList(names);
02420 domainoid = typenameTypeId(NULL, typename);
02421
02422
02423 typrel = heap_open(TypeRelationId, RowExclusiveLock);
02424
02425 tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(domainoid));
02426 if (!HeapTupleIsValid(tup))
02427 elog(ERROR, "cache lookup failed for type %u", domainoid);
02428 typTup = (Form_pg_type) GETSTRUCT(tup);
02429
02430
02431 checkDomainOwner(tup);
02432
02433 if (!IsA(newConstraint, Constraint))
02434 elog(ERROR, "unrecognized node type: %d",
02435 (int) nodeTag(newConstraint));
02436
02437 constr = (Constraint *) newConstraint;
02438
02439 switch (constr->contype)
02440 {
02441 case CONSTR_CHECK:
02442
02443 break;
02444
02445 case CONSTR_UNIQUE:
02446 ereport(ERROR,
02447 (errcode(ERRCODE_SYNTAX_ERROR),
02448 errmsg("unique constraints not possible for domains")));
02449 break;
02450
02451 case CONSTR_PRIMARY:
02452 ereport(ERROR,
02453 (errcode(ERRCODE_SYNTAX_ERROR),
02454 errmsg("primary key constraints not possible for domains")));
02455 break;
02456
02457 case CONSTR_EXCLUSION:
02458 ereport(ERROR,
02459 (errcode(ERRCODE_SYNTAX_ERROR),
02460 errmsg("exclusion constraints not possible for domains")));
02461 break;
02462
02463 case CONSTR_FOREIGN:
02464 ereport(ERROR,
02465 (errcode(ERRCODE_SYNTAX_ERROR),
02466 errmsg("foreign key constraints not possible for domains")));
02467 break;
02468
02469 case CONSTR_ATTR_DEFERRABLE:
02470 case CONSTR_ATTR_NOT_DEFERRABLE:
02471 case CONSTR_ATTR_DEFERRED:
02472 case CONSTR_ATTR_IMMEDIATE:
02473 ereport(ERROR,
02474 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
02475 errmsg("specifying constraint deferrability not supported for domains")));
02476 break;
02477
02478 default:
02479 elog(ERROR, "unrecognized constraint subtype: %d",
02480 (int) constr->contype);
02481 break;
02482 }
02483
02484
02485
02486
02487
02488
02489
02490 ccbin = domainAddConstraint(domainoid, typTup->typnamespace,
02491 typTup->typbasetype, typTup->typtypmod,
02492 constr, NameStr(typTup->typname));
02493
02494
02495
02496
02497
02498 if (!constr->skip_validation)
02499 validateDomainConstraint(domainoid, ccbin);
02500
02501
02502 heap_close(typrel, RowExclusiveLock);
02503
02504 return domainoid;
02505 }
02506
02507
02508
02509
02510
02511
02512 Oid
02513 AlterDomainValidateConstraint(List *names, char *constrName)
02514 {
02515 TypeName *typename;
02516 Oid domainoid;
02517 Relation typrel;
02518 Relation conrel;
02519 HeapTuple tup;
02520 Form_pg_constraint con = NULL;
02521 Form_pg_constraint copy_con;
02522 char *conbin;
02523 SysScanDesc scan;
02524 Datum val;
02525 bool found = false;
02526 bool isnull;
02527 HeapTuple tuple;
02528 HeapTuple copyTuple;
02529 ScanKeyData key;
02530
02531
02532 typename = makeTypeNameFromNameList(names);
02533 domainoid = typenameTypeId(NULL, typename);
02534
02535
02536 typrel = heap_open(TypeRelationId, AccessShareLock);
02537
02538 tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(domainoid));
02539 if (!HeapTupleIsValid(tup))
02540 elog(ERROR, "cache lookup failed for type %u", domainoid);
02541
02542
02543 checkDomainOwner(tup);
02544
02545
02546
02547
02548 conrel = heap_open(ConstraintRelationId, RowExclusiveLock);
02549 ScanKeyInit(&key,
02550 Anum_pg_constraint_contypid,
02551 BTEqualStrategyNumber, F_OIDEQ,
02552 ObjectIdGetDatum(domainoid));
02553 scan = systable_beginscan(conrel, ConstraintTypidIndexId,
02554 true, SnapshotNow, 1, &key);
02555
02556 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
02557 {
02558 con = (Form_pg_constraint) GETSTRUCT(tuple);
02559 if (strcmp(NameStr(con->conname), constrName) == 0)
02560 {
02561 found = true;
02562 break;
02563 }
02564 }
02565
02566 if (!found)
02567 ereport(ERROR,
02568 (errcode(ERRCODE_UNDEFINED_OBJECT),
02569 errmsg("constraint \"%s\" of domain \"%s\" does not exist",
02570 constrName, TypeNameToString(typename))));
02571
02572 if (con->contype != CONSTRAINT_CHECK)
02573 ereport(ERROR,
02574 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
02575 errmsg("constraint \"%s\" of domain \"%s\" is not a check constraint",
02576 constrName, TypeNameToString(typename))));
02577
02578 val = SysCacheGetAttr(CONSTROID, tuple,
02579 Anum_pg_constraint_conbin,
02580 &isnull);
02581 if (isnull)
02582 elog(ERROR, "null conbin for constraint %u",
02583 HeapTupleGetOid(tuple));
02584 conbin = TextDatumGetCString(val);
02585
02586 validateDomainConstraint(domainoid, conbin);
02587
02588
02589
02590
02591 copyTuple = heap_copytuple(tuple);
02592 copy_con = (Form_pg_constraint) GETSTRUCT(copyTuple);
02593 copy_con->convalidated = true;
02594 simple_heap_update(conrel, ©Tuple->t_self, copyTuple);
02595 CatalogUpdateIndexes(conrel, copyTuple);
02596
02597 InvokeObjectPostAlterHook(ConstraintRelationId,
02598 HeapTupleGetOid(copyTuple), 0);
02599
02600 heap_freetuple(copyTuple);
02601
02602 systable_endscan(scan);
02603
02604 heap_close(typrel, AccessShareLock);
02605 heap_close(conrel, RowExclusiveLock);
02606
02607 ReleaseSysCache(tup);
02608
02609 return domainoid;
02610 }
02611
02612 static void
02613 validateDomainConstraint(Oid domainoid, char *ccbin)
02614 {
02615 Expr *expr = (Expr *) stringToNode(ccbin);
02616 List *rels;
02617 ListCell *rt;
02618 EState *estate;
02619 ExprContext *econtext;
02620 ExprState *exprstate;
02621
02622
02623 estate = CreateExecutorState();
02624 econtext = GetPerTupleExprContext(estate);
02625
02626
02627 exprstate = ExecPrepareExpr(expr, estate);
02628
02629
02630
02631
02632 rels = get_rels_with_domain(domainoid, ShareLock);
02633
02634 foreach(rt, rels)
02635 {
02636 RelToCheck *rtc = (RelToCheck *) lfirst(rt);
02637 Relation testrel = rtc->rel;
02638 TupleDesc tupdesc = RelationGetDescr(testrel);
02639 HeapScanDesc scan;
02640 HeapTuple tuple;
02641
02642
02643 scan = heap_beginscan(testrel, SnapshotNow, 0, NULL);
02644 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
02645 {
02646 int i;
02647
02648
02649 for (i = 0; i < rtc->natts; i++)
02650 {
02651 int attnum = rtc->atts[i];
02652 Datum d;
02653 bool isNull;
02654 Datum conResult;
02655
02656 d = heap_getattr(tuple, attnum, tupdesc, &isNull);
02657
02658 econtext->domainValue_datum = d;
02659 econtext->domainValue_isNull = isNull;
02660
02661 conResult = ExecEvalExprSwitchContext(exprstate,
02662 econtext,
02663 &isNull, NULL);
02664
02665 if (!isNull && !DatumGetBool(conResult))
02666 {
02667
02668
02669
02670
02671
02672
02673
02674
02675 ereport(ERROR,
02676 (errcode(ERRCODE_CHECK_VIOLATION),
02677 errmsg("column \"%s\" of table \"%s\" contains values that violate the new constraint",
02678 NameStr(tupdesc->attrs[attnum - 1]->attname),
02679 RelationGetRelationName(testrel)),
02680 errtablecol(testrel, attnum)));
02681 }
02682 }
02683
02684 ResetExprContext(econtext);
02685 }
02686 heap_endscan(scan);
02687
02688
02689 heap_close(testrel, NoLock);
02690 }
02691
02692 FreeExecutorState(estate);
02693 }
02694
02695
02696
02697
02698
02699
02700
02701
02702
02703
02704
02705
02706
02707
02708
02709
02710
02711
02712
02713
02714
02715
02716
02717
02718
02719
02720
02721
02722
02723
02724
02725
02726
02727 static List *
02728 get_rels_with_domain(Oid domainOid, LOCKMODE lockmode)
02729 {
02730 List *result = NIL;
02731 Relation depRel;
02732 ScanKeyData key[2];
02733 SysScanDesc depScan;
02734 HeapTuple depTup;
02735
02736 Assert(lockmode != NoLock);
02737
02738
02739
02740
02741
02742 depRel = heap_open(DependRelationId, AccessShareLock);
02743
02744 ScanKeyInit(&key[0],
02745 Anum_pg_depend_refclassid,
02746 BTEqualStrategyNumber, F_OIDEQ,
02747 ObjectIdGetDatum(TypeRelationId));
02748 ScanKeyInit(&key[1],
02749 Anum_pg_depend_refobjid,
02750 BTEqualStrategyNumber, F_OIDEQ,
02751 ObjectIdGetDatum(domainOid));
02752
02753 depScan = systable_beginscan(depRel, DependReferenceIndexId, true,
02754 SnapshotNow, 2, key);
02755
02756 while (HeapTupleIsValid(depTup = systable_getnext(depScan)))
02757 {
02758 Form_pg_depend pg_depend = (Form_pg_depend) GETSTRUCT(depTup);
02759 RelToCheck *rtc = NULL;
02760 ListCell *rellist;
02761 Form_pg_attribute pg_att;
02762 int ptr;
02763
02764
02765 if (pg_depend->classid == TypeRelationId)
02766 {
02767 Assert(get_typtype(pg_depend->objid) == TYPTYPE_DOMAIN);
02768
02769
02770
02771
02772
02773
02774
02775 result = list_concat(result,
02776 get_rels_with_domain(pg_depend->objid,
02777 lockmode));
02778 continue;
02779 }
02780
02781
02782
02783 if (pg_depend->classid != RelationRelationId ||
02784 pg_depend->objsubid <= 0)
02785 continue;
02786
02787
02788 foreach(rellist, result)
02789 {
02790 RelToCheck *rt = (RelToCheck *) lfirst(rellist);
02791
02792 if (RelationGetRelid(rt->rel) == pg_depend->objid)
02793 {
02794 rtc = rt;
02795 break;
02796 }
02797 }
02798
02799 if (rtc == NULL)
02800 {
02801
02802 Relation rel;
02803
02804
02805 rel = relation_open(pg_depend->objid, lockmode);
02806
02807
02808
02809
02810
02811 if (OidIsValid(rel->rd_rel->reltype))
02812 find_composite_type_dependencies(rel->rd_rel->reltype,
02813 NULL,
02814 format_type_be(domainOid));
02815
02816
02817 if (rel->rd_rel->relkind != RELKIND_RELATION &&
02818 rel->rd_rel->relkind != RELKIND_MATVIEW)
02819 {
02820 relation_close(rel, lockmode);
02821 continue;
02822 }
02823
02824
02825 rtc = (RelToCheck *) palloc(sizeof(RelToCheck));
02826 rtc->rel = rel;
02827 rtc->natts = 0;
02828 rtc->atts = (int *) palloc(sizeof(int) * RelationGetNumberOfAttributes(rel));
02829 result = lcons(rtc, result);
02830 }
02831
02832
02833
02834
02835
02836
02837
02838 if (pg_depend->objsubid > RelationGetNumberOfAttributes(rtc->rel))
02839 continue;
02840 pg_att = rtc->rel->rd_att->attrs[pg_depend->objsubid - 1];
02841 if (pg_att->attisdropped || pg_att->atttypid != domainOid)
02842 continue;
02843
02844
02845
02846
02847
02848
02849 Assert(rtc->natts < RelationGetNumberOfAttributes(rtc->rel));
02850
02851 ptr = rtc->natts++;
02852 while (ptr > 0 && rtc->atts[ptr - 1] > pg_depend->objsubid)
02853 {
02854 rtc->atts[ptr] = rtc->atts[ptr - 1];
02855 ptr--;
02856 }
02857 rtc->atts[ptr] = pg_depend->objsubid;
02858 }
02859
02860 systable_endscan(depScan);
02861
02862 relation_close(depRel, AccessShareLock);
02863
02864 return result;
02865 }
02866
02867
02868
02869
02870
02871
02872
02873 void
02874 checkDomainOwner(HeapTuple tup)
02875 {
02876 Form_pg_type typTup = (Form_pg_type) GETSTRUCT(tup);
02877
02878
02879 if (typTup->typtype != TYPTYPE_DOMAIN)
02880 ereport(ERROR,
02881 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
02882 errmsg("%s is not a domain",
02883 format_type_be(HeapTupleGetOid(tup)))));
02884
02885
02886 if (!pg_type_ownercheck(HeapTupleGetOid(tup), GetUserId()))
02887 aclcheck_error_type(ACLCHECK_NOT_OWNER, HeapTupleGetOid(tup));
02888 }
02889
02890
02891
02892
02893 static char *
02894 domainAddConstraint(Oid domainOid, Oid domainNamespace, Oid baseTypeOid,
02895 int typMod, Constraint *constr,
02896 char *domainName)
02897 {
02898 Node *expr;
02899 char *ccsrc;
02900 char *ccbin;
02901 ParseState *pstate;
02902 CoerceToDomainValue *domVal;
02903
02904
02905
02906
02907 if (constr->conname)
02908 {
02909 if (ConstraintNameIsUsed(CONSTRAINT_DOMAIN,
02910 domainOid,
02911 domainNamespace,
02912 constr->conname))
02913 ereport(ERROR,
02914 (errcode(ERRCODE_DUPLICATE_OBJECT),
02915 errmsg("constraint \"%s\" for domain \"%s\" already exists",
02916 constr->conname, domainName)));
02917 }
02918 else
02919 constr->conname = ChooseConstraintName(domainName,
02920 NULL,
02921 "check",
02922 domainNamespace,
02923 NIL);
02924
02925
02926
02927
02928 pstate = make_parsestate(NULL);
02929
02930
02931
02932
02933
02934
02935
02936
02937 domVal = makeNode(CoerceToDomainValue);
02938 domVal->typeId = baseTypeOid;
02939 domVal->typeMod = typMod;
02940 domVal->collation = get_typcollation(baseTypeOid);
02941 domVal->location = -1;
02942
02943 pstate->p_value_substitute = (Node *) domVal;
02944
02945 expr = transformExpr(pstate, constr->raw_expr, EXPR_KIND_DOMAIN_CHECK);
02946
02947
02948
02949
02950 expr = coerce_to_boolean(pstate, expr, "CHECK");
02951
02952
02953
02954
02955 assign_expr_collations(pstate, expr);
02956
02957
02958
02959
02960
02961 if (list_length(pstate->p_rtable) != 0 ||
02962 contain_var_clause(expr))
02963 ereport(ERROR,
02964 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
02965 errmsg("cannot use table references in domain check constraint")));
02966
02967
02968
02969
02970 ccbin = nodeToString(expr);
02971
02972
02973
02974
02975 ccsrc = deparse_expression(expr,
02976 NIL, false, false);
02977
02978
02979
02980
02981 CreateConstraintEntry(constr->conname,
02982 domainNamespace,
02983 CONSTRAINT_CHECK,
02984 false,
02985 false,
02986 !constr->skip_validation,
02987 InvalidOid,
02988 NULL,
02989 0,
02990 domainOid,
02991 InvalidOid,
02992 InvalidOid,
02993 NULL,
02994 NULL,
02995 NULL,
02996 NULL,
02997 0,
02998 ' ',
02999 ' ',
03000 ' ',
03001 NULL,
03002 expr,
03003 ccbin,
03004 ccsrc,
03005 true,
03006 0,
03007 false,
03008 false);
03009
03010
03011
03012
03013
03014 return ccbin;
03015 }
03016
03017
03018
03019
03020
03021
03022
03023
03024
03025
03026
03027
03028
03029 List *
03030 GetDomainConstraints(Oid typeOid)
03031 {
03032 List *result = NIL;
03033 bool notNull = false;
03034 Relation conRel;
03035
03036 conRel = heap_open(ConstraintRelationId, AccessShareLock);
03037
03038 for (;;)
03039 {
03040 HeapTuple tup;
03041 HeapTuple conTup;
03042 Form_pg_type typTup;
03043 ScanKeyData key[1];
03044 SysScanDesc scan;
03045
03046 tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typeOid));
03047 if (!HeapTupleIsValid(tup))
03048 elog(ERROR, "cache lookup failed for type %u", typeOid);
03049 typTup = (Form_pg_type) GETSTRUCT(tup);
03050
03051 if (typTup->typtype != TYPTYPE_DOMAIN)
03052 {
03053
03054 ReleaseSysCache(tup);
03055 break;
03056 }
03057
03058
03059 if (typTup->typnotnull)
03060 notNull = true;
03061
03062
03063 ScanKeyInit(&key[0],
03064 Anum_pg_constraint_contypid,
03065 BTEqualStrategyNumber, F_OIDEQ,
03066 ObjectIdGetDatum(typeOid));
03067
03068 scan = systable_beginscan(conRel, ConstraintTypidIndexId, true,
03069 SnapshotNow, 1, key);
03070
03071 while (HeapTupleIsValid(conTup = systable_getnext(scan)))
03072 {
03073 Form_pg_constraint c = (Form_pg_constraint) GETSTRUCT(conTup);
03074 Datum val;
03075 bool isNull;
03076 Expr *check_expr;
03077 DomainConstraintState *r;
03078
03079
03080 if (c->contype != CONSTRAINT_CHECK)
03081 continue;
03082
03083
03084
03085
03086 val = fastgetattr(conTup, Anum_pg_constraint_conbin,
03087 conRel->rd_att, &isNull);
03088 if (isNull)
03089 elog(ERROR, "domain \"%s\" constraint \"%s\" has NULL conbin",
03090 NameStr(typTup->typname), NameStr(c->conname));
03091
03092 check_expr = (Expr *) stringToNode(TextDatumGetCString(val));
03093
03094
03095 check_expr = expression_planner(check_expr);
03096
03097 r = makeNode(DomainConstraintState);
03098 r->constrainttype = DOM_CONSTRAINT_CHECK;
03099 r->name = pstrdup(NameStr(c->conname));
03100 r->check_expr = ExecInitExpr(check_expr, NULL);
03101
03102
03103
03104
03105
03106 result = lcons(r, result);
03107 }
03108
03109 systable_endscan(scan);
03110
03111
03112 typeOid = typTup->typbasetype;
03113 ReleaseSysCache(tup);
03114 }
03115
03116 heap_close(conRel, AccessShareLock);
03117
03118
03119
03120
03121
03122 if (notNull)
03123 {
03124 DomainConstraintState *r = makeNode(DomainConstraintState);
03125
03126 r->constrainttype = DOM_CONSTRAINT_NOTNULL;
03127 r->name = pstrdup("NOT NULL");
03128 r->check_expr = NULL;
03129
03130
03131 result = lcons(r, result);
03132 }
03133
03134 return result;
03135 }
03136
03137
03138
03139
03140
03141 Oid
03142 RenameType(RenameStmt *stmt)
03143 {
03144 List *names = stmt->object;
03145 const char *newTypeName = stmt->newname;
03146 TypeName *typename;
03147 Oid typeOid;
03148 Relation rel;
03149 HeapTuple tup;
03150 Form_pg_type typTup;
03151
03152
03153 typename = makeTypeNameFromNameList(names);
03154 typeOid = typenameTypeId(NULL, typename);
03155
03156
03157 rel = heap_open(TypeRelationId, RowExclusiveLock);
03158
03159 tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(typeOid));
03160 if (!HeapTupleIsValid(tup))
03161 elog(ERROR, "cache lookup failed for type %u", typeOid);
03162 typTup = (Form_pg_type) GETSTRUCT(tup);
03163
03164
03165 if (!pg_type_ownercheck(typeOid, GetUserId()))
03166 aclcheck_error_type(ACLCHECK_NOT_OWNER, typeOid);
03167
03168
03169 if (stmt->renameType == OBJECT_DOMAIN && typTup->typtype != TYPTYPE_DOMAIN)
03170 ereport(ERROR,
03171 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
03172 errmsg("\"%s\" is not a domain",
03173 format_type_be(typeOid))));
03174
03175
03176
03177
03178
03179
03180 if (typTup->typtype == TYPTYPE_COMPOSITE &&
03181 get_rel_relkind(typTup->typrelid) != RELKIND_COMPOSITE_TYPE)
03182 ereport(ERROR,
03183 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
03184 errmsg("%s is a table's row type",
03185 format_type_be(typeOid)),
03186 errhint("Use ALTER TABLE instead.")));
03187
03188
03189 if (OidIsValid(typTup->typelem) &&
03190 get_array_type(typTup->typelem) == typeOid)
03191 ereport(ERROR,
03192 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
03193 errmsg("cannot alter array type %s",
03194 format_type_be(typeOid)),
03195 errhint("You can alter type %s, which will alter the array type as well.",
03196 format_type_be(typTup->typelem))));
03197
03198
03199
03200
03201
03202 if (typTup->typtype == TYPTYPE_COMPOSITE)
03203 RenameRelationInternal(typTup->typrelid, newTypeName, false);
03204 else
03205 RenameTypeInternal(typeOid, newTypeName,
03206 typTup->typnamespace);
03207
03208
03209 heap_close(rel, RowExclusiveLock);
03210
03211 return typeOid;
03212 }
03213
03214
03215
03216
03217 Oid
03218 AlterTypeOwner(List *names, Oid newOwnerId, ObjectType objecttype)
03219 {
03220 TypeName *typename;
03221 Oid typeOid;
03222 Relation rel;
03223 HeapTuple tup;
03224 HeapTuple newtup;
03225 Form_pg_type typTup;
03226 AclResult aclresult;
03227
03228 rel = heap_open(TypeRelationId, RowExclusiveLock);
03229
03230
03231 typename = makeTypeNameFromNameList(names);
03232
03233
03234 tup = LookupTypeName(NULL, typename, NULL);
03235 if (tup == NULL)
03236 ereport(ERROR,
03237 (errcode(ERRCODE_UNDEFINED_OBJECT),
03238 errmsg("type \"%s\" does not exist",
03239 TypeNameToString(typename))));
03240 typeOid = typeTypeId(tup);
03241
03242
03243 newtup = heap_copytuple(tup);
03244 ReleaseSysCache(tup);
03245 tup = newtup;
03246 typTup = (Form_pg_type) GETSTRUCT(tup);
03247
03248
03249 if (objecttype == OBJECT_DOMAIN && typTup->typtype != TYPTYPE_DOMAIN)
03250 ereport(ERROR,
03251 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
03252 errmsg("%s is not a domain",
03253 format_type_be(typeOid))));
03254
03255
03256
03257
03258
03259
03260 if (typTup->typtype == TYPTYPE_COMPOSITE &&
03261 get_rel_relkind(typTup->typrelid) != RELKIND_COMPOSITE_TYPE)
03262 ereport(ERROR,
03263 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
03264 errmsg("%s is a table's row type",
03265 format_type_be(typeOid)),
03266 errhint("Use ALTER TABLE instead.")));
03267
03268
03269 if (OidIsValid(typTup->typelem) &&
03270 get_array_type(typTup->typelem) == typeOid)
03271 ereport(ERROR,
03272 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
03273 errmsg("cannot alter array type %s",
03274 format_type_be(typeOid)),
03275 errhint("You can alter type %s, which will alter the array type as well.",
03276 format_type_be(typTup->typelem))));
03277
03278
03279
03280
03281
03282 if (typTup->typowner != newOwnerId)
03283 {
03284
03285 if (!superuser())
03286 {
03287
03288 if (!pg_type_ownercheck(HeapTupleGetOid(tup), GetUserId()))
03289 aclcheck_error_type(ACLCHECK_NOT_OWNER, HeapTupleGetOid(tup));
03290
03291
03292 check_is_member_of_role(GetUserId(), newOwnerId);
03293
03294
03295 aclresult = pg_namespace_aclcheck(typTup->typnamespace,
03296 newOwnerId,
03297 ACL_CREATE);
03298 if (aclresult != ACLCHECK_OK)
03299 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
03300 get_namespace_name(typTup->typnamespace));
03301 }
03302
03303
03304
03305
03306
03307
03308 if (typTup->typtype == TYPTYPE_COMPOSITE)
03309 ATExecChangeOwner(typTup->typrelid, newOwnerId, true, AccessExclusiveLock);
03310 else
03311 {
03312
03313
03314
03315
03316
03317 typTup->typowner = newOwnerId;
03318
03319 simple_heap_update(rel, &tup->t_self, tup);
03320
03321 CatalogUpdateIndexes(rel, tup);
03322
03323
03324 changeDependencyOnOwner(TypeRelationId, typeOid, newOwnerId);
03325
03326 InvokeObjectPostAlterHook(TypeRelationId, typeOid, 0);
03327
03328
03329 if (OidIsValid(typTup->typarray))
03330 AlterTypeOwnerInternal(typTup->typarray, newOwnerId, false);
03331 }
03332 }
03333
03334
03335 heap_close(rel, RowExclusiveLock);
03336
03337 return typeOid;
03338 }
03339
03340
03341
03342
03343
03344
03345
03346
03347
03348
03349
03350
03351
03352
03353 void
03354 AlterTypeOwnerInternal(Oid typeOid, Oid newOwnerId,
03355 bool hasDependEntry)
03356 {
03357 Relation rel;
03358 HeapTuple tup;
03359 Form_pg_type typTup;
03360
03361 rel = heap_open(TypeRelationId, RowExclusiveLock);
03362
03363 tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(typeOid));
03364 if (!HeapTupleIsValid(tup))
03365 elog(ERROR, "cache lookup failed for type %u", typeOid);
03366 typTup = (Form_pg_type) GETSTRUCT(tup);
03367
03368
03369
03370
03371 typTup->typowner = newOwnerId;
03372
03373 simple_heap_update(rel, &tup->t_self, tup);
03374
03375 CatalogUpdateIndexes(rel, tup);
03376
03377
03378 if (hasDependEntry)
03379 changeDependencyOnOwner(TypeRelationId, typeOid, newOwnerId);
03380
03381
03382 if (OidIsValid(typTup->typarray))
03383 AlterTypeOwnerInternal(typTup->typarray, newOwnerId, false);
03384
03385 InvokeObjectPostAlterHook(TypeRelationId, typeOid, 0);
03386
03387
03388 heap_close(rel, RowExclusiveLock);
03389 }
03390
03391
03392
03393
03394 Oid
03395 AlterTypeNamespace(List *names, const char *newschema, ObjectType objecttype)
03396 {
03397 TypeName *typename;
03398 Oid typeOid;
03399 Oid nspOid;
03400 ObjectAddresses *objsMoved;
03401
03402
03403 typename = makeTypeNameFromNameList(names);
03404 typeOid = typenameTypeId(NULL, typename);
03405
03406
03407 if (objecttype == OBJECT_DOMAIN && get_typtype(typeOid) != TYPTYPE_DOMAIN)
03408 ereport(ERROR,
03409 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
03410 errmsg("%s is not a domain",
03411 format_type_be(typeOid))));
03412
03413
03414 nspOid = LookupCreationNamespace(newschema);
03415
03416 objsMoved = new_object_addresses();
03417 AlterTypeNamespace_oid(typeOid, nspOid, objsMoved);
03418 free_object_addresses(objsMoved);
03419
03420 return typeOid;
03421 }
03422
03423 Oid
03424 AlterTypeNamespace_oid(Oid typeOid, Oid nspOid, ObjectAddresses *objsMoved)
03425 {
03426 Oid elemOid;
03427
03428
03429 if (!pg_type_ownercheck(typeOid, GetUserId()))
03430 aclcheck_error_type(ACLCHECK_NOT_OWNER, typeOid);
03431
03432
03433 elemOid = get_element_type(typeOid);
03434 if (OidIsValid(elemOid) && get_array_type(elemOid) == typeOid)
03435 ereport(ERROR,
03436 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
03437 errmsg("cannot alter array type %s",
03438 format_type_be(typeOid)),
03439 errhint("You can alter type %s, which will alter the array type as well.",
03440 format_type_be(elemOid))));
03441
03442
03443 return AlterTypeNamespaceInternal(typeOid, nspOid, false, true, objsMoved);
03444 }
03445
03446
03447
03448
03449
03450
03451
03452
03453
03454
03455
03456
03457
03458
03459
03460
03461 Oid
03462 AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid,
03463 bool isImplicitArray,
03464 bool errorOnTableType,
03465 ObjectAddresses *objsMoved)
03466 {
03467 Relation rel;
03468 HeapTuple tup;
03469 Form_pg_type typform;
03470 Oid oldNspOid;
03471 Oid arrayOid;
03472 bool isCompositeType;
03473 ObjectAddress thisobj;
03474
03475
03476
03477
03478 thisobj.classId = TypeRelationId;
03479 thisobj.objectId = typeOid;
03480 thisobj.objectSubId = 0;
03481
03482 if (object_address_present(&thisobj, objsMoved))
03483 return InvalidOid;
03484
03485 rel = heap_open(TypeRelationId, RowExclusiveLock);
03486
03487 tup = SearchSysCacheCopy1(TYPEOID, ObjectIdGetDatum(typeOid));
03488 if (!HeapTupleIsValid(tup))
03489 elog(ERROR, "cache lookup failed for type %u", typeOid);
03490 typform = (Form_pg_type) GETSTRUCT(tup);
03491
03492 oldNspOid = typform->typnamespace;
03493 arrayOid = typform->typarray;
03494
03495
03496 CheckSetNamespace(oldNspOid, nspOid, TypeRelationId, typeOid);
03497
03498
03499 if (SearchSysCacheExists2(TYPENAMENSP,
03500 CStringGetDatum(NameStr(typform->typname)),
03501 ObjectIdGetDatum(nspOid)))
03502 ereport(ERROR,
03503 (errcode(ERRCODE_DUPLICATE_OBJECT),
03504 errmsg("type \"%s\" already exists in schema \"%s\"",
03505 NameStr(typform->typname),
03506 get_namespace_name(nspOid))));
03507
03508
03509 isCompositeType =
03510 (typform->typtype == TYPTYPE_COMPOSITE &&
03511 get_rel_relkind(typform->typrelid) == RELKIND_COMPOSITE_TYPE);
03512
03513
03514 if (typform->typtype == TYPTYPE_COMPOSITE && !isCompositeType &&
03515 errorOnTableType)
03516 ereport(ERROR,
03517 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
03518 errmsg("%s is a table's row type",
03519 format_type_be(typeOid)),
03520 errhint("Use ALTER TABLE instead.")));
03521
03522
03523
03524
03525 typform->typnamespace = nspOid;
03526
03527 simple_heap_update(rel, &tup->t_self, tup);
03528 CatalogUpdateIndexes(rel, tup);
03529
03530
03531
03532
03533
03534
03535
03536 if (isCompositeType)
03537 {
03538 Relation classRel;
03539
03540 classRel = heap_open(RelationRelationId, RowExclusiveLock);
03541
03542 AlterRelationNamespaceInternal(classRel, typform->typrelid,
03543 oldNspOid, nspOid,
03544 false, objsMoved);
03545
03546 heap_close(classRel, RowExclusiveLock);
03547
03548
03549
03550
03551
03552 AlterConstraintNamespaces(typform->typrelid, oldNspOid,
03553 nspOid, false, objsMoved);
03554 }
03555 else
03556 {
03557
03558 if (typform->typtype == TYPTYPE_DOMAIN)
03559 AlterConstraintNamespaces(typeOid, oldNspOid, nspOid, true,
03560 objsMoved);
03561 }
03562
03563
03564
03565
03566
03567 if ((isCompositeType || typform->typtype != TYPTYPE_COMPOSITE) &&
03568 !isImplicitArray)
03569 if (changeDependencyFor(TypeRelationId, typeOid,
03570 NamespaceRelationId, oldNspOid, nspOid) != 1)
03571 elog(ERROR, "failed to change schema dependency for type %s",
03572 format_type_be(typeOid));
03573
03574 InvokeObjectPostAlterHook(TypeRelationId, typeOid, 0);
03575
03576 heap_freetuple(tup);
03577
03578 heap_close(rel, RowExclusiveLock);
03579
03580 add_exact_object_address(&thisobj, objsMoved);
03581
03582
03583 if (OidIsValid(arrayOid))
03584 AlterTypeNamespaceInternal(arrayOid, nspOid, true, true, objsMoved);
03585
03586 return oldNspOid;
03587 }