catalog_utils.c 38.5 KB
Newer Older
1 2 3 4 5 6 7 8
/*-------------------------------------------------------------------------
 *
 * catalog_utils.c--
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
Thomas G. Lockhart's avatar
Thomas G. Lockhart committed
9
 *	  $Header: /cvsroot/pgsql/src/backend/parser/Attic/catalog_utils.c,v 1.27 1997/09/13 03:11:51 thomas Exp $
10 11 12
 *
 *-------------------------------------------------------------------------
 */
13
#include <string.h>
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#include "postgres.h"

#include "lib/dllist.h"
#include "utils/datum.h"

#include "utils/builtins.h"
#include "utils/elog.h"
#include "utils/palloc.h"
#include "fmgr.h"

#include "nodes/pg_list.h"
#include "nodes/parsenodes.h"
#include "utils/syscache.h"
#include "catalog/catname.h"

29
#include "parser/catalog_utils.h"
30
#include "catalog/pg_inherits.h"
31
#include "catalog/pg_operator.h"
32
#include "catalog/pg_type.h"
33
#include "catalog/pg_proc.h"
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#include "catalog/indexing.h"
#include "catalog/catname.h"

#include "access/skey.h"
#include "access/relscan.h"
#include "access/tupdesc.h"
#include "access/htup.h"
#include "access/heapam.h"
#include "access/genam.h"
#include "access/itup.h"
#include "access/tupmacs.h"

#include "storage/buf.h"
#include "storage/bufmgr.h"
#include "utils/lsyscache.h"
#include "storage/lmgr.h"

51 52 53 54
#include "port-protos.h"		/* strdup() */

struct
{
55 56 57
	char	   *field;
	int			code;
}			special_attr[] =
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92

{
	{
		"ctid", SelfItemPointerAttributeNumber
	},
	{
		"oid", ObjectIdAttributeNumber
	},
	{
		"xmin", MinTransactionIdAttributeNumber
	},
	{
		"cmin", MinCommandIdAttributeNumber
	},
	{
		"xmax", MaxTransactionIdAttributeNumber
	},
	{
		"cmax", MaxCommandIdAttributeNumber
	},
	{
		"chain", ChainItemPointerAttributeNumber
	},
	{
		"anchor", AnchorItemPointerAttributeNumber
	},
	{
		"tmin", MinAbsoluteTimeAttributeNumber
	},
	{
		"tmax", MaxAbsoluteTimeAttributeNumber
	},
	{
		"vtype", VersionTypeAttributeNumber
	}
93 94 95
};

#define SPECIALS (sizeof(special_attr)/sizeof(*special_attr))
96

97
static char *attnum_type[SPECIALS] = {
98 99 100 101 102 103 104 105 106 107 108 109 110 111
	"tid",
	"oid",
	"xid",
	"cid",
	"xid",
	"cid",
	"tid",
	"tid",
	"abstime",
	"abstime",
	"char"
};

#define MAXFARGS 8				/* max # args to a c or postquel function */
112 113

/*
114 115 116
 *	This structure is used to explore the inheritance hierarchy above
 *	nodes in the type tree in order to disambiguate among polymorphic
 *	functions.
117 118
 */

119 120
typedef struct _InhPaths
{
121 122 123
	int			nsupers;		/* number of superclasses */
	Oid			self;			/* this class */
	Oid		   *supervec;		/* vector of superclasses */
124
} InhPaths;
125 126

/*
127 128
 *	This structure holds a list of possible functions or operators that
 *	agree with the known name and argument types of the function/operator.
129
 */
130 131
typedef struct _CandidateList
{
132
	Oid		   *args;
133
	struct _CandidateList *next;
134
}		   *CandidateList;
135

136 137 138
static Oid **argtype_inherit(int nargs, Oid *oid_array);
static Oid **genxprod(InhPaths *arginh, int nargs);
static int	findsupers(Oid relid, Oid **supervec);
139 140 141
static bool check_typeid(Oid id);
static char *instr1(TypeTupleForm tp, char *string, int typlen);
static void op_error(char *op, Oid arg1, Oid arg2);
142

143
/* check to see if a type id is valid,
144
 * returns true if it is. By using this call before calling
145 146
 * get_id_type or get_id_typname, more meaningful error messages
 * can be produced because the caller typically has more context of
147
 *	what's going on                 - jolly
148
 */
149
static bool
150
check_typeid(Oid id)
151
{
152 153 154
	return (SearchSysCacheTuple(TYPOID,
								ObjectIdGetDatum(id),
								0, 0, 0) != NULL);
155 156 157 158 159
}


/* return a Type structure, given an typid */
Type
160
get_id_type(Oid id)
161
{
162
	HeapTuple	tup;
163 164 165 166 167 168 169 170

	if (!(tup = SearchSysCacheTuple(TYPOID, ObjectIdGetDatum(id),
									0, 0, 0)))
	{
		elog(WARN, "type id lookup of %ud failed", id);
		return (NULL);
	}
	return ((Type) tup);
171 172 173
}

/* return a type name, given a typeid */
174
char	   *
175
get_id_typname(Oid id)
176
{
177 178
	HeapTuple	tup;
	TypeTupleForm typetuple;
179 180 181 182 183 184 185 186 187

	if (!(tup = SearchSysCacheTuple(TYPOID, ObjectIdGetDatum(id),
									0, 0, 0)))
	{
		elog(WARN, "type id lookup of %ud failed", id);
		return (NULL);
	}
	typetuple = (TypeTupleForm) GETSTRUCT(tup);
	return (typetuple->typname).data;
188 189 190 191 192 193
}

/* return a Type structure, given type name */
Type
type(char *s)
{
194
	HeapTuple	tup;
195 196 197 198 199 200 201 202 203 204 205

	if (s == NULL)
	{
		elog(WARN, "type(): Null type");
	}

	if (!(tup = SearchSysCacheTuple(TYPNAME, PointerGetDatum(s), 0, 0, 0)))
	{
		elog(WARN, "type name lookup of %s failed", s);
	}
	return ((Type) tup);
206 207 208 209 210 211 212
}

/* given attribute id, return type of that attribute */
/* XXX Special case for pseudo-attributes is a hack */
Oid
att_typeid(Relation rd, int attid)
{
213 214 215 216 217 218 219 220 221 222 223

	if (attid < 0)
	{
		return (typeid(type(attnum_type[-attid - 1])));
	}

	/*
	 * -1 because varattno (where attid comes from) returns one more than
	 * index
	 */
	return (rd->rd_att->attrs[attid - 1]->atttypid);
224 225 226 227 228 229
}


int
att_attnelems(Relation rd, int attid)
{
230
	return (rd->rd_att->attrs[attid - 1]->attnelems);
231 232 233 234 235 236
}

/* given type, return the type OID */
Oid
typeid(Type tp)
{
237 238 239 240 241
	if (tp == NULL)
	{
		elog(WARN, "typeid() called with NULL type struct");
	}
	return (tp->t_oid);
242 243 244 245 246 247
}

/* given type (as type struct), return the length of type */
int16
tlen(Type t)
{
248
	TypeTupleForm typ;
249 250 251

	typ = (TypeTupleForm) GETSTRUCT(t);
	return (typ->typlen);
252 253 254 255 256 257
}

/* given type (as type struct), return the value of its 'byval' attribute.*/
bool
tbyval(Type t)
{
258
	TypeTupleForm typ;
259 260 261

	typ = (TypeTupleForm) GETSTRUCT(t);
	return (typ->typbyval);
262 263 264
}

/* given type (as type struct), return the name of type */
265
char	   *
266 267
tname(Type t)
{
268
	TypeTupleForm typ;
269 270 271

	typ = (TypeTupleForm) GETSTRUCT(t);
	return (typ->typname).data;
272 273 274 275 276 277
}

/* given type (as type struct), return wether type is passed by value */
int
tbyvalue(Type t)
{
278
	TypeTupleForm typ;
279 280 281

	typ = (TypeTupleForm) GETSTRUCT(t);
	return (typ->typbyval);
282 283 284
}

/* given a type, return its typetype ('c' for 'c'atalog types) */
285
static char
286 287
typetypetype(Type t)
{
288
	TypeTupleForm typ;
289 290 291

	typ = (TypeTupleForm) GETSTRUCT(t);
	return (typ->typtype);
292 293 294 295 296 297
}

/* given operator, return the operator OID */
Oid
oprid(Operator op)
{
298
	return (op->t_oid);
299 300 301
}

/*
302 303 304 305
 *	given opname, leftTypeId and rightTypeId,
 *	find all possible (arg1, arg2) pairs for which an operator named
 *	opname exists, such that leftTypeId can be coerced to arg1 and
 *	rightTypeId can be coerced to arg2
306 307 308
 */
static int
binary_oper_get_candidates(char *opname,
309 310
						   Oid leftTypeId,
						   Oid rightTypeId,
311
						   CandidateList *candidates)
312
{
313 314 315 316
	CandidateList current_candidate;
	Relation	pg_operator_desc;
	HeapScanDesc pg_operator_scan;
	HeapTuple	tup;
317
	OperatorTupleForm oper;
318 319 320 321
	Buffer		buffer;
	int			nkeys;
	int			ncandidates = 0;
	ScanKeyData opKey[3];
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 351 352 353 354 355 356 357 358 359

	*candidates = NULL;

	ScanKeyEntryInitialize(&opKey[0], 0,
						   Anum_pg_operator_oprname,
						   NameEqualRegProcedure,
						   NameGetDatum(opname));

	ScanKeyEntryInitialize(&opKey[1], 0,
						   Anum_pg_operator_oprkind,
						   CharacterEqualRegProcedure,
						   CharGetDatum('b'));


	if (leftTypeId == UNKNOWNOID)
	{
		if (rightTypeId == UNKNOWNOID)
		{
			nkeys = 2;
		}
		else
		{
			nkeys = 3;

			ScanKeyEntryInitialize(&opKey[2], 0,
								   Anum_pg_operator_oprright,
								   ObjectIdEqualRegProcedure,
								   ObjectIdGetDatum(rightTypeId));
		}
	}
	else if (rightTypeId == UNKNOWNOID)
	{
		nkeys = 3;

		ScanKeyEntryInitialize(&opKey[2], 0,
							   Anum_pg_operator_oprleft,
							   ObjectIdEqualRegProcedure,
							   ObjectIdGetDatum(leftTypeId));
360
	}
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
	else
	{
		/* currently only "unknown" can be coerced */
		return 0;
	}

	pg_operator_desc = heap_openr(OperatorRelationName);
	pg_operator_scan = heap_beginscan(pg_operator_desc,
									  0,
									  SelfTimeQual,
									  nkeys,
									  opKey);

	do
	{
		tup = heap_getnext(pg_operator_scan, 0, &buffer);
		if (HeapTupleIsValid(tup))
		{
			current_candidate = (CandidateList) palloc(sizeof(struct _CandidateList));
			current_candidate->args = (Oid *) palloc(2 * sizeof(Oid));

			oper = (OperatorTupleForm) GETSTRUCT(tup);
			current_candidate->args[0] = oper->oprleft;
			current_candidate->args[1] = oper->oprright;
			current_candidate->next = *candidates;
			*candidates = current_candidate;
			ncandidates++;
			ReleaseBuffer(buffer);
		}
	} while (HeapTupleIsValid(tup));

	heap_endscan(pg_operator_scan);
	heap_close(pg_operator_desc);

	return ncandidates;
396 397 398 399
}

/*
 * equivalentOpersAfterPromotion -
400 401 402 403 404 405
 *	  checks if a list of candidate operators obtained from
 *	  binary_oper_get_candidates() contain equivalent operators. If
 *	  this routine is called, we have more than 1 candidate and need to
 *	  decided whether to pick one of them. This routine returns true if
 *	  the all the candidates operate on the same data types after
 *	  promotion (int2, int4, float4 -> float8).
406
 */
407
static bool
408 409
equivalentOpersAfterPromotion(CandidateList candidates)
{
410 411 412 413
	CandidateList result;
	CandidateList promotedCandidates = NULL;
	Oid			leftarg,
				rightarg;
414 415 416

	for (result = candidates; result != NULL; result = result->next)
	{
417
		CandidateList c;
418 419 420 421 422

		c = (CandidateList) palloc(sizeof(*c));
		c->args = (Oid *) palloc(2 * sizeof(Oid));
		switch (result->args[0])
		{
423 424 425 426 427 428 429 430 431
			case FLOAT4OID:
			case INT4OID:
			case INT2OID:
			case CASHOID:
				c->args[0] = FLOAT8OID;
				break;
			default:
				c->args[0] = result->args[0];
				break;
432 433 434
		}
		switch (result->args[1])
		{
435 436 437 438 439 440 441 442 443
			case FLOAT4OID:
			case INT4OID:
			case INT2OID:
			case CASHOID:
				c->args[1] = FLOAT8OID;
				break;
			default:
				c->args[1] = result->args[1];
				break;
444 445 446
		}
		c->next = promotedCandidates;
		promotedCandidates = c;
447
	}
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465

	/*
	 * if we get called, we have more than 1 candidates so we can do the
	 * following safely
	 */
	leftarg = promotedCandidates->args[0];
	rightarg = promotedCandidates->args[1];

	for (result = promotedCandidates->next; result != NULL; result = result->next)
	{
		if (result->args[0] != leftarg || result->args[1] != rightarg)

			/*
			 * this list contains operators that operate on different data
			 * types even after promotion. Hence we can't decide on which
			 * one to pick. The user must do explicit type casting.
			 */
			return FALSE;
466
	}
467 468 469 470 471 472 473

	/*
	 * all the candidates are equivalent in the following sense: they
	 * operate on equivalent data types and picking any one of them is as
	 * good.
	 */
	return TRUE;
474
}
475

476 477

/*
478 479
 *	given a choice of argument type pairs for a binary operator,
 *	try to choose a default pair
480
 */
481
static CandidateList
482
binary_oper_select_candidate(Oid arg1,
483 484
							 Oid arg2,
							 CandidateList candidates)
485
{
486
	CandidateList result;
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531

	/*
	 * if both are "unknown", there is no way to select a candidate
	 *
	 * current wisdom holds that the default operator should be one in which
	 * both operands have the same type (there will only be one such
	 * operator)
	 *
	 * 7.27.93 - I have decided not to do this; it's too hard to justify, and
	 * it's easy enough to typecast explicitly -avi [the rest of this
	 * routine were commented out since then -ay]
	 */

	if (arg1 == UNKNOWNOID && arg2 == UNKNOWNOID)
		return (NULL);

	/*
	 * 6/23/95 - I don't complete agree with avi. In particular, casting
	 * floats is a pain for users. Whatever the rationale behind not doing
	 * this is, I need the following special case to work.
	 *
	 * In the WHERE clause of a query, if a float is specified without
	 * quotes, we treat it as float8. I added the float48* operators so
	 * that we can operate on float4 and float8. But now we have more than
	 * one matching operator if the right arg is unknown (eg. float
	 * specified with quotes). This break some stuff in the regression
	 * test where there are floats in quotes not properly casted. Below is
	 * the solution. In addition to requiring the operator operates on the
	 * same type for both operands [as in the code Avi originally
	 * commented out], we also require that the operators be equivalent in
	 * some sense. (see equivalentOpersAfterPromotion for details.) - ay
	 * 6/95
	 */
	if (!equivalentOpersAfterPromotion(candidates))
		return NULL;

	/*
	 * if we get here, any one will do but we're more picky and require
	 * both operands be the same.
	 */
	for (result = candidates; result != NULL; result = result->next)
	{
		if (result->args[0] == result->args[1])
			return result;
	}
532

533
	return (NULL);
534 535 536 537 538
}

/* Given operator, types of arg1, and arg2, return oper struct */
/* arg1, arg2 --typeids */
Operator
539
oper(char *op, Oid arg1, Oid arg2, bool noWarnings)
540
{
541 542 543
	HeapTuple	tup;
	CandidateList candidates;
	int			ncandidates;
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598

	if (!arg2)
		arg2 = arg1;
	if (!arg1)
		arg1 = arg2;

	if (!(tup = SearchSysCacheTuple(OPRNAME,
									PointerGetDatum(op),
									ObjectIdGetDatum(arg1),
									ObjectIdGetDatum(arg2),
									Int8GetDatum('b'))))
	{
		ncandidates = binary_oper_get_candidates(op, arg1, arg2, &candidates);
		if (ncandidates == 0)
		{

			/*
			 * no operators of the desired types found
			 */
			if (!noWarnings)
				op_error(op, arg1, arg2);
			return (NULL);
		}
		else if (ncandidates == 1)
		{

			/*
			 * exactly one operator of the desired types found
			 */
			tup = SearchSysCacheTuple(OPRNAME,
									  PointerGetDatum(op),
								   ObjectIdGetDatum(candidates->args[0]),
								   ObjectIdGetDatum(candidates->args[1]),
									  Int8GetDatum('b'));
			Assert(HeapTupleIsValid(tup));
		}
		else
		{

			/*
			 * multiple operators of the desired types found
			 */
			candidates = binary_oper_select_candidate(arg1, arg2, candidates);
			if (candidates != NULL)
			{
				/* we chose one of them */
				tup = SearchSysCacheTuple(OPRNAME,
										  PointerGetDatum(op),
								   ObjectIdGetDatum(candidates->args[0]),
								   ObjectIdGetDatum(candidates->args[1]),
										  Int8GetDatum('b'));
				Assert(HeapTupleIsValid(tup));
			}
			else
			{
599 600
				Type		tp1,
							tp2;
601 602 603 604 605 606 607 608 609 610 611 612 613

				/* we chose none of them */
				tp1 = get_id_type(arg1);
				tp2 = get_id_type(arg2);
				if (!noWarnings)
				{
					elog(NOTICE, "there is more than one operator %s for types", op);
					elog(NOTICE, "%s and %s. You will have to retype this query",
						 tname(tp1), tname(tp2));
					elog(WARN, "using an explicit cast");
				}
				return (NULL);
			}
614
		}
615
	}
616
	return ((Operator) tup);
617 618 619
}

/*
620 621 622
 *	given opname and typeId, find all possible types for which
 *	a right/left unary operator named opname exists,
 *	such that typeId can be coerced to it
623 624 625
 */
static int
unary_oper_get_candidates(char *op,
626
						  Oid typeId,
627
						  CandidateList *candidates,
628
						  char rightleft)
629
{
630 631 632 633
	CandidateList current_candidate;
	Relation	pg_operator_desc;
	HeapScanDesc pg_operator_scan;
	HeapTuple	tup;
634
	OperatorTupleForm oper;
635 636
	Buffer		buffer;
	int			ncandidates = 0;
637 638 639 640 641 642 643

	static ScanKeyData opKey[2] = {
		{0, Anum_pg_operator_oprname, NameEqualRegProcedure},
	{0, Anum_pg_operator_oprkind, CharacterEqualRegProcedure}};

	*candidates = NULL;

644
	fmgr_info(NameEqualRegProcedure, (func_ptr *) &opKey[0].sk_func,
645 646
			  &opKey[0].sk_nargs);
	opKey[0].sk_argument = NameGetDatum(op);
647
	fmgr_info(CharacterEqualRegProcedure, (func_ptr *) &opKey[1].sk_func,
648 649 650 651 652 653 654 655 656 657 658 659
			  &opKey[1].sk_nargs);
	opKey[1].sk_argument = CharGetDatum(rightleft);

	/* currently, only "unknown" can be coerced */

	/*
	 * but we should allow types that are internally the same to be
	 * "coerced"
	 */
	if (typeId != UNKNOWNOID)
	{
		return 0;
660
	}
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692

	pg_operator_desc = heap_openr(OperatorRelationName);
	pg_operator_scan = heap_beginscan(pg_operator_desc,
									  0,
									  SelfTimeQual,
									  2,
									  opKey);

	do
	{
		tup = heap_getnext(pg_operator_scan, 0, &buffer);
		if (HeapTupleIsValid(tup))
		{
			current_candidate = (CandidateList) palloc(sizeof(struct _CandidateList));
			current_candidate->args = (Oid *) palloc(sizeof(Oid));

			oper = (OperatorTupleForm) GETSTRUCT(tup);
			if (rightleft == 'r')
				current_candidate->args[0] = oper->oprleft;
			else
				current_candidate->args[0] = oper->oprright;
			current_candidate->next = *candidates;
			*candidates = current_candidate;
			ncandidates++;
			ReleaseBuffer(buffer);
		}
	} while (HeapTupleIsValid(tup));

	heap_endscan(pg_operator_scan);
	heap_close(pg_operator_desc);

	return ncandidates;
693 694 695 696 697
}

/* Given unary right-side operator (operator on right), return oper struct */
/* arg-- type id */
Operator
698
right_oper(char *op, Oid arg)
699
{
700 701 702
	HeapTuple	tup;
	CandidateList candidates;
	int			ncandidates;
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735

	/*
	 * if (!OpCache) { init_op_cache(); }
	 */
	if (!(tup = SearchSysCacheTuple(OPRNAME,
									PointerGetDatum(op),
									ObjectIdGetDatum(arg),
									ObjectIdGetDatum(InvalidOid),
									Int8GetDatum('r'))))
	{
		ncandidates = unary_oper_get_candidates(op, arg, &candidates, 'r');
		if (ncandidates == 0)
		{
			elog(WARN,
				 "Can't find right op: %s for type %d", op, arg);
			return (NULL);
		}
		else if (ncandidates == 1)
		{
			tup = SearchSysCacheTuple(OPRNAME,
									  PointerGetDatum(op),
								   ObjectIdGetDatum(candidates->args[0]),
									  ObjectIdGetDatum(InvalidOid),
									  Int8GetDatum('r'));
			Assert(HeapTupleIsValid(tup));
		}
		else
		{
			elog(NOTICE, "there is more than one right operator %s", op);
			elog(NOTICE, "you will have to retype this query");
			elog(WARN, "using an explicit cast");
			return (NULL);
		}
736
	}
737
	return ((Operator) tup);
738 739 740 741 742
}

/* Given unary left-side operator (operator on left), return oper struct */
/* arg--type id */
Operator
743
left_oper(char *op, Oid arg)
744
{
745 746 747
	HeapTuple	tup;
	CandidateList candidates;
	int			ncandidates;
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780

	/*
	 * if (!OpCache) { init_op_cache(); }
	 */
	if (!(tup = SearchSysCacheTuple(OPRNAME,
									PointerGetDatum(op),
									ObjectIdGetDatum(InvalidOid),
									ObjectIdGetDatum(arg),
									Int8GetDatum('l'))))
	{
		ncandidates = unary_oper_get_candidates(op, arg, &candidates, 'l');
		if (ncandidates == 0)
		{
			elog(WARN,
				 "Can't find left op: %s for type %d", op, arg);
			return (NULL);
		}
		else if (ncandidates == 1)
		{
			tup = SearchSysCacheTuple(OPRNAME,
									  PointerGetDatum(op),
									  ObjectIdGetDatum(InvalidOid),
								   ObjectIdGetDatum(candidates->args[0]),
									  Int8GetDatum('l'));
			Assert(HeapTupleIsValid(tup));
		}
		else
		{
			elog(NOTICE, "there is more than one left operator %s", op);
			elog(NOTICE, "you will have to retype this query");
			elog(WARN, "using an explicit cast");
			return (NULL);
		}
781
	}
782
	return ((Operator) tup);
783 784 785 786 787 788 789
}

/* given range variable, return id of variable */

int
varattno(Relation rd, char *a)
{
790
	int			i;
791 792 793 794 795 796 797

	for (i = 0; i < rd->rd_rel->relnatts; i++)
	{
		if (!namestrcmp(&(rd->rd_att->attrs[i]->attname), a))
		{
			return (i + 1);
		}
798
	}
799 800 801 802 803 804
	for (i = 0; i < SPECIALS; i++)
	{
		if (!strcmp(special_attr[i].field, a))
		{
			return (special_attr[i].code);
		}
805
	}
806

Thomas G. Lockhart's avatar
Thomas G. Lockhart committed
807
	elog(WARN, "Relation %s does not have attribute %s",
808 809
		 RelationGetRelationName(rd), a);
	return (-1);
810 811 812 813 814 815 816 817 818 819
}

/* Given range variable, return whether attribute of this name
 * is a set.
 * NOTE the ASSUMPTION here that no system attributes are, or ever
 * will be, sets.
 */
bool
varisset(Relation rd, char *name)
{
820
	int			i;
821 822 823 824 825 826 827 828

	/* First check if this is a system attribute */
	for (i = 0; i < SPECIALS; i++)
	{
		if (!strcmp(special_attr[i].field, name))
		{
			return (false);		/* no sys attr is a set */
		}
829
	}
830
	return (get_attisset(rd->rd_id, name));
831 832 833 834 835 836
}

/* given range variable, return id of variable */
int
nf_varattno(Relation rd, char *a)
{
837
	int			i;
838 839 840 841 842 843 844

	for (i = 0; i < rd->rd_rel->relnatts; i++)
	{
		if (!namestrcmp(&(rd->rd_att->attrs[i]->attname), a))
		{
			return (i + 1);
		}
845
	}
846 847 848 849 850 851
	for (i = 0; i < SPECIALS; i++)
	{
		if (!strcmp(special_attr[i].field, a))
		{
			return (special_attr[i].code);
		}
852
	}
853
	return InvalidAttrNumber;
854 855 856 857 858
}

/*-------------
 * given an attribute number and a relation, return its relation name
 */
859
char	   *
860 861
getAttrName(Relation rd, int attrno)
{
862 863
	char	   *name;
	int			i;
864 865 866 867 868 869 870 871 872 873 874

	if (attrno < 0)
	{
		for (i = 0; i < SPECIALS; i++)
		{
			if (special_attr[i].code == attrno)
			{
				name = special_attr[i].field;
				return (name);
			}
		}
Thomas G. Lockhart's avatar
Thomas G. Lockhart committed
875
		elog(WARN, "Illegal attr no %d for relation %s",
876 877 878 879 880 881 882 883 884
			 attrno, RelationGetRelationName(rd));
	}
	else if (attrno >= 1 && attrno <= RelationGetNumberOfAttributes(rd))
	{
		name = (rd->rd_att->attrs[attrno - 1]->attname).data;
		return (name);
	}
	else
	{
Thomas G. Lockhart's avatar
Thomas G. Lockhart committed
885
		elog(WARN, "Illegal attr no %d for relation %s",
886
			 attrno, RelationGetRelationName(rd));
887
	}
888 889 890 891 892 893

	/*
	 * Shouldn't get here, but we want lint to be happy...
	 */

	return (NULL);
894 895 896 897
}

/* Given a typename and value, returns the ascii form of the value */

898
#ifdef NOT_USED
899
char	   *
900 901
outstr(char *typename,			/* Name of type of value */
	   char *value)				/* Could be of any type */
902
{
903 904
	TypeTupleForm tp;
	Oid			op;
905 906 907 908

	tp = (TypeTupleForm) GETSTRUCT(type(typename));
	op = tp->typoutput;
	return ((char *) fmgr(op, value));
909
}
910

911
#endif
912 913

/* Given a Type and a string, return the internal form of that string */
914
char	   *
915 916
instr2(Type tp, char *string, int typlen)
{
917
	return (instr1((TypeTupleForm) GETSTRUCT(tp), string, typlen));
918 919 920 921
}

/* Given a type structure and a string, returns the internal form of
   that string */
922
static char *
923 924
instr1(TypeTupleForm tp, char *string, int typlen)
{
925 926
	Oid			op;
	Oid			typelem;
927 928 929 930 931

	op = tp->typinput;
	typelem = tp->typelem;		/* XXX - used for array_in */
	/* typlen is for bpcharin() and varcharin() */
	return ((char *) fmgr(op, string, typelem, typlen));
932 933 934 935 936 937 938 939
}

/* Given the attribute type of an array return the arrtribute type of
   an element of the array */

Oid
GetArrayElementType(Oid typearray)
{
940 941
	HeapTuple	type_tuple;
	TypeTupleForm type_struct_array;
942 943 944 945 946 947

	type_tuple = SearchSysCacheTuple(TYPOID,
									 ObjectIdGetDatum(typearray),
									 0, 0, 0);

	if (!HeapTupleIsValid(type_tuple))
Thomas G. Lockhart's avatar
Thomas G. Lockhart committed
948
		elog(WARN, "GetArrayElementType: Cache lookup failed for type %d",
949 950 951 952 953 954 955 956
			 typearray);

	/* get the array type struct from the type tuple */
	type_struct_array = (TypeTupleForm) GETSTRUCT(type_tuple);

	if (type_struct_array->typelem == InvalidOid)
	{
		elog(WARN, "GetArrayElementType: type %s is not an array",
957
			 (Name) &(type_struct_array->typname.data[0]));
958 959 960
	}

	return (type_struct_array->typelem);
961 962 963 964 965
}

Oid
funcid_get_rettype(Oid funcid)
{
966 967
	HeapTuple	func_tuple = NULL;
	Oid			funcrettype = (Oid) 0;
968 969 970 971 972 973 974 975 976 977 978

	func_tuple = SearchSysCacheTuple(PROOID, ObjectIdGetDatum(funcid),
									 0, 0, 0);

	if (!HeapTupleIsValid(func_tuple))
		elog(WARN, "function  %d does not exist", funcid);

	funcrettype = (Oid)
		((Form_pg_proc) GETSTRUCT(func_tuple))->prorettype;

	return (funcrettype);
979 980 981 982 983 984
}

/*
 * get a list of all argument type vectors for which a function named
 * funcname taking nargs arguments exists
 */
985
static CandidateList
986 987
func_get_candidates(char *funcname, int nargs)
{
988 989 990 991 992
	Relation	heapRelation;
	Relation	idesc;
	ScanKeyData skey;
	HeapTuple	tuple;
	IndexScanDesc sd;
993
	RetrieveIndexResult indexRes;
994 995 996 997 998 999
	Buffer		buffer;
	Form_pg_proc pgProcP;
	bool		bufferUsed = FALSE;
	CandidateList candidates = NULL;
	CandidateList current_candidate;
	int			i;
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018

	heapRelation = heap_openr(ProcedureRelationName);
	ScanKeyEntryInitialize(&skey,
						   (bits16) 0x0,
						   (AttrNumber) 1,
						   (RegProcedure) NameEqualRegProcedure,
						   (Datum) funcname);

	idesc = index_openr(ProcedureNameIndex);

	sd = index_beginscan(idesc, false, 1, &skey);

	do
	{
		tuple = (HeapTuple) NULL;
		if (bufferUsed)
		{
			ReleaseBuffer(buffer);
			bufferUsed = FALSE;
1019
		}
1020 1021 1022 1023

		indexRes = index_getnext(sd, ForwardScanDirection);
		if (indexRes)
		{
1024
			ItemPointer iptr;
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057

			iptr = &indexRes->heap_iptr;
			tuple = heap_fetch(heapRelation, NowTimeQual, iptr, &buffer);
			pfree(indexRes);
			if (HeapTupleIsValid(tuple))
			{
				pgProcP = (Form_pg_proc) GETSTRUCT(tuple);
				bufferUsed = TRUE;
				if (pgProcP->pronargs == nargs)
				{
					current_candidate = (CandidateList)
						palloc(sizeof(struct _CandidateList));
					current_candidate->args = (Oid *)
						palloc(8 * sizeof(Oid));
					memset(current_candidate->args, 0, 8 * sizeof(Oid));
					for (i = 0; i < nargs; i++)
					{
						current_candidate->args[i] =
							pgProcP->proargtypes[i];
					}

					current_candidate->next = candidates;
					candidates = current_candidate;
				}
			}
		}
	} while (indexRes);

	index_endscan(sd);
	index_close(idesc);
	heap_close(heapRelation);

	return candidates;
1058 1059 1060 1061 1062
}

/*
 * can input_typeids be coerced to func_typeids?
 */
1063
static bool
1064
can_coerce(int nargs, Oid *input_typeids, Oid *func_typeids)
1065
{
1066 1067
	int			i;
	Type		tp;
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090

	/*
	 * right now, we only coerce "unknown", and we cannot coerce it to a
	 * relation type
	 */
	for (i = 0; i < nargs; i++)
	{
		if (input_typeids[i] != func_typeids[i])
		{
			if ((input_typeids[i] == BPCHAROID && func_typeids[i] == TEXTOID) ||
				(input_typeids[i] == BPCHAROID && func_typeids[i] == VARCHAROID) ||
				(input_typeids[i] == VARCHAROID && func_typeids[i] == TEXTOID) ||
				(input_typeids[i] == VARCHAROID && func_typeids[i] == BPCHAROID) ||
			(input_typeids[i] == CASHOID && func_typeids[i] == INT4OID) ||
			 (input_typeids[i] == INT4OID && func_typeids[i] == CASHOID))
				;				/* these are OK */
			else if (input_typeids[i] != UNKNOWNOID || func_typeids[i] == 0)
				return false;

			tp = get_id_type(input_typeids[i]);
			if (typetypetype(tp) == 'c')
				return false;
		}
1091
	}
1092 1093

	return true;
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
}

/*
 * given a list of possible typeid arrays to a function and an array of
 * input typeids, produce a shortlist of those function typeid arrays
 * that match the input typeids (either exactly or by coercion), and
 * return the number of such arrays
 */
static int
match_argtypes(int nargs,
1104
			   Oid *input_typeids,
1105
			   CandidateList function_typeids,
1106
			   CandidateList *candidates)		/* return value */
1107
{
1108 1109 1110 1111
	CandidateList current_candidate;
	CandidateList matching_candidate;
	Oid		   *current_typeids;
	int			ncandidates = 0;
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128

	*candidates = NULL;

	for (current_candidate = function_typeids;
		 current_candidate != NULL;
		 current_candidate = current_candidate->next)
	{
		current_typeids = current_candidate->args;
		if (can_coerce(nargs, input_typeids, current_typeids))
		{
			matching_candidate = (CandidateList)
				palloc(sizeof(struct _CandidateList));
			matching_candidate->args = current_typeids;
			matching_candidate->next = *candidates;
			*candidates = matching_candidate;
			ncandidates++;
		}
1129
	}
1130 1131

	return ncandidates;
1132 1133 1134 1135 1136 1137 1138 1139
}

/*
 * given the input argtype array and more than one candidate
 * for the function argtype array, attempt to resolve the conflict.
 * returns the selected argtype array if the conflict can be resolved,
 * otherwise returns NULL
 */
1140
static Oid *
1141
func_select_candidate(int nargs,
1142
					  Oid *input_typeids,
1143
					  CandidateList candidates)
1144
{
1145 1146
	/* XXX no conflict resolution implemeneted yet */
	return (NULL);
1147 1148 1149 1150
}

bool
func_get_detail(char *funcname,
1151
				int nargs,
1152 1153 1154 1155 1156
				Oid *oid_array,
				Oid *funcid,	/* return value */
				Oid *rettype,	/* return value */
				bool *retset,	/* return value */
				Oid **true_typeids)		/* return value */
1157
{
1158 1159 1160 1161 1162 1163
	Oid		  **input_typeid_vector;
	Oid		   *current_input_typeids;
	CandidateList function_typeids;
	CandidateList current_function_typeids;
	HeapTuple	ftup;
	Form_pg_proc pform;
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193

	/*
	 * attempt to find named function in the system catalogs with
	 * arguments exactly as specified - so that the normal case is just as
	 * quick as before
	 */
	ftup = SearchSysCacheTuple(PRONAME,
							   PointerGetDatum(funcname),
							   Int32GetDatum(nargs),
							   PointerGetDatum(oid_array),
							   0);
	*true_typeids = oid_array;

	/*
	 * If an exact match isn't found : 1) get a vector of all possible
	 * input arg type arrays constructed from the superclasses of the
	 * original input arg types 2) get a list of all possible argument
	 * type arrays to the function with given name and number of arguments
	 * 3) for each input arg type array from vector #1 : a) find how many
	 * of the function arg type arrays from list #2 it can be coerced to
	 * b) - if the answer is one, we have our function - if the answer is
	 * more than one, attempt to resolve the conflict - if the answer is
	 * zero, try the next array from vector #1
	 */
	if (!HeapTupleIsValid(ftup))
	{
		function_typeids = func_get_candidates(funcname, nargs);

		if (function_typeids != NULL)
		{
1194
			int			ncandidates = 0;
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241

			input_typeid_vector = argtype_inherit(nargs, oid_array);
			current_input_typeids = oid_array;

			do
			{
				ncandidates = match_argtypes(nargs, current_input_typeids,
											 function_typeids,
											 &current_function_typeids);
				if (ncandidates == 1)
				{
					*true_typeids = current_function_typeids->args;
					ftup = SearchSysCacheTuple(PRONAME,
											   PointerGetDatum(funcname),
											   Int32GetDatum(nargs),
										  PointerGetDatum(*true_typeids),
											   0);
					Assert(HeapTupleIsValid(ftup));
				}
				else if (ncandidates > 1)
				{
					*true_typeids =
						func_select_candidate(nargs,
											  current_input_typeids,
											  current_function_typeids);
					if (*true_typeids == NULL)
					{
						elog(NOTICE, "there is more than one function named \"%s\"",
							 funcname);
						elog(NOTICE, "that satisfies the given argument types. you will have to");
						elog(NOTICE, "retype your query using explicit typecasts.");
						func_error("func_get_detail", funcname, nargs, oid_array);
					}
					else
					{
						ftup = SearchSysCacheTuple(PRONAME,
											   PointerGetDatum(funcname),
												   Int32GetDatum(nargs),
										  PointerGetDatum(*true_typeids),
												   0);
						Assert(HeapTupleIsValid(ftup));
					}
				}
				current_input_typeids = *input_typeid_vector++;
			}
			while (current_input_typeids !=
				   InvalidOid && ncandidates == 0);
1242
		}
1243 1244 1245 1246
	}

	if (!HeapTupleIsValid(ftup))
	{
1247
		Type		tp;
1248 1249 1250 1251 1252 1253 1254

		if (nargs == 1)
		{
			tp = get_id_type(oid_array[0]);
			if (typetypetype(tp) == 'c')
				elog(WARN, "no such attribute or function \"%s\"",
					 funcname);
1255
		}
1256
		func_error("func_get_detail", funcname, nargs, oid_array);
1257
	}
1258 1259 1260 1261 1262 1263 1264 1265
	else
	{
		pform = (Form_pg_proc) GETSTRUCT(ftup);
		*funcid = ftup->t_oid;
		*rettype = pform->prorettype;
		*retset = pform->proretset;

		return (true);
1266 1267
	}
/* shouldn't reach here */
1268
	return (false);
1269 1270 1271 1272

}

/*
1273 1274
 *	argtype_inherit() -- Construct an argtype vector reflecting the
 *						 inheritance properties of the supplied argv.
1275
 *
1276 1277 1278 1279 1280 1281 1282
 *		This function is used to disambiguate among functions with the
 *		same name but different signatures.  It takes an array of eight
 *		type ids.  For each type id in the array that's a complex type
 *		(a class), it walks up the inheritance tree, finding all
 *		superclasses of that type.	A vector of new Oid type arrays
 *		is returned to the caller, reflecting the structure of the
 *		inheritance tree above the supplied arguments.
1283
 *
1284 1285 1286 1287 1288 1289 1290 1291 1292
 *		The order of this vector is as follows:  all superclasses of the
 *		rightmost complex class are explored first.  The exploration
 *		continues from right to left.  This policy means that we favor
 *		keeping the leftmost argument type as low in the inheritance tree
 *		as possible.  This is intentional; it is exactly what we need to
 *		do for method dispatch.  The last type array we return is all
 *		zeroes.  This will match any functions for which return types are
 *		not defined.  There are lots of these (mostly builtins) in the
 *		catalogs.
1293
 */
1294
static Oid **
1295
argtype_inherit(int nargs, Oid *oid_array)
1296
{
1297 1298 1299
	Oid			relid;
	int			i;
	InhPaths	arginh[MAXFARGS];
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321

	for (i = 0; i < MAXFARGS; i++)
	{
		if (i < nargs)
		{
			arginh[i].self = oid_array[i];
			if ((relid = typeid_get_relid(oid_array[i])) != InvalidOid)
			{
				arginh[i].nsupers = findsupers(relid, &(arginh[i].supervec));
			}
			else
			{
				arginh[i].nsupers = 0;
				arginh[i].supervec = (Oid *) NULL;
			}
		}
		else
		{
			arginh[i].self = InvalidOid;
			arginh[i].nsupers = 0;
			arginh[i].supervec = (Oid *) NULL;
		}
1322
	}
1323 1324 1325

	/* return an ordered cross-product of the classes involved */
	return (genxprod(arginh, nargs));
1326 1327
}

1328 1329
typedef struct _SuperQE
{
1330
	Oid			sqe_relid;
1331
} SuperQE;
1332 1333

static int
1334
findsupers(Oid relid, Oid **supervec)
1335
{
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
	Oid		   *relidvec;
	Relation	inhrel;
	HeapScanDesc inhscan;
	ScanKeyData skey;
	HeapTuple	inhtup;
	TupleDesc	inhtupdesc;
	int			nvisited;
	SuperQE    *qentry,
			   *vnode;
	Dllist	   *visited,
			   *queue;
	Dlelem	   *qe,
			   *elt;

	Relation	rd;
	Buffer		buf;
	Datum		d;
	bool		newrelid;
	char		isNull;
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380

	nvisited = 0;
	queue = DLNewList();
	visited = DLNewList();


	inhrel = heap_openr(InheritsRelationName);
	RelationSetLockForRead(inhrel);
	inhtupdesc = RelationGetTupleDescriptor(inhrel);

	/*
	 * Use queue to do a breadth-first traversal of the inheritance graph
	 * from the relid supplied up to the root.
	 */
	do
	{
		ScanKeyEntryInitialize(&skey, 0x0, Anum_pg_inherits_inhrel,
							   ObjectIdEqualRegProcedure,
							   ObjectIdGetDatum(relid));

		inhscan = heap_beginscan(inhrel, 0, NowTimeQual, 1, &skey);

		while (HeapTupleIsValid(inhtup = heap_getnext(inhscan, 0, &buf)))
		{
			qentry = (SuperQE *) palloc(sizeof(SuperQE));

1381 1382
			d = fastgetattr(inhtup, Anum_pg_inherits_inhparent,
							inhtupdesc, &isNull);
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
			qentry->sqe_relid = DatumGetObjectId(d);

			/* put this one on the queue */
			DLAddTail(queue, DLNewElem(qentry));

			ReleaseBuffer(buf);
		}

		heap_endscan(inhscan);

		/* pull next unvisited relid off the queue */
		do
		{
			qe = DLRemHead(queue);
			qentry = qe ? (SuperQE *) DLE_VAL(qe) : NULL;

			if (qentry == (SuperQE *) NULL)
				break;

			relid = qentry->sqe_relid;
			newrelid = true;

			for (elt = DLGetHead(visited); elt; elt = DLGetSucc(elt))
			{
				vnode = (SuperQE *) DLE_VAL(elt);
				if (vnode && (qentry->sqe_relid == vnode->sqe_relid))
				{
					newrelid = false;
					break;
				}
			}
		} while (!newrelid);

		if (qentry != (SuperQE *) NULL)
		{

			/* save the type id, rather than the relation id */
			if ((rd = heap_open(qentry->sqe_relid)) == (Relation) NULL)
				elog(WARN, "relid %d does not exist", qentry->sqe_relid);
			qentry->sqe_relid = typeid(type(RelationGetRelationName(rd)->data));
			heap_close(rd);

			DLAddTail(visited, qe);

			nvisited++;
		}
	} while (qentry != (SuperQE *) NULL);

	RelationUnsetLockForRead(inhrel);
	heap_close(inhrel);

	if (nvisited > 0)
	{
		relidvec = (Oid *) palloc(nvisited * sizeof(Oid));
		*supervec = relidvec;

		for (elt = DLGetHead(visited); elt; elt = DLGetSucc(elt))
		{
			vnode = (SuperQE *) DLE_VAL(elt);
			*relidvec++ = vnode->sqe_relid;
		}

1445
	}
1446 1447 1448
	else
	{
		*supervec = (Oid *) NULL;
1449
	}
1450 1451

	return (nvisited);
1452 1453
}

1454
static Oid **
1455
genxprod(InhPaths *arginh, int nargs)
1456
{
1457 1458 1459 1460 1461 1462 1463
	int			nanswers;
	Oid		  **result,
			  **iter;
	Oid		   *oneres;
	int			i,
				j;
	int			cur[MAXFARGS];
1464 1465 1466 1467 1468 1469

	nanswers = 1;
	for (i = 0; i < nargs; i++)
	{
		nanswers *= (arginh[i].nsupers + 2);
		cur[i] = 0;
1470
	}
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505

	iter = result = (Oid **) palloc(sizeof(Oid *) * nanswers);

	/* compute the cross product from right to left */
	for (;;)
	{
		oneres = (Oid *) palloc(MAXFARGS * sizeof(Oid));
		memset(oneres, 0, MAXFARGS * sizeof(Oid));

		for (i = nargs - 1; i >= 0 && cur[i] > arginh[i].nsupers; i--)
			continue;

		/* if we're done, terminate with NULL pointer */
		if (i < 0)
		{
			*iter = NULL;
			return (result);
		}

		/* no, increment this column and zero the ones after it */
		cur[i] = cur[i] + 1;
		for (j = nargs - 1; j > i; j--)
			cur[j] = 0;

		for (i = 0; i < nargs; i++)
		{
			if (cur[i] == 0)
				oneres[i] = arginh[i].self;
			else if (cur[i] > arginh[i].nsupers)
				oneres[i] = 0;	/* wild card */
			else
				oneres[i] = arginh[i].supervec[cur[i] - 1];
		}

		*iter++ = oneres;
1506 1507 1508 1509 1510
	}
}

/* Given a type id, returns the in-conversion function of the type */
Oid
1511
typeid_get_retinfunc(Oid type_id)
1512
{
1513 1514 1515
	HeapTuple	typeTuple;
	TypeTupleForm type;
	Oid			infunc;
1516 1517 1518 1519 1520

	typeTuple = SearchSysCacheTuple(TYPOID,
									ObjectIdGetDatum(type_id),
									0, 0, 0);
	if (!HeapTupleIsValid(typeTuple))
Thomas G. Lockhart's avatar
Thomas G. Lockhart committed
1521
		elog(WARN, "typeid_get_retinfunc: Invalid type - oid = %u", type_id);
1522 1523 1524 1525

	type = (TypeTupleForm) GETSTRUCT(typeTuple);
	infunc = type->typinput;
	return (infunc);
1526 1527
}

1528 1529 1530 1531
/* Given a type id, returns the out-conversion function of the type */
Oid
typeid_get_retoutfunc(Oid type_id)
{
1532 1533 1534
	HeapTuple	typeTuple;
	TypeTupleForm type;
	Oid			outfunc;
1535 1536 1537 1538 1539

	typeTuple = SearchSysCacheTuple(TYPOID,
									ObjectIdGetDatum(type_id),
									0, 0, 0);
	if (!HeapTupleIsValid(typeTuple))
Thomas G. Lockhart's avatar
Thomas G. Lockhart committed
1540
		elog(WARN, "typeid_get_retoutfunc: Invalid type - oid = %u", type_id);
1541 1542 1543 1544

	type = (TypeTupleForm) GETSTRUCT(typeTuple);
	outfunc = type->typoutput;
	return (outfunc);
1545 1546
}

1547
Oid
1548
typeid_get_relid(Oid type_id)
1549
{
1550 1551 1552
	HeapTuple	typeTuple;
	TypeTupleForm type;
	Oid			infunc;
1553 1554 1555 1556 1557

	typeTuple = SearchSysCacheTuple(TYPOID,
									ObjectIdGetDatum(type_id),
									0, 0, 0);
	if (!HeapTupleIsValid(typeTuple))
Thomas G. Lockhart's avatar
Thomas G. Lockhart committed
1558
		elog(WARN, "typeid_get_relid: Invalid type - oid = %u", type_id);
1559 1560 1561 1562

	type = (TypeTupleForm) GETSTRUCT(typeTuple);
	infunc = type->typrelid;
	return (infunc);
1563 1564
}

1565 1566
Oid
get_typrelid(Type typ)
1567
{
1568
	TypeTupleForm typtup;
1569 1570 1571 1572

	typtup = (TypeTupleForm) GETSTRUCT(typ);

	return (typtup->typrelid);
1573 1574 1575 1576 1577
}

Oid
get_typelem(Oid type_id)
{
1578 1579
	HeapTuple	typeTuple;
	TypeTupleForm type;
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589

	if (!(typeTuple = SearchSysCacheTuple(TYPOID,
										  ObjectIdGetDatum(type_id),
										  0, 0, 0)))
	{
		elog(WARN, "type id lookup of %u failed", type_id);
	}
	type = (TypeTupleForm) GETSTRUCT(typeTuple);

	return (type->typelem);
1590 1591
}

1592
#ifdef NOT_USED
1593 1594 1595
char
FindDelimiter(char *typename)
{
1596 1597 1598
	char		delim;
	HeapTuple	typeTuple;
	TypeTupleForm type;
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610


	if (!(typeTuple = SearchSysCacheTuple(TYPNAME,
										  PointerGetDatum(typename),
										  0, 0, 0)))
	{
		elog(WARN, "type name lookup of %s failed", typename);
	}
	type = (TypeTupleForm) GETSTRUCT(typeTuple);

	delim = type->typdelim;
	return (delim);
1611
}
1612

1613
#endif
1614 1615 1616 1617 1618

/*
 * Give a somewhat useful error message when the operator for two types
 * is not found.
 */
1619
static void
1620
op_error(char *op, Oid arg1, Oid arg2)
1621
{
1622 1623
	Type		tp1 = NULL,
				tp2 = NULL;
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648

	if (check_typeid(arg1))
	{
		tp1 = get_id_type(arg1);
	}
	else
	{
		elog(WARN, "left hand side of operator %s has an unknown type, probably a bad attribute name", op);
	}

	if (check_typeid(arg2))
	{
		tp2 = get_id_type(arg2);
	}
	else
	{
		elog(WARN, "right hand side of operator %s has an unknown type, probably a bad attribute name", op);
	}

	elog(NOTICE, "there is no operator %s for types %s and %s",
		 op, tname(tp1), tname(tp2));
	elog(NOTICE, "You will either have to retype this query using an");
	elog(NOTICE, "explicit cast, or you will have to define the operator");
	elog(WARN, "%s for %s and %s using CREATE OPERATOR",
		 op, tname(tp1), tname(tp2));
1649 1650 1651 1652 1653 1654 1655
}

/*
 * Error message when function lookup fails that gives details of the
 * argument types
 */
void
1656
func_error(char *caller, char *funcname, int nargs, Oid *argtypes)
1657
{
1658 1659 1660
	char		p[(NAMEDATALEN + 2) * MAXFMGRARGS],
			   *ptr;
	int			i;
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678

	ptr = p;
	*ptr = '\0';
	for (i = 0; i < nargs; i++)
	{
		if (i)
		{
			*ptr++ = ',';
			*ptr++ = ' ';
		}
		if (argtypes[i] != 0)
		{
			strcpy(ptr, tname(get_id_type(argtypes[i])));
			*(ptr + NAMEDATALEN) = '\0';
		}
		else
			strcpy(ptr, "opaque");
		ptr += strlen(ptr);
1679
	}
1680 1681

	elog(WARN, "%s: function %s(%s) does not exist", caller, funcname, p);
1682 1683
}

1684 1685 1686 1687 1688 1689 1690
/*
 * Error message when aggregate lookup fails that gives details of the
 * basetype
 */
void
agg_error(char *caller, char *aggname, Oid basetypeID)
{
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705

	/*
	 * basetypeID that is Invalid (zero) means aggregate over all types.
	 * (count)
	 */

	if (basetypeID == InvalidOid)
	{
		elog(WARN, "%s: aggregate '%s' for all types does not exist", caller, aggname);
	}
	else
	{
		elog(WARN, "%s: aggregate '%s' for '%s' does not exist", caller, aggname,
			 tname(get_id_type(basetypeID)));
	}
1706
}