catalog_utils.c 39.4 KB
Newer Older
1 2 3 4 5 6 7 8
/*-------------------------------------------------------------------------
 *
 * catalog_utils.c--
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
9
 *    $Header: /cvsroot/pgsql/src/backend/parser/Attic/catalog_utils.c,v 1.20 1997/08/12 20:15:32 momjian 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
#include "port-protos.h"              /* strdup() */

53 54 55 56 57 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 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
struct {
    char *field;
    int code;
} special_attr[] = {
    { "ctid", SelfItemPointerAttributeNumber },
    { "oid", ObjectIdAttributeNumber },
    { "xmin", MinTransactionIdAttributeNumber },
    { "cmin", MinCommandIdAttributeNumber },
    { "xmax", MaxTransactionIdAttributeNumber },
    { "cmax", MaxCommandIdAttributeNumber },
    { "chain", ChainItemPointerAttributeNumber },
    { "anchor", AnchorItemPointerAttributeNumber },
    { "tmin", MinAbsoluteTimeAttributeNumber },
    { "tmax", MaxAbsoluteTimeAttributeNumber },
    { "vtype", VersionTypeAttributeNumber }
};

#define SPECIALS (sizeof(special_attr)/sizeof(*special_attr))
  
static char *attnum_type[SPECIALS] = {
    "tid",
    "oid",
    "xid",
    "cid",
    "xid",
    "cid",
    "tid",
    "tid",
    "abstime",
    "abstime",
    "char"
  };

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

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

typedef struct _InhPaths {
    int		nsupers;	/* number of superclasses */
    Oid	self;		/* this class */
    Oid	*supervec;	/* vector of superclasses */
} InhPaths;

/*
 *  This structure holds a list of possible functions or operators that
 *  agree with the known name and argument types of the function/operator.
 */
typedef struct _CandidateList {
    Oid *args;
    struct _CandidateList *next;
} *CandidateList;

109 110 111 112
static Oid **argtype_inherit(int nargs, Oid *oid_array);
static Oid **genxprod(InhPaths *arginh, int nargs);
static int findsupers(Oid relid, Oid **supervec);

113 114 115 116 117 118 119
/* check to see if a type id is valid,
 * returns true if it is. By using this call before calling 
 * get_id_type or get_id_typname, more meaningful error messages
 * can be produced because the caller typically has more context of
 *  what's going on                 - jolly
 */
bool
120
check_typeid(Oid id)
121 122 123 124 125 126 127 128 129
{
    return (SearchSysCacheTuple(TYPOID, 
				ObjectIdGetDatum(id),
				0,0,0) != NULL);
}


/* return a Type structure, given an typid */
Type
130
get_id_type(Oid id)
131 132 133 134 135
{
    HeapTuple tup;
    
    if (!(tup = SearchSysCacheTuple(TYPOID, ObjectIdGetDatum(id),
				    0,0,0))) { 
136
	elog ( WARN, "type id lookup of %ud failed", id);
137 138 139 140 141 142 143
	return(NULL);
    }
    return((Type) tup);
}

/* return a type name, given a typeid */
char*
144
get_id_typname(Oid id)
145 146 147 148 149 150
{
    HeapTuple tup;
    TypeTupleForm typetuple;
    
    if (!(tup = SearchSysCacheTuple(TYPOID, ObjectIdGetDatum(id),
				    0,0,0))) {
151
	elog ( WARN, "type id lookup of %ud failed", id);
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
	return(NULL);
    }
    typetuple = (TypeTupleForm)GETSTRUCT(tup);
    return (typetuple->typname).data;
}

/* return a Type structure, given type name */
Type
type(char *s)
{
    HeapTuple tup;
    
    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);
}

/* given attribute id, return type of that attribute */
/* XXX Special case for pseudo-attributes is a hack */
Oid
att_typeid(Relation rd, int attid)
{
    
    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);
}


int
att_attnelems(Relation rd, int attid)
{
    return(rd->rd_att->attrs[attid-1]->attnelems);
}

/* given type, return the type OID */
Oid
typeid(Type tp)
{
    if (tp == NULL) {
	elog ( WARN , "typeid() called with NULL type struct");
    }
    return(tp->t_oid);
}

/* given type (as type struct), return the length of type */
int16
tlen(Type t)
{
    TypeTupleForm    typ;
    
    typ = (TypeTupleForm)GETSTRUCT(t);
    return(typ->typlen);
}

/* given type (as type struct), return the value of its 'byval' attribute.*/
bool
tbyval(Type t)
{
    TypeTupleForm    typ;
    
    typ = (TypeTupleForm)GETSTRUCT(t);
    return(typ->typbyval);
}

/* given type (as type struct), return the name of type */
char*
tname(Type t)
{
    TypeTupleForm    typ;
    
    typ = (TypeTupleForm)GETSTRUCT(t);
    return (typ->typname).data;
}

/* given type (as type struct), return wether type is passed by value */
int
tbyvalue(Type t)
{
    TypeTupleForm typ;
    
    typ = (TypeTupleForm) GETSTRUCT(t);
    return(typ->typbyval);
}

/* given a type, return its typetype ('c' for 'c'atalog types) */
246
static char
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
typetypetype(Type t)
{
    TypeTupleForm typ;
    
    typ = (TypeTupleForm) GETSTRUCT(t);
    return(typ->typtype);
}

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

/*
 *  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
 */
static int
binary_oper_get_candidates(char *opname,
270 271
			   Oid leftTypeId,
			   Oid rightTypeId,
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 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 351 352 353 354 355 356 357 358 359 360 361 362
			   CandidateList *candidates)
{
    CandidateList 	current_candidate;
    Relation            pg_operator_desc;
    HeapScanDesc        pg_operator_scan;
    HeapTuple           tup;
    OperatorTupleForm	oper;
    Buffer              buffer;
    int			nkeys;
    int			ncandidates = 0;
    ScanKeyData  	opKey[3];
    
    *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));
    } 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;
}

/*
 * equivalentOpersAfterPromotion -
 *    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).
 */
static bool
equivalentOpersAfterPromotion(CandidateList candidates)
{
    CandidateList result;
    CandidateList promotedCandidates = NULL;
363
    Oid leftarg, rightarg;
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 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418

    for (result = candidates; result != NULL; result = result->next) {
	CandidateList c;
	c = (CandidateList)palloc(sizeof(*c));
	c->args = (Oid *)palloc(2 * sizeof(Oid));
	switch (result->args[0]) {
	case FLOAT4OID:
	case INT4OID:
	case INT2OID:
	    c->args[0] = FLOAT8OID;
	    break;
	default:
	    c->args[0] = result->args[0];
	    break;
	}
	switch (result->args[1]) {
	case FLOAT4OID:
	case INT4OID:
	case INT2OID:
	    c->args[1] = FLOAT8OID;
	    break;
	default:
	    c->args[1] = result->args[1];
	    break;
	}
	c->next = promotedCandidates;
	promotedCandidates = c;
    }

    /* 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;
    }

    /* 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;
}
	

/*
 *  given a choice of argument type pairs for a binary operator,
 *  try to choose a default pair
 */
static CandidateList
419 420
binary_oper_select_candidate(Oid arg1,
			     Oid arg2,
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
			     CandidateList candidates)
{
    CandidateList result;

    /*
     * 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;
    }

    return (NULL);
}

/* Given operator, types of arg1, and arg2, return oper struct */
/* arg1, arg2 --typeids */
Operator
473
oper(char *op, Oid arg1, Oid arg2, bool noWarnings)
474 475 476 477 478
{
    HeapTuple tup;
    CandidateList candidates;
    int ncandidates;

Marc G. Fournier's avatar
Marc G. Fournier committed
479 480 481
    if (!arg2) arg2=arg1;
    if (!arg1) arg1=arg2;

482 483 484 485 486 487 488 489 490 491
    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
	     */
492 493
	    if (!noWarnings)
		op_error(op, arg1, arg2);
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
	    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 {
		Type tp1, tp2;
		
		/* we chose none of them */
		tp1 = get_id_type(arg1);
		tp2 = get_id_type(arg2);
524 525 526 527 528 529
		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");
		}
530 531 532 533 534 535 536 537 538 539 540 541 542 543
		return(NULL);
	    }
	}
    }
    return((Operator) tup);
}

/*
 *  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
 */
static int
unary_oper_get_candidates(char *op,
544
			  Oid typeId,
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 599 600 601 602 603 604 605 606 607
			  CandidateList *candidates,
			  char rightleft)
{
    CandidateList 	current_candidate;
    Relation            pg_operator_desc;
    HeapScanDesc        pg_operator_scan;
    HeapTuple           tup;
    OperatorTupleForm	oper;
    Buffer              buffer;
    int			ncandidates = 0;
    
    static ScanKeyData opKey[2] = {
	{ 0, Anum_pg_operator_oprname, NameEqualRegProcedure },
	{ 0, Anum_pg_operator_oprkind, CharacterEqualRegProcedure } };
    
    *candidates = NULL;
    
    fmgr_info(NameEqualRegProcedure, (func_ptr *) &opKey[0].sk_func,
	      &opKey[0].sk_nargs);
    opKey[0].sk_argument = NameGetDatum(op);
    fmgr_info(CharacterEqualRegProcedure, (func_ptr *) &opKey[1].sk_func,
	      &opKey[1].sk_nargs);
    opKey[1].sk_argument = CharGetDatum(rightleft);
    
    /* currently, only "unknown" can be coerced */
    if (typeId != UNKNOWNOID) {
        return 0;
    }
    
    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;
}

/* Given unary right-side operator (operator on right), return oper struct */
/* arg-- type id */
Operator
608
right_oper(char *op, Oid arg)
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
{
    HeapTuple tup;
    CandidateList candidates;
    int ncandidates;
    
    /*
      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);
	}
    }
    return((Operator) tup);
}

/* Given unary left-side operator (operator on left), return oper struct */
/* arg--type id */
Operator
651
left_oper(char *op, Oid arg)
652 653 654 655 656 657 658 659 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 693 694 695 696 697 698 699 700 701 702 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 736 737 738 739 740 741 742 743 744 745 746 747 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 781 782 783 784 785 786 787 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 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 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 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 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 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
{
    HeapTuple tup;
    CandidateList candidates;
    int ncandidates;
    
    /*
      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);
	}
    }
    return((Operator) tup);
}

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

int
varattno(Relation rd, char *a)
{
    int i;
    
    for (i = 0; i < rd->rd_rel->relnatts; i++) {
	if (!namestrcmp(&(rd->rd_att->attrs[i]->attname), a)) {
	    return(i+1);
	}
    }
    for (i = 0; i < SPECIALS; i++) {
	if (!strcmp(special_attr[i].field, a)) {
	    return(special_attr[i].code);
	}
    }
    
    elog(WARN,"Relation %s does not have attribute %s\n", 
	 RelationGetRelationName(rd), a );
    return(-1);
}

/* 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)
{
    int i;
    
    /* 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 */
	}
    }
    return (get_attisset(rd->rd_id, name));
}

/* given range variable, return id of variable */
int
nf_varattno(Relation rd, char *a)
{
    int i;
    
    for (i = 0; i < rd->rd_rel->relnatts; i++) {
	if (!namestrcmp(&(rd->rd_att->attrs[i]->attname), a)) {
	    return(i+1);
	}
    }
    for (i = 0; i < SPECIALS; i++) {
	if (!strcmp(special_attr[i].field, a)) {
	    return(special_attr[i].code);
	}
    }
    return InvalidAttrNumber;
}

/*-------------
 * given an attribute number and a relation, return its relation name
 */
char*
getAttrName(Relation rd, int attrno)
{
    char *name;
    int i;
    
    if (attrno<0) {
	for (i = 0; i < SPECIALS; i++) {
	    if (special_attr[i].code == attrno) {
		name = special_attr[i].field;
		return(name);
	    }
	}
	elog(WARN, "Illegal attr no %d for relation %s\n",
	     attrno, RelationGetRelationName(rd));
    } else if (attrno >=1 && attrno<= RelationGetNumberOfAttributes(rd)) {
	name = (rd->rd_att->attrs[attrno-1]->attname).data;
	return(name);
    } else {
	elog(WARN, "Illegal attr no %d for relation %s\n",
	     attrno, RelationGetRelationName(rd));
    }
    
    /*
     * Shouldn't get here, but we want lint to be happy...
     */
    
    return(NULL);
}

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

char *
outstr(char *typename,	/* Name of type of value */
       char *value)	/* Could be of any type */
{
    TypeTupleForm tp;
    Oid op;
    
    tp = (TypeTupleForm ) GETSTRUCT(type(typename));
    op = tp->typoutput;
    return((char *) fmgr(op, value));
}

/* Given a Type and a string, return the internal form of that string */
char *
instr2(Type tp, char *string, int typlen)
{
    return(instr1((TypeTupleForm ) GETSTRUCT(tp), string, typlen));
}

/* Given a type structure and a string, returns the internal form of
   that string */
char *
instr1(TypeTupleForm tp, char *string, int typlen)
{
    Oid op;
    Oid typelem;
    
    op = tp->typinput;
    typelem = tp->typelem; /* XXX - used for array_in */
    /* typlen is for bpcharin() and varcharin() */
    return((char *) fmgr(op, string, typelem, typlen));
}

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

Oid
GetArrayElementType(Oid typearray)
{
    HeapTuple type_tuple;
    TypeTupleForm type_struct_array;
    
    type_tuple = SearchSysCacheTuple(TYPOID,
				     ObjectIdGetDatum(typearray),
				     0,0,0);
    
    if (!HeapTupleIsValid(type_tuple))
	elog(WARN, "GetArrayElementType: Cache lookup failed for type %d\n",
	     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",
	     (Name)&(type_struct_array->typname.data[0]));
    }
    
    return(type_struct_array->typelem);
}

Oid
funcid_get_rettype(Oid funcid)
{
    HeapTuple func_tuple = NULL;
    Oid funcrettype = (Oid)0;
    
    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);
}

/*
 * get a list of all argument type vectors for which a function named
 * funcname taking nargs arguments exists
 */
static CandidateList
func_get_candidates(char *funcname, int nargs)
{
    Relation heapRelation;
    Relation idesc;
    ScanKeyData skey;
    HeapTuple tuple;
    IndexScanDesc sd;
    RetrieveIndexResult indexRes;
    Buffer buffer;
    Form_pg_proc pgProcP;
    bool bufferUsed = FALSE;
    CandidateList candidates = NULL;
    CandidateList current_candidate;
    int i;
    
    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;
        }
	
        indexRes = index_getnext(sd, ForwardScanDirection);
        if (indexRes) {
            ItemPointer iptr;
	    
            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;
}

/*
 * can input_typeids be coerced to func_typeids?
 */
static bool
can_coerce(int nargs, Oid *input_typeids, Oid *func_typeids)
{
    int i;
    Type tp;
    
    /*
     * 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] != UNKNOWNOID || func_typeids[i] == 0)
		return false;
	    
	    tp = get_id_type(input_typeids[i]);
	    if (typetypetype(tp) == 'c' )
		return false;
	}
    }
    
    return true;
}

/*
 * 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,
	       Oid *input_typeids,
	       CandidateList function_typeids,
	       CandidateList *candidates) /* return value */
{
    CandidateList current_candidate;
    CandidateList matching_candidate;
    Oid *current_typeids;
    int ncandidates = 0;
    
    *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++;
	}
    }
    
    return ncandidates;
}

/*
 * 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
 */
static Oid *
func_select_candidate(int nargs,
		      Oid *input_typeids,
		      CandidateList candidates)
{
    /* XXX no conflict resolution implemeneted yet */
    return (NULL);
}

bool
func_get_detail(char *funcname,
		int nargs,
		Oid *oid_array,
		Oid *funcid,	/* return value */
		Oid *rettype,	/* return value */
		bool *retset,	/* return value */
		Oid **true_typeids) /* return value */
{
    Oid **input_typeid_vector;
    Oid *current_input_typeids;
    CandidateList function_typeids;
    CandidateList current_function_typeids;
    HeapTuple ftup;
    Form_pg_proc pform;
    
    /*
     * 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) {
	    int ncandidates = 0;
	    
	    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.");
1091
			func_error("func_get_detail", funcname, nargs, oid_array);
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
		    }
		    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);
	}
    }
    
    if (!HeapTupleIsValid(ftup)) {
	Type tp;

	if (nargs == 1) {
	    tp = get_id_type(oid_array[0]);
	    if (typetypetype(tp) == 'c')
		elog(WARN, "no such attribute or function \"%s\"",
		     funcname);
	}
1118
	func_error("func_get_detail", funcname, nargs, oid_array);
1119 1120 1121
    } else {
	pform = (Form_pg_proc) GETSTRUCT(ftup);
	*funcid = ftup->t_oid;
1122 1123
	*rettype = pform->prorettype;
	*retset = pform->proretset;
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 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 1194 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 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
	
	return (true);
    }
/* shouldn't reach here */
 return (false);

}

/*
 *  argtype_inherit() -- Construct an argtype vector reflecting the
 *			 inheritance properties of the supplied argv.
 *
 *	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.
 *
 *	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.
 */
static Oid **
argtype_inherit(int nargs, Oid *oid_array)
{
    Oid relid;
    int i;
    InhPaths arginh[MAXFARGS];
    
    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;
	}
    }
    
    /* return an ordered cross-product of the classes involved */
    return (genxprod(arginh, nargs));
}

typedef struct _SuperQE {
    Oid	sqe_relid;
} SuperQE;

static int
findsupers(Oid relid, Oid **supervec)
{
    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;
    
    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));
	    
	    d = (Datum) fastgetattr(inhtup, Anum_pg_inherits_inhparent,
				    inhtupdesc, &isNull);
	    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;
	   }
	  
    } else {
	*supervec = (Oid *) NULL;
      }

    return (nvisited);
}

static Oid **
genxprod(InhPaths *arginh, int nargs)
{
    int nanswers;
    Oid **result, **iter;
    Oid *oneres;
    int i, j;
    int cur[MAXFARGS];
    
    nanswers = 1;
    for (i = 0; i < nargs; i++) {
	nanswers *= (arginh[i].nsupers + 2);
	cur[i] = 0;
    }
    
    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;
    }
}

/* Given a type id, returns the in-conversion function of the type */
Oid
1344
typeid_get_retinfunc(Oid type_id)
1345
{
1346
    HeapTuple       typeTuple;
1347 1348 1349 1350 1351 1352 1353
    TypeTupleForm   type;
    Oid             infunc;
    typeTuple = SearchSysCacheTuple(TYPOID,
				    ObjectIdGetDatum(type_id),
				    0,0,0);
    if ( !HeapTupleIsValid ( typeTuple ))
	elog(WARN,
1354
	     "typeid_get_retinfunc: Invalid type - oid = %u",
1355 1356 1357 1358 1359 1360 1361
	     type_id);
    
    type = (TypeTupleForm) GETSTRUCT(typeTuple);
    infunc = type->typinput;
    return(infunc);
}

1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
/* Given a type id, returns the out-conversion function of the type */
Oid
typeid_get_retoutfunc(Oid type_id)
{
    HeapTuple       typeTuple;
    TypeTupleForm   type;
    Oid             outfunc;
    typeTuple = SearchSysCacheTuple(TYPOID,
				    ObjectIdGetDatum(type_id),
				    0,0,0);
    if ( !HeapTupleIsValid ( typeTuple ))
	elog(WARN,
	     "typeid_get_retoutfunc: Invalid type - oid = %u",
	     type_id);
    
    type = (TypeTupleForm) GETSTRUCT(typeTuple);
    outfunc = type->typoutput;
    return(outfunc);
}

1382
Oid
1383
typeid_get_relid(Oid type_id)
1384
{
1385
    HeapTuple       typeTuple;
1386 1387 1388 1389 1390 1391
    TypeTupleForm   type;
    Oid             infunc;
    typeTuple = SearchSysCacheTuple(TYPOID,
				    ObjectIdGetDatum(type_id),
				    0,0,0);
    if ( !HeapTupleIsValid ( typeTuple ))
1392
	elog(WARN, "typeid_get_relid: Invalid type - oid = %u ", type_id);
1393 1394 1395 1396 1397 1398
    
    type = (TypeTupleForm) GETSTRUCT(typeTuple);
    infunc = type->typrelid;
    return(infunc);
}

1399 1400
Oid
get_typrelid(Type typ)
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
{
    TypeTupleForm typtup;
    
    typtup = (TypeTupleForm) GETSTRUCT(typ);
    
    return (typtup->typrelid);
}

Oid
get_typelem(Oid type_id)
{
1412
    HeapTuple       typeTuple;
1413 1414 1415 1416 1417
    TypeTupleForm   type;
    
    if (!(typeTuple = SearchSysCacheTuple(TYPOID,
					  ObjectIdGetDatum(type_id),
					  0,0,0))) {
1418
	elog (WARN , "type id lookup of %u failed", type_id);
1419 1420 1421 1422 1423 1424 1425 1426 1427
    }
    type = (TypeTupleForm) GETSTRUCT(typeTuple);
    
    return (type->typelem);
}

char
FindDelimiter(char *typename)
{
1428 1429
    char            delim;
    HeapTuple       typeTuple;
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
    TypeTupleForm   type;
    
    
    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);
}

/*
 * Give a somewhat useful error message when the operator for two types
 * is not found.
 */
void
1449
op_error(char *op, Oid arg1, Oid arg2)
1450
{
Bruce Momjian's avatar
Bruce Momjian committed
1451
    Type tp1 = NULL, tp2 = NULL;
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468

    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");
1469
    elog(WARN, "%s for %s and %s using CREATE OPERATOR", 
1470 1471 1472 1473 1474 1475 1476 1477
	 op, tname(tp1),tname(tp2));
}

/*
 * Error message when function lookup fails that gives details of the
 * argument types
 */
void
1478
func_error(char *caller, char *funcname, int nargs, Oid *argtypes)
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
{
    char p[(NAMEDATALEN+2)*MAXFMGRARGS], *ptr;
    int i;
	
    ptr = p;
    *ptr = '\0';
    for (i=0; i<nargs; i++) {
	if (i) {
	    *ptr++ = ',';
	    *ptr++ = ' ';
	}
	if (argtypes[i] != 0) {
1491
	    strcpy(ptr, tname(get_id_type(argtypes[i])));
1492 1493 1494 1495 1496 1497 1498 1499 1500
	    *(ptr + NAMEDATALEN) = '\0';
	} else
	    strcpy(ptr, "opaque");
	ptr += strlen(ptr);
    }
	
    elog(WARN, "%s: function %s(%s) does not exist", caller, funcname, p);
}

1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
/*
 * Error message when aggregate lookup fails that gives details of the
 * basetype
 */
void
agg_error(char *caller, char *aggname, Oid basetypeID)
{
    /* 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)));
    }
}