functioncmds.c 25.3 KB
Newer Older
1 2 3 4 5 6
/*-------------------------------------------------------------------------
 *
 * functioncmds.c
 *
 *	  Routines for CREATE and DROP FUNCTION commands
 *
Bruce Momjian's avatar
Bruce Momjian committed
7
 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
8 9 10 11
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
12
 *	  $Header: /cvsroot/pgsql/src/backend/commands/functioncmds.c,v 1.23 2002/10/04 22:08:44 tgl Exp $
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 *
 * DESCRIPTION
 *	  These routines take the parse tree and pick out the
 *	  appropriate arguments/flags, and pass the results to the
 *	  corresponding "FooDefine" routines (in src/catalog) that do
 *	  the actual catalog-munging.  These routines also verify permission
 *	  of the user to execute the command.
 *
 * NOTES
 *	  These things must be defined and committed in the following order:
 *		"create function":
 *				input/output, recv/send procedures
 *		"create type":
 *				type
 *		"create operator":
 *				operators
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

34
#include "access/genam.h"
35 36
#include "access/heapam.h"
#include "catalog/catname.h"
37
#include "catalog/dependency.h"
38
#include "catalog/indexing.h"
39
#include "catalog/namespace.h"
40
#include "catalog/pg_cast.h"
41 42 43 44 45 46 47 48 49
#include "catalog/pg_language.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "miscadmin.h"
#include "optimizer/cost.h"
#include "parser/parse_func.h"
#include "parser/parse_type.h"
#include "utils/acl.h"
50
#include "utils/builtins.h"
51
#include "utils/fmgroids.h"
52 53 54 55 56 57 58 59 60 61 62 63
#include "utils/lsyscache.h"
#include "utils/syscache.h"


/*
 *	 Examine the "returns" clause returnType of the CREATE FUNCTION statement
 *	 and return information about it as *prorettype_p and *returnsSet.
 *
 * This is more complex than the average typename lookup because we want to
 * allow a shell type to be used, or even created if the specified return type
 * doesn't exist yet.  (Without this, there's no way to define the I/O procs
 * for a new type.)  But SQL function creation won't cope, so error out if
Bruce Momjian's avatar
Bruce Momjian committed
64
 * the target language is SQL.	(We do this here, not in the SQL-function
65 66
 * validator, so as not to produce a WARNING and then an ERROR for the same
 * condition.)
67 68 69 70 71
 */
static void
compute_return_type(TypeName *returnType, Oid languageOid,
					Oid *prorettype_p, bool *returnsSet_p)
{
Bruce Momjian's avatar
Bruce Momjian committed
72
	Oid			rettype;
73 74 75 76 77 78 79 80

	rettype = LookupTypeName(returnType);

	if (OidIsValid(rettype))
	{
		if (!get_typisdefined(rettype))
		{
			if (languageOid == SQLlanguageId)
81 82
				elog(ERROR, "SQL function cannot return shell type \"%s\"",
					 TypeNameToString(returnType));
83 84 85 86 87 88 89
			else
				elog(WARNING, "Return type \"%s\" is only a shell",
					 TypeNameToString(returnType));
		}
	}
	else
	{
Bruce Momjian's avatar
Bruce Momjian committed
90
		char	   *typnam = TypeNameToString(returnType);
91 92 93
		Oid			namespaceId;
		AclResult	aclresult;
		char	   *typname;
94

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
		/*
		 * Only C-coded functions can be I/O functions.  We enforce this
		 * restriction here mainly to prevent littering the catalogs with
		 * shell types due to simple typos in user-defined function
		 * definitions.
		 */
		if (languageOid != INTERNALlanguageId &&
			languageOid != ClanguageId)
			elog(ERROR, "Type \"%s\" does not exist", typnam);

		/* Otherwise, go ahead and make a shell type */
		elog(WARNING, "ProcedureCreate: type %s is not yet defined",
			 typnam);
		namespaceId = QualifiedNameGetCreationNamespace(returnType->names,
														&typname);
		aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
										  ACL_CREATE);
		if (aclresult != ACLCHECK_OK)
			aclcheck_error(aclresult, get_namespace_name(namespaceId));
		rettype = TypeShellMake(typname, namespaceId);
		if (!OidIsValid(rettype))
			elog(ERROR, "could not create type %s", typnam);
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
	}

	*prorettype_p = rettype;
	*returnsSet_p = returnType->setof;
}

/*
 * Interpret the argument-types list of the CREATE FUNCTION statement.
 */
static int
compute_parameter_types(List *argTypes, Oid languageOid,
						Oid *parameterTypes)
{
	int			parameterCount = 0;
	List	   *x;

	MemSet(parameterTypes, 0, FUNC_MAX_ARGS * sizeof(Oid));
	foreach(x, argTypes)
	{
		TypeName   *t = (TypeName *) lfirst(x);
		Oid			toid;

		if (parameterCount >= FUNC_MAX_ARGS)
			elog(ERROR, "functions cannot have more than %d arguments",
				 FUNC_MAX_ARGS);

		toid = LookupTypeName(t);
		if (OidIsValid(toid))
		{
			if (!get_typisdefined(toid))
			{
148
				/* As above, hard error if language is SQL */
149
				if (languageOid == SQLlanguageId)
150 151 152 153 154
					elog(ERROR, "SQL function cannot accept shell type \"%s\"",
						 TypeNameToString(t));
				else
					elog(WARNING, "Argument type \"%s\" is only a shell",
						 TypeNameToString(t));
155
			}
156 157 158 159 160
		}
		else
		{
			elog(ERROR, "Type \"%s\" does not exist",
				 TypeNameToString(t));
161 162 163
		}

		if (t->setof)
164
			elog(ERROR, "Functions cannot accept set arguments");
165 166 167 168 169 170 171

		parameterTypes[parameterCount++] = toid;
	}

	return parameterCount;
}

172 173 174 175 176 177 178 179 180 181 182 183

/*
 * Dissect the list of options assembled in gram.y into function
 * attributes.
 */

static void
compute_attributes_sql_style(const List *options,
							 List **as,
							 char **language,
							 char *volatility_p,
							 bool *strict_p,
184
							 bool *security_definer)
185 186
{
	const List *option;
Bruce Momjian's avatar
Bruce Momjian committed
187 188 189 190 191
	DefElem    *as_item = NULL;
	DefElem    *language_item = NULL;
	DefElem    *volatility_item = NULL;
	DefElem    *strict_item = NULL;
	DefElem    *security_item = NULL;
192 193 194 195 196

	foreach(option, options)
	{
		DefElem    *defel = (DefElem *) lfirst(option);

Bruce Momjian's avatar
Bruce Momjian committed
197
		if (strcmp(defel->defname, "as") == 0)
198 199 200 201 202
		{
			if (as_item)
				elog(ERROR, "conflicting or redundant options");
			as_item = defel;
		}
Bruce Momjian's avatar
Bruce Momjian committed
203
		else if (strcmp(defel->defname, "language") == 0)
204 205 206 207 208
		{
			if (language_item)
				elog(ERROR, "conflicting or redundant options");
			language_item = defel;
		}
Bruce Momjian's avatar
Bruce Momjian committed
209
		else if (strcmp(defel->defname, "volatility") == 0)
210 211 212 213 214
		{
			if (volatility_item)
				elog(ERROR, "conflicting or redundant options");
			volatility_item = defel;
		}
Bruce Momjian's avatar
Bruce Momjian committed
215
		else if (strcmp(defel->defname, "strict") == 0)
216 217 218 219 220
		{
			if (strict_item)
				elog(ERROR, "conflicting or redundant options");
			strict_item = defel;
		}
Bruce Momjian's avatar
Bruce Momjian committed
221
		else if (strcmp(defel->defname, "security") == 0)
222 223 224 225 226 227 228 229 230 231
		{
			if (security_item)
				elog(ERROR, "conflicting or redundant options");
			security_item = defel;
		}
		else
			elog(ERROR, "invalid CREATE FUNCTION option");
	}

	if (as_item)
Bruce Momjian's avatar
Bruce Momjian committed
232
		*as = (List *) as_item->arg;
233 234 235 236 237 238 239 240 241 242
	else
		elog(ERROR, "no function body specified");

	if (language_item)
		*language = strVal(language_item->arg);
	else
		elog(ERROR, "no language specified");

	if (volatility_item)
	{
Bruce Momjian's avatar
Bruce Momjian committed
243
		if (strcmp(strVal(volatility_item->arg), "immutable") == 0)
244
			*volatility_p = PROVOLATILE_IMMUTABLE;
Bruce Momjian's avatar
Bruce Momjian committed
245
		else if (strcmp(strVal(volatility_item->arg), "stable") == 0)
246
			*volatility_p = PROVOLATILE_STABLE;
Bruce Momjian's avatar
Bruce Momjian committed
247
		else if (strcmp(strVal(volatility_item->arg), "volatile") == 0)
248 249 250 251 252 253 254 255 256 257 258 259
			*volatility_p = PROVOLATILE_VOLATILE;
		else
			elog(ERROR, "invalid volatility");
	}

	if (strict_item)
		*strict_p = intVal(strict_item->arg);
	if (security_item)
		*security_definer = intVal(security_item->arg);
}


260 261 262 263 264 265 266
/*-------------
 *	 Interpret the parameters *parameters and return their contents as
 *	 *byte_pct_p, etc.
 *
 *	These parameters supply optional information about a function.
 *	All have defaults if not specified.
 *
267
 *	Note: currently, only two of these parameters actually do anything:
268 269 270 271 272 273 274 275 276 277 278 279 280
 *
 *	 * isStrict means the function should not be called when any NULL
 *	   inputs are present; instead a NULL result value should be assumed.
 *
 *	 * volatility tells the optimizer whether the function's result can
 *	   be assumed to be repeatable over multiple evaluations.
 *
 *	The other four parameters are not used anywhere.	They used to be
 *	used in the "expensive functions" optimizer, but that's been dead code
 *	for a long time.
 *------------
 */
static void
281
compute_attributes_with_style(List *parameters, bool *isStrict_p, char *volatility_p)
282 283 284 285 286 287 288
{
	List	   *pl;

	foreach(pl, parameters)
	{
		DefElem    *param = (DefElem *) lfirst(pl);

289
		if (strcasecmp(param->defname, "isstrict") == 0)
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
			*isStrict_p = true;
		else if (strcasecmp(param->defname, "iscachable") == 0)
		{
			/* obsolete spelling of isImmutable */
			*volatility_p = PROVOLATILE_IMMUTABLE;
		}
		else
			elog(WARNING, "Unrecognized function attribute '%s' ignored",
				 param->defname);
	}
}


/*
 * For a dynamically linked C language object, the form of the clause is
 *
 *	   AS <object file name> [, <link symbol name> ]
 *
 * In all other cases
 *
 *	   AS <object reference, or sql code>
 *
 */

static void
interpret_AS_clause(Oid languageOid, const char *languageName, const List *as,
					char **prosrc_str_p, char **probin_str_p)
{
	Assert(as != NIL);

	if (languageOid == ClanguageId)
	{
		/*
		 * For "C" language, store the file name in probin and, when
		 * given, the link symbol name in prosrc.
		 */
		*probin_str_p = strVal(lfirst(as));
		if (lnext(as) == NULL)
			*prosrc_str_p = "-";
		else
			*prosrc_str_p = strVal(lsecond(as));
	}
	else
	{
		/* Everything else wants the given string in prosrc. */
		*prosrc_str_p = strVal(lfirst(as));
		*probin_str_p = "-";

		if (lnext(as) != NIL)
			elog(ERROR, "CREATE FUNCTION: only one AS item needed for %s language",
				 languageName);
	}
}



/*
 * CreateFunction
 *	 Execute a CREATE FUNCTION utility statement.
 */
void
351
CreateFunction(CreateFunctionStmt *stmt)
352 353 354 355 356
{
	char	   *probin_str;
	char	   *prosrc_str;
	Oid			prorettype;
	bool		returnsSet;
357
	char	   *language;
358 359
	char		languageName[NAMEDATALEN];
	Oid			languageOid;
360
	Oid			languageValidator;
361 362
	char	   *funcname;
	Oid			namespaceId;
363
	AclResult	aclresult;
364 365
	int			parameterCount;
	Oid			parameterTypes[FUNC_MAX_ARGS];
366
	bool		isStrict,
367
				security;
368 369 370
	char		volatility;
	HeapTuple	languageTuple;
	Form_pg_language languageStruct;
371
	List	   *as_clause;
372 373 374 375 376

	/* Convert list of names to a name and namespace */
	namespaceId = QualifiedNameGetCreationNamespace(stmt->funcname,
													&funcname);

377 378 379 380 381
	/* Check we have creation rights in target namespace */
	aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
	if (aclresult != ACLCHECK_OK)
		aclcheck_error(aclresult, get_namespace_name(namespaceId));

382 383
	/* defaults attributes */
	isStrict = false;
384
	security = false;
385 386 387 388
	volatility = PROVOLATILE_VOLATILE;

	/* override attributes from explicit list */
	compute_attributes_sql_style(stmt->options,
Bruce Momjian's avatar
Bruce Momjian committed
389
			   &as_clause, &language, &volatility, &isStrict, &security);
390

391
	/* Convert language name to canonical case */
392
	case_translate_language_name(language, languageName);
393 394 395 396 397 398 399 400

	/* Look up the language and validate permissions */
	languageTuple = SearchSysCache(LANGNAME,
								   PointerGetDatum(languageName),
								   0, 0, 0);
	if (!HeapTupleIsValid(languageTuple))
		elog(ERROR, "language \"%s\" does not exist", languageName);

401
	languageOid = HeapTupleGetOid(languageTuple);
402 403
	languageStruct = (Form_pg_language) GETSTRUCT(languageTuple);

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
	if (languageStruct->lanpltrusted)
	{
		/* if trusted language, need USAGE privilege */
		AclResult	aclresult;

		aclresult = pg_language_aclcheck(languageOid, GetUserId(), ACL_USAGE);
		if (aclresult != ACLCHECK_OK)
			aclcheck_error(aclresult, NameStr(languageStruct->lanname));
	}
	else
	{
		/* if untrusted language, must be superuser */
		if (!superuser())
			aclcheck_error(ACLCHECK_NO_PRIV, NameStr(languageStruct->lanname));
	}
419

420 421
	languageValidator = languageStruct->lanvalidator;

422 423 424 425 426 427 428 429 430 431 432 433
	ReleaseSysCache(languageTuple);

	/*
	 * Convert remaining parameters of CREATE to form wanted by
	 * ProcedureCreate.
	 */
	compute_return_type(stmt->returnType, languageOid,
						&prorettype, &returnsSet);

	parameterCount = compute_parameter_types(stmt->argTypes, languageOid,
											 parameterTypes);

434
	compute_attributes_with_style(stmt->withClause, &isStrict, &volatility);
435

436
	interpret_AS_clause(languageOid, languageName, as_clause,
437 438
						&prosrc_str, &probin_str);

439 440 441
	if (languageOid == INTERNALlanguageId)
	{
		/*
Bruce Momjian's avatar
Bruce Momjian committed
442 443 444 445 446 447
		 * In PostgreSQL versions before 6.5, the SQL name of the created
		 * function could not be different from the internal name, and
		 * "prosrc" wasn't used.  So there is code out there that does
		 * CREATE FUNCTION xyz AS '' LANGUAGE 'internal'. To preserve some
		 * modicum of backwards compatibility, accept an empty "prosrc"
		 * value as meaning the supplied SQL function name.
448 449 450 451 452 453 454 455 456 457 458 459
		 */
		if (strlen(prosrc_str) == 0)
			prosrc_str = funcname;
	}

	if (languageOid == ClanguageId)
	{
		/* If link symbol is specified as "-", substitute procedure name */
		if (strcmp(prosrc_str, "-") == 0)
			prosrc_str = funcname;
	}

460 461 462 463 464 465 466 467 468 469
	/*
	 * And now that we have all the parameters, and know we're permitted
	 * to do so, go ahead and create the function.
	 */
	ProcedureCreate(funcname,
					namespaceId,
					stmt->replace,
					returnsSet,
					prorettype,
					languageOid,
470
					languageValidator,
471 472 473
					prosrc_str, /* converted to text later */
					probin_str, /* converted to text later */
					false,		/* not an aggregate */
474
					security,
475 476 477 478 479 480 481 482 483 484 485 486
					isStrict,
					volatility,
					parameterCount,
					parameterTypes);
}


/*
 * RemoveFunction
 *		Deletes a function.
 */
void
487
RemoveFunction(RemoveFuncStmt *stmt)
488
{
489
	List	   *functionName = stmt->funcname;
Bruce Momjian's avatar
Bruce Momjian committed
490
	List	   *argTypes = stmt->args;	/* list of TypeName nodes */
491 492
	Oid			funcOid;
	HeapTuple	tup;
493
	ObjectAddress object;
494

495 496 497
	/*
	 * Find the function, do permissions and validity checks
	 */
Bruce Momjian's avatar
Bruce Momjian committed
498
	funcOid = LookupFuncNameTypeNames(functionName, argTypes,
499
									  "RemoveFunction");
500 501 502 503

	tup = SearchSysCache(PROCOID,
						 ObjectIdGetDatum(funcOid),
						 0, 0, 0);
Bruce Momjian's avatar
Bruce Momjian committed
504
	if (!HeapTupleIsValid(tup)) /* should not happen */
505 506 507
		elog(ERROR, "RemoveFunction: couldn't find tuple for function %s",
			 NameListToString(functionName));

508 509 510 511 512
	/* Permission check: must own func or its namespace */
	if (!pg_proc_ownercheck(funcOid, GetUserId()) &&
		!pg_namespace_ownercheck(((Form_pg_proc) GETSTRUCT(tup))->pronamespace,
								 GetUserId()))
		aclcheck_error(ACLCHECK_NOT_OWNER, NameListToString(functionName));
513 514 515 516 517 518 519 520 521 522 523 524 525

	if (((Form_pg_proc) GETSTRUCT(tup))->proisagg)
		elog(ERROR, "RemoveFunction: function '%s' is an aggregate"
			 "\n\tUse DROP AGGREGATE to remove it",
			 NameListToString(functionName));

	if (((Form_pg_proc) GETSTRUCT(tup))->prolang == INTERNALlanguageId)
	{
		/* "Helpful" WARNING when removing a builtin function ... */
		elog(WARNING, "Removing built-in function \"%s\"",
			 NameListToString(functionName));
	}

526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
	ReleaseSysCache(tup);

	/*
	 * Do the deletion
	 */
	object.classId = RelOid_pg_proc;
	object.objectId = funcOid;
	object.objectSubId = 0;

	performDeletion(&object, stmt->behavior);
}

/*
 * Guts of function deletion.
 *
 * Note: this is also used for aggregate deletion, since the OIDs of
 * both functions and aggregates point to pg_proc.
 */
void
RemoveFunctionById(Oid funcOid)
{
	Relation	relation;
	HeapTuple	tup;
	bool		isagg;

	/*
	 * Delete the pg_proc tuple.
	 */
	relation = heap_openr(ProcedureRelationName, RowExclusiveLock);

	tup = SearchSysCache(PROCOID,
						 ObjectIdGetDatum(funcOid),
						 0, 0, 0);
Bruce Momjian's avatar
Bruce Momjian committed
559
	if (!HeapTupleIsValid(tup)) /* should not happen */
560 561 562 563
		elog(ERROR, "RemoveFunctionById: couldn't find tuple for function %u",
			 funcOid);

	isagg = ((Form_pg_proc) GETSTRUCT(tup))->proisagg;
564 565 566 567 568 569

	simple_heap_delete(relation, &tup->t_self);

	ReleaseSysCache(tup);

	heap_close(relation, RowExclusiveLock);
570 571 572 573 574 575 576 577 578 579 580

	/*
	 * If there's a pg_aggregate tuple, delete that too.
	 */
	if (isagg)
	{
		relation = heap_openr(AggregateRelationName, RowExclusiveLock);

		tup = SearchSysCache(AGGFNOID,
							 ObjectIdGetDatum(funcOid),
							 0, 0, 0);
Bruce Momjian's avatar
Bruce Momjian committed
581
		if (!HeapTupleIsValid(tup))		/* should not happen */
582 583 584 585 586 587 588 589 590
			elog(ERROR, "RemoveFunctionById: couldn't find pg_aggregate tuple for %u",
				 funcOid);

		simple_heap_delete(relation, &tup->t_self);

		ReleaseSysCache(tup);

		heap_close(relation, RowExclusiveLock);
	}
591
}
592 593


594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
/*
 * SetFunctionReturnType - change declared return type of a function
 *
 * This is presently only used for adjusting legacy functions that return
 * OPAQUE to return whatever we find their correct definition should be.
 * The caller should emit a suitable NOTICE explaining what we did.
 */
void
SetFunctionReturnType(Oid funcOid, Oid newRetType)
{
	Relation	pg_proc_rel;
	HeapTuple	tup;
	Form_pg_proc procForm;

	pg_proc_rel = heap_openr(ProcedureRelationName, RowExclusiveLock);

	tup = SearchSysCacheCopy(PROCOID,
							 ObjectIdGetDatum(funcOid),
							 0, 0, 0);
	if (!HeapTupleIsValid(tup)) /* should not happen */
		elog(ERROR, "SetFunctionReturnType: couldn't find tuple for function %u",
			 funcOid);
	procForm = (Form_pg_proc) GETSTRUCT(tup);

	if (procForm->prorettype != OPAQUEOID)
		elog(ERROR, "SetFunctionReturnType: function %u doesn't return OPAQUE",
			 funcOid);

	/* okay to overwrite copied tuple */
	procForm->prorettype = newRetType;

	/* update the catalog and its indexes */
	simple_heap_update(pg_proc_rel, &tup->t_self, tup);

	CatalogUpdateIndexes(pg_proc_rel, tup);

	heap_close(pg_proc_rel, RowExclusiveLock);
}


/*
 * SetFunctionArgType - change declared argument type of a function
 *
 * As above, but change an argument's type.
 */
void
SetFunctionArgType(Oid funcOid, int argIndex, Oid newArgType)
{
	Relation	pg_proc_rel;
	HeapTuple	tup;
	Form_pg_proc procForm;

	pg_proc_rel = heap_openr(ProcedureRelationName, RowExclusiveLock);

	tup = SearchSysCacheCopy(PROCOID,
							 ObjectIdGetDatum(funcOid),
							 0, 0, 0);
	if (!HeapTupleIsValid(tup)) /* should not happen */
		elog(ERROR, "SetFunctionArgType: couldn't find tuple for function %u",
			 funcOid);
	procForm = (Form_pg_proc) GETSTRUCT(tup);

	if (argIndex < 0 || argIndex >= procForm->pronargs ||
		procForm->proargtypes[argIndex] != OPAQUEOID)
		elog(ERROR, "SetFunctionArgType: function %u doesn't take OPAQUE",
			 funcOid);

	/* okay to overwrite copied tuple */
	procForm->proargtypes[argIndex] = newArgType;

	/* update the catalog and its indexes */
	simple_heap_update(pg_proc_rel, &tup->t_self, tup);

	CatalogUpdateIndexes(pg_proc_rel, tup);

	heap_close(pg_proc_rel, RowExclusiveLock);
}


673 674 675 676 677 678 679 680 681 682

/*
 * CREATE CAST
 */
void
CreateCast(CreateCastStmt *stmt)
{
	Oid			sourcetypeid;
	Oid			targettypeid;
	Oid			funcid;
683
	char		castcontext;
684
	Relation	relation;
685 686 687
	HeapTuple	tuple;
	Datum		values[Natts_pg_cast];
	char		nulls[Natts_pg_cast];
688
	ObjectAddress myself,
Bruce Momjian's avatar
Bruce Momjian committed
689
				referenced;
690 691 692 693 694 695 696 697 698 699 700 701 702 703

	sourcetypeid = LookupTypeName(stmt->sourcetype);
	if (!OidIsValid(sourcetypeid))
		elog(ERROR, "source data type %s does not exist",
			 TypeNameToString(stmt->sourcetype));

	targettypeid = LookupTypeName(stmt->targettype);
	if (!OidIsValid(targettypeid))
		elog(ERROR, "target data type %s does not exist",
			 TypeNameToString(stmt->targettype));

	if (sourcetypeid == targettypeid)
		elog(ERROR, "source data type and target data type are the same");

704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
	/* No shells, no pseudo-types allowed */
	if (!get_typisdefined(sourcetypeid))
		elog(ERROR, "source data type %s is only a shell",
			 TypeNameToString(stmt->sourcetype));

	if (!get_typisdefined(targettypeid))
		elog(ERROR, "target data type %s is only a shell",
			 TypeNameToString(stmt->targettype));

	if (get_typtype(sourcetypeid) == 'p')
		elog(ERROR, "source data type %s is a pseudo-type",
			 TypeNameToString(stmt->sourcetype));

	if (get_typtype(targettypeid) == 'p')
		elog(ERROR, "target data type %s is a pseudo-type",
			 TypeNameToString(stmt->targettype));

721 722 723 724 725 726
	if (!pg_type_ownercheck(sourcetypeid, GetUserId())
		&& !pg_type_ownercheck(targettypeid, GetUserId()))
		elog(ERROR, "must be owner of type %s or type %s",
			 TypeNameToString(stmt->sourcetype),
			 TypeNameToString(stmt->targettype));

727 728
	if (stmt->func != NULL)
	{
729 730
		Form_pg_proc procstruct;

731 732 733
		funcid = LookupFuncNameTypeNames(stmt->func->funcname,
										 stmt->func->funcargs,
										 "CreateCast");
734

735 736 737
		tuple = SearchSysCache(PROCOID,
							   ObjectIdGetDatum(funcid),
							   0, 0, 0);
738 739 740 741 742 743 744 745 746 747
		if (!HeapTupleIsValid(tuple))
			elog(ERROR, "cache lookup of function %u failed", funcid);

		procstruct = (Form_pg_proc) GETSTRUCT(tuple);
		if (procstruct->pronargs != 1)
			elog(ERROR, "cast function must take 1 argument");
		if (procstruct->proargtypes[0] != sourcetypeid)
			elog(ERROR, "argument of cast function must match source data type");
		if (procstruct->prorettype != targettypeid)
			elog(ERROR, "return data type of cast function must match target data type");
748 749
		if (procstruct->provolatile == PROVOLATILE_VOLATILE)
			elog(ERROR, "cast function must not be volatile");
750 751 752
		if (procstruct->proisagg)
			elog(ERROR, "cast function must not be an aggregate function");
		if (procstruct->proretset)
753
			elog(ERROR, "cast function must not return a set");
754 755 756 757 758

		ReleaseSysCache(tuple);
	}
	else
	{
759 760 761 762 763 764 765
		int16	typ1len;
		int16	typ2len;
		bool	typ1byval;
		bool	typ2byval;
		char	typ1align;
		char	typ2align;

766
		/* indicates binary coercibility */
767
		funcid = InvalidOid;
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787

		/*
		 * Must be superuser to create binary-compatible casts, since
		 * erroneous casts can easily crash the backend.
		 */
		if (!superuser())
			elog(ERROR, "Must be superuser to create a cast WITHOUT FUNCTION");

		/*
		 * Also, insist that the types match as to size, alignment, and
		 * pass-by-value attributes; this provides at least a crude check
		 * that they have similar representations.  A pair of types that
		 * fail this test should certainly not be equated.
		 */
		get_typlenbyvalalign(sourcetypeid, &typ1len, &typ1byval, &typ1align);
		get_typlenbyvalalign(targettypeid, &typ2len, &typ2byval, &typ2align);
		if (typ1len != typ2len ||
			typ1byval != typ2byval ||
			typ1align != typ2align)
			elog(ERROR, "source and target datatypes are not physically compatible");
788 789
	}

790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
	/* convert CoercionContext enum to char value for castcontext */
	switch (stmt->context)
	{
		case COERCION_IMPLICIT:
			castcontext = COERCION_CODE_IMPLICIT;
			break;
		case COERCION_ASSIGNMENT:
			castcontext = COERCION_CODE_ASSIGNMENT;
			break;
		case COERCION_EXPLICIT:
			castcontext = COERCION_CODE_EXPLICIT;
			break;
		default:
			elog(ERROR, "CreateCast: bogus CoercionContext %c", stmt->context);
			castcontext = 0;	/* keep compiler quiet */
			break;
	}

	relation = heap_openr(CastRelationName, RowExclusiveLock);

	/*
	 * Check for duplicate.  This is just to give a friendly error message,
	 * the unique index would catch it anyway (so no need to sweat about
	 * race conditions).
	 */
	tuple = SearchSysCache(CASTSOURCETARGET,
						   ObjectIdGetDatum(sourcetypeid),
						   ObjectIdGetDatum(targettypeid),
						   0, 0);
	if (HeapTupleIsValid(tuple))
		elog(ERROR, "cast from data type %s to data type %s already exists",
			 TypeNameToString(stmt->sourcetype),
			 TypeNameToString(stmt->targettype));

824
	/* ready to go */
Bruce Momjian's avatar
Bruce Momjian committed
825 826 827
	values[Anum_pg_cast_castsource - 1] = ObjectIdGetDatum(sourcetypeid);
	values[Anum_pg_cast_casttarget - 1] = ObjectIdGetDatum(targettypeid);
	values[Anum_pg_cast_castfunc - 1] = ObjectIdGetDatum(funcid);
828
	values[Anum_pg_cast_castcontext - 1] = CharGetDatum(castcontext);
829

830
	MemSet(nulls, ' ', Natts_pg_cast);
831 832 833

	tuple = heap_formtuple(RelationGetDescr(relation), values, nulls);

834
	simple_heap_insert(relation, tuple);
835

836
	CatalogUpdateIndexes(relation, tuple);
837

838
	/* make dependency entries */
839
	myself.classId = RelationGetRelid(relation);
840
	myself.objectId = HeapTupleGetOid(tuple);
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
	myself.objectSubId = 0;

	/* dependency on source type */
	referenced.classId = RelOid_pg_type;
	referenced.objectId = sourcetypeid;
	referenced.objectSubId = 0;
	recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);

	/* dependency on target type */
	referenced.classId = RelOid_pg_type;
	referenced.objectId = targettypeid;
	referenced.objectSubId = 0;
	recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);

	/* dependency on function */
	if (OidIsValid(funcid))
	{
		referenced.classId = RelOid_pg_proc;
		referenced.objectId = funcid;
		referenced.objectSubId = 0;
		recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
	}

	heap_freetuple(tuple);
865

866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
	heap_close(relation, RowExclusiveLock);
}



/*
 * DROP CAST
 */
void
DropCast(DropCastStmt *stmt)
{
	Oid			sourcetypeid;
	Oid			targettypeid;
	HeapTuple	tuple;
	ObjectAddress object;

	sourcetypeid = LookupTypeName(stmt->sourcetype);
	if (!OidIsValid(sourcetypeid))
		elog(ERROR, "source data type %s does not exist",
			 TypeNameToString(stmt->sourcetype));

	targettypeid = LookupTypeName(stmt->targettype);
	if (!OidIsValid(targettypeid))
		elog(ERROR, "target data type %s does not exist",
			 TypeNameToString(stmt->targettype));

	tuple = SearchSysCache(CASTSOURCETARGET,
Bruce Momjian's avatar
Bruce Momjian committed
893 894 895
						   ObjectIdGetDatum(sourcetypeid),
						   ObjectIdGetDatum(targettypeid),
						   0, 0);
896 897 898 899 900 901
	if (!HeapTupleIsValid(tuple))
		elog(ERROR, "cast from type %s to type %s does not exist",
			 TypeNameToString(stmt->sourcetype),
			 TypeNameToString(stmt->targettype));

	/* Permission check */
902 903 904 905 906
	if (!pg_type_ownercheck(sourcetypeid, GetUserId())
		&& !pg_type_ownercheck(targettypeid, GetUserId()))
		elog(ERROR, "must be owner of type %s or type %s",
			 TypeNameToString(stmt->sourcetype),
			 TypeNameToString(stmt->targettype));
907 908 909 910 911

	/*
	 * Do the deletion
	 */
	object.classId = get_system_catalog_relid(CastRelationName);
912
	object.objectId = HeapTupleGetOid(tuple);
913 914
	object.objectSubId = 0;

915 916
	ReleaseSysCache(tuple);

917 918 919 920 921 922 923
	performDeletion(&object, stmt->behavior);
}


void
DropCastById(Oid castOid)
{
924 925
	Relation	relation,
				index;
926
	ScanKeyData scankey;
927
	IndexScanDesc scan;
928 929 930
	HeapTuple	tuple;

	relation = heap_openr(CastRelationName, RowExclusiveLock);
931 932
	index = index_openr(CastOidIndex);

933
	ScanKeyEntryInitialize(&scankey, 0x0,
934 935 936
						   1, F_OIDEQ, ObjectIdGetDatum(castOid));
	scan = index_beginscan(relation, index, SnapshotNow, 1, &scankey);
	tuple = index_getnext(scan, ForwardScanDirection);
937 938 939 940
	if (HeapTupleIsValid(tuple))
		simple_heap_delete(relation, &tuple->t_self);
	else
		elog(ERROR, "could not find tuple for cast %u", castOid);
941 942 943
	index_endscan(scan);

	index_close(index);
944 945
	heap_close(relation, RowExclusiveLock);
}