]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_oper.c
Implement feature of new FE/BE protocol whereby RowDescription identifies
[postgresql] / src / backend / parser / parse_oper.c
1 /*-------------------------------------------------------------------------
2  *
3  * parse_oper.c
4  *              handle operator things for parser
5  *
6  * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $Header: /cvsroot/pgsql/src/backend/parser/parse_oper.c,v 1.63 2003/04/29 22:13:10 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "postgres.h"
17
18 #include "access/genam.h"
19 #include "access/heapam.h"
20 #include "catalog/catname.h"
21 #include "catalog/indexing.h"
22 #include "catalog/namespace.h"
23 #include "catalog/pg_operator.h"
24 #include "parser/parse_coerce.h"
25 #include "parser/parse_expr.h"
26 #include "parser/parse_func.h"
27 #include "parser/parse_oper.h"
28 #include "parser/parse_type.h"
29 #include "utils/builtins.h"
30 #include "utils/fmgroids.h"
31 #include "utils/lsyscache.h"
32 #include "utils/syscache.h"
33
34
35 static Oid binary_oper_exact(Oid arg1, Oid arg2,
36                                   FuncCandidateList candidates);
37 static Oid oper_select_candidate(int nargs, Oid *input_typeids,
38                                           FuncCandidateList candidates);
39 static void op_error(List *op, Oid arg1, Oid arg2);
40 static void unary_op_error(List *op, Oid arg, bool is_left_op);
41
42
43 /*
44  * LookupOperName
45  *              Given a possibly-qualified operator name and exact input datatypes,
46  *              look up the operator.  Returns InvalidOid if no such operator.
47  *
48  * Pass oprleft = InvalidOid for a prefix op, oprright = InvalidOid for
49  * a postfix op.
50  *
51  * If the operator name is not schema-qualified, it is sought in the current
52  * namespace search path.
53  */
54 Oid
55 LookupOperName(List *opername, Oid oprleft, Oid oprright)
56 {
57         FuncCandidateList clist;
58         char            oprkind;
59
60         if (!OidIsValid(oprleft))
61                 oprkind = 'l';
62         else if (!OidIsValid(oprright))
63                 oprkind = 'r';
64         else
65                 oprkind = 'b';
66
67         clist = OpernameGetCandidates(opername, oprkind);
68
69         while (clist)
70         {
71                 if (clist->args[0] == oprleft && clist->args[1] == oprright)
72                         return clist->oid;
73                 clist = clist->next;
74         }
75
76         return InvalidOid;
77 }
78
79 /*
80  * LookupOperNameTypeNames
81  *              Like LookupOperName, but the argument types are specified by
82  *              TypeName nodes.  Also, if we fail to find the operator
83  *              and caller is not NULL, then an error is reported.
84  *
85  * Pass oprleft = NULL for a prefix op, oprright = NULL for a postfix op.
86  */
87 Oid
88 LookupOperNameTypeNames(List *opername, TypeName *oprleft,
89                                                 TypeName *oprright, const char *caller)
90 {
91         Oid                     operoid;
92         Oid                     leftoid,
93                                 rightoid;
94
95         if (oprleft == NULL)
96                 leftoid = InvalidOid;
97         else
98         {
99                 leftoid = LookupTypeName(oprleft);
100                 if (!OidIsValid(leftoid))
101                         elog(ERROR, "Type \"%s\" does not exist",
102                                  TypeNameToString(oprleft));
103         }
104         if (oprright == NULL)
105                 rightoid = InvalidOid;
106         else
107         {
108                 rightoid = LookupTypeName(oprright);
109                 if (!OidIsValid(rightoid))
110                         elog(ERROR, "Type \"%s\" does not exist",
111                                  TypeNameToString(oprright));
112         }
113
114         operoid = LookupOperName(opername, leftoid, rightoid);
115
116         if (!OidIsValid(operoid) && caller != NULL)
117         {
118                 if (oprleft == NULL)
119                         elog(ERROR, "%s: Prefix operator '%s' for type '%s' does not exist",
120                                  caller, NameListToString(opername),
121                                  TypeNameToString(oprright));
122                 else if (oprright == NULL)
123                         elog(ERROR, "%s: Postfix operator '%s' for type '%s' does not exist",
124                                  caller, NameListToString(opername),
125                                  TypeNameToString(oprleft));
126                 else
127                         elog(ERROR, "%s: Operator '%s' for types '%s' and '%s' does not exist",
128                                  caller, NameListToString(opername),
129                                  TypeNameToString(oprleft),
130                                  TypeNameToString(oprright));
131         }
132
133         return operoid;
134 }
135
136 /*
137  * equality_oper - identify a suitable equality operator for a datatype
138  *
139  * On failure, return NULL if noError, else report a standard error
140  */
141 Operator
142 equality_oper(Oid argtype, bool noError)
143 {
144         Operator        optup;
145
146         /*
147          * Look for an "=" operator for the datatype.  We require it to be
148          * an exact or binary-compatible match, since most callers are not
149          * prepared to cope with adding any run-time type coercion steps.
150          */
151         optup = compatible_oper(makeList1(makeString("=")),
152                                                         argtype, argtype, true);
153         if (optup != NULL)
154         {
155                 /*
156                  * Only believe that it's equality if it's mergejoinable,
157                  * hashjoinable, or uses eqsel() as oprrest.
158                  */
159                 Form_pg_operator pgopform = (Form_pg_operator) GETSTRUCT(optup);
160
161                 if (OidIsValid(pgopform->oprlsortop) ||
162                         pgopform->oprcanhash ||
163                         pgopform->oprrest == F_EQSEL)
164                         return optup;
165
166                 ReleaseSysCache(optup);
167         }
168         if (!noError)
169                 elog(ERROR, "Unable to identify an equality operator for type %s",
170                          format_type_be(argtype));
171         return NULL;
172 }
173
174 /*
175  * ordering_oper - identify a suitable sorting operator ("<") for a datatype
176  *
177  * On failure, return NULL if noError, else report a standard error
178  */
179 Operator
180 ordering_oper(Oid argtype, bool noError)
181 {
182         Operator        optup;
183
184         /*
185          * Find the type's equality operator, and use its lsortop (it *must*
186          * be mergejoinable).  We use this definition because for sorting and
187          * grouping purposes, it's important that the equality and ordering
188          * operators are consistent.
189          */
190         optup = equality_oper(argtype, noError);
191         if (optup != NULL)
192         {
193                 Oid             lsortop = ((Form_pg_operator) GETSTRUCT(optup))->oprlsortop;
194
195                 ReleaseSysCache(optup);
196
197                 if (OidIsValid(lsortop))
198                 {
199                         optup = SearchSysCache(OPEROID,
200                                                                    ObjectIdGetDatum(lsortop),
201                                                                    0, 0, 0);
202                         if (optup != NULL)
203                                 return optup;
204                 }
205         }
206         if (!noError)
207                 elog(ERROR, "Unable to identify an ordering operator for type %s"
208                          "\n\tUse an explicit ordering operator or modify the query",
209                          format_type_be(argtype));
210         return NULL;
211 }
212
213 /*
214  * equality_oper_funcid - convenience routine for oprfuncid(equality_oper())
215  */
216 Oid
217 equality_oper_funcid(Oid argtype)
218 {
219         Operator        optup;
220         Oid                     result;
221
222         optup = equality_oper(argtype, false);
223         result = oprfuncid(optup);
224         ReleaseSysCache(optup);
225         return result;
226 }
227
228 /*
229  * ordering_oper_opid - convenience routine for oprid(ordering_oper())
230  *
231  * This was formerly called any_ordering_op()
232  */
233 Oid
234 ordering_oper_opid(Oid argtype)
235 {
236         Operator        optup;
237         Oid                     result;
238
239         optup = ordering_oper(argtype, false);
240         result = oprid(optup);
241         ReleaseSysCache(optup);
242         return result;
243 }
244
245
246 /* given operator tuple, return the operator OID */
247 Oid
248 oprid(Operator op)
249 {
250         return HeapTupleGetOid(op);
251 }
252
253 /* given operator tuple, return the underlying function's OID */
254 Oid
255 oprfuncid(Operator op)
256 {
257         Form_pg_operator pgopform = (Form_pg_operator) GETSTRUCT(op);
258
259         return pgopform->oprcode;
260 }
261
262
263 /* binary_oper_exact()
264  * Check for an "exact" match to the specified operand types.
265  *
266  * If one operand is an unknown literal, assume it should be taken to be
267  * the same type as the other operand for this purpose.
268  */
269 static Oid
270 binary_oper_exact(Oid arg1, Oid arg2,
271                                   FuncCandidateList candidates)
272 {
273         /* Unspecified type for one of the arguments? then use the other */
274         if ((arg1 == UNKNOWNOID) && (arg2 != InvalidOid))
275                 arg1 = arg2;
276         else if ((arg2 == UNKNOWNOID) && (arg1 != InvalidOid))
277                 arg2 = arg1;
278
279         while (candidates != NULL)
280         {
281                 if (arg1 == candidates->args[0] &&
282                         arg2 == candidates->args[1])
283                         return candidates->oid;
284                 candidates = candidates->next;
285         }
286
287         return InvalidOid;
288 }
289
290
291 /* oper_select_candidate()
292  * Given the input argtype array and one or more candidates
293  * for the function argtype array, attempt to resolve the conflict.
294  * Returns the selected argtype array if the conflict can be resolved,
295  * otherwise returns NULL.
296  *
297  * By design, this is pretty similar to func_select_candidate in parse_func.c.
298  * However, we can do a couple of extra things here because we know we can
299  * have no more than two args to deal with.  Also, the calling convention
300  * is a little different: we must prune away "candidates" that aren't actually
301  * coercion-compatible with the input types, whereas in parse_func.c that
302  * gets done by match_argtypes before func_select_candidate is called.
303  *
304  * This routine is new code, replacing binary_oper_select_candidate()
305  * which dates from v4.2/v1.0.x days. It tries very hard to match up
306  * operators with types, including allowing type coercions if necessary.
307  * The important thing is that the code do as much as possible,
308  * while _never_ doing the wrong thing, where "the wrong thing" would
309  * be returning an operator when other better choices are available,
310  * or returning an operator which is a non-intuitive possibility.
311  * - thomas 1998-05-21
312  *
313  * The comments below came from binary_oper_select_candidate(), and
314  * illustrate the issues and choices which are possible:
315  * - thomas 1998-05-20
316  *
317  * current wisdom holds that the default operator should be one in which
318  * both operands have the same type (there will only be one such
319  * operator)
320  *
321  * 7.27.93 - I have decided not to do this; it's too hard to justify, and
322  * it's easy enough to typecast explicitly - avi
323  * [the rest of this routine was commented out since then - ay]
324  *
325  * 6/23/95 - I don't complete agree with avi. In particular, casting
326  * floats is a pain for users. Whatever the rationale behind not doing
327  * this is, I need the following special case to work.
328  *
329  * In the WHERE clause of a query, if a float is specified without
330  * quotes, we treat it as float8. I added the float48* operators so
331  * that we can operate on float4 and float8. But now we have more than
332  * one matching operator if the right arg is unknown (eg. float
333  * specified with quotes). This break some stuff in the regression
334  * test where there are floats in quotes not properly casted. Below is
335  * the solution. In addition to requiring the operator operates on the
336  * same type for both operands [as in the code Avi originally
337  * commented out], we also require that the operators be equivalent in
338  * some sense. (see equivalentOpersAfterPromotion for details.)
339  * - ay 6/95
340  */
341 static Oid
342 oper_select_candidate(int nargs,
343                                           Oid *input_typeids,
344                                           FuncCandidateList candidates)
345 {
346         FuncCandidateList current_candidate;
347         FuncCandidateList last_candidate;
348         Oid                *current_typeids;
349         Oid                     current_type;
350         int                     unknownOids;
351         int                     i;
352         int                     ncandidates;
353         int                     nbestMatch,
354                                 nmatch;
355         CATEGORY        slot_category[FUNC_MAX_ARGS],
356                                 current_category;
357         bool            slot_has_preferred_type[FUNC_MAX_ARGS];
358         bool            resolved_unknowns;
359
360         /*
361          * First, delete any candidates that cannot actually accept the given
362          * input types, whether directly or by coercion.  (Note that
363          * can_coerce_type will assume that UNKNOWN inputs are coercible to
364          * anything, so candidates will not be eliminated on that basis.)
365          */
366         ncandidates = 0;
367         last_candidate = NULL;
368         for (current_candidate = candidates;
369                  current_candidate != NULL;
370                  current_candidate = current_candidate->next)
371         {
372                 if (can_coerce_type(nargs, input_typeids, current_candidate->args,
373                                                         COERCION_IMPLICIT))
374                 {
375                         if (last_candidate == NULL)
376                         {
377                                 candidates = current_candidate;
378                                 last_candidate = current_candidate;
379                                 ncandidates = 1;
380                         }
381                         else
382                         {
383                                 last_candidate->next = current_candidate;
384                                 last_candidate = current_candidate;
385                                 ncandidates++;
386                         }
387                 }
388                 /* otherwise, don't bother keeping this one... */
389         }
390
391         if (last_candidate)                     /* terminate rebuilt list */
392                 last_candidate->next = NULL;
393
394         /* Done if no candidate or only one candidate survives */
395         if (ncandidates == 0)
396                 return InvalidOid;
397         if (ncandidates == 1)
398                 return candidates->oid;
399
400         /*
401          * Run through all candidates and keep those with the most matches on
402          * exact types. Keep all candidates if none match.
403          */
404         ncandidates = 0;
405         nbestMatch = 0;
406         last_candidate = NULL;
407         for (current_candidate = candidates;
408                  current_candidate != NULL;
409                  current_candidate = current_candidate->next)
410         {
411                 current_typeids = current_candidate->args;
412                 nmatch = 0;
413                 for (i = 0; i < nargs; i++)
414                 {
415                         if (input_typeids[i] != UNKNOWNOID &&
416                                 current_typeids[i] == input_typeids[i])
417                                 nmatch++;
418                 }
419
420                 /* take this one as the best choice so far? */
421                 if ((nmatch > nbestMatch) || (last_candidate == NULL))
422                 {
423                         nbestMatch = nmatch;
424                         candidates = current_candidate;
425                         last_candidate = current_candidate;
426                         ncandidates = 1;
427                 }
428                 /* no worse than the last choice, so keep this one too? */
429                 else if (nmatch == nbestMatch)
430                 {
431                         last_candidate->next = current_candidate;
432                         last_candidate = current_candidate;
433                         ncandidates++;
434                 }
435                 /* otherwise, don't bother keeping this one... */
436         }
437
438         if (last_candidate)                     /* terminate rebuilt list */
439                 last_candidate->next = NULL;
440
441         if (ncandidates == 1)
442                 return candidates->oid;
443
444         /*
445          * Still too many candidates? Run through all candidates and keep
446          * those with the most matches on exact types + binary-compatible
447          * types. Keep all candidates if none match.
448          */
449         ncandidates = 0;
450         nbestMatch = 0;
451         last_candidate = NULL;
452         for (current_candidate = candidates;
453                  current_candidate != NULL;
454                  current_candidate = current_candidate->next)
455         {
456                 current_typeids = current_candidate->args;
457                 nmatch = 0;
458                 for (i = 0; i < nargs; i++)
459                 {
460                         if (input_typeids[i] != UNKNOWNOID)
461                         {
462                                 if (IsBinaryCoercible(input_typeids[i], current_typeids[i]))
463                                         nmatch++;
464                         }
465                 }
466
467                 /* take this one as the best choice so far? */
468                 if ((nmatch > nbestMatch) || (last_candidate == NULL))
469                 {
470                         nbestMatch = nmatch;
471                         candidates = current_candidate;
472                         last_candidate = current_candidate;
473                         ncandidates = 1;
474                 }
475                 /* no worse than the last choice, so keep this one too? */
476                 else if (nmatch == nbestMatch)
477                 {
478                         last_candidate->next = current_candidate;
479                         last_candidate = current_candidate;
480                         ncandidates++;
481                 }
482                 /* otherwise, don't bother keeping this one... */
483         }
484
485         if (last_candidate)                     /* terminate rebuilt list */
486                 last_candidate->next = NULL;
487
488         if (ncandidates == 1)
489                 return candidates->oid;
490
491         /*
492          * Still too many candidates? Now look for candidates which are
493          * preferred types at the args that will require coercion. Keep all
494          * candidates if none match.
495          */
496         ncandidates = 0;
497         nbestMatch = 0;
498         last_candidate = NULL;
499         for (current_candidate = candidates;
500                  current_candidate != NULL;
501                  current_candidate = current_candidate->next)
502         {
503                 current_typeids = current_candidate->args;
504                 nmatch = 0;
505                 for (i = 0; i < nargs; i++)
506                 {
507                         if (input_typeids[i] != UNKNOWNOID)
508                         {
509                                 current_category = TypeCategory(current_typeids[i]);
510                                 if (current_typeids[i] == input_typeids[i] ||
511                                         IsPreferredType(current_category, current_typeids[i]))
512                                         nmatch++;
513                         }
514                 }
515
516                 if ((nmatch > nbestMatch) || (last_candidate == NULL))
517                 {
518                         nbestMatch = nmatch;
519                         candidates = current_candidate;
520                         last_candidate = current_candidate;
521                         ncandidates = 1;
522                 }
523                 else if (nmatch == nbestMatch)
524                 {
525                         last_candidate->next = current_candidate;
526                         last_candidate = current_candidate;
527                         ncandidates++;
528                 }
529         }
530
531         if (last_candidate)                     /* terminate rebuilt list */
532                 last_candidate->next = NULL;
533
534         if (ncandidates == 1)
535                 return candidates->oid;
536
537         /*
538          * Still too many candidates? Try assigning types for the unknown
539          * columns.
540          *
541          * First try: if we have an unknown and a non-unknown input, see whether
542          * there is a candidate all of whose input types are the same as the
543          * known input type (there can be at most one such candidate).  If so,
544          * use that candidate.  NOTE that this is cool only because operators
545          * can't have more than 2 args, so taking the last non-unknown as
546          * current_type can yield only one possibility if there is also an
547          * unknown.
548          */
549         unknownOids = FALSE;
550         current_type = UNKNOWNOID;
551         for (i = 0; i < nargs; i++)
552         {
553                 if ((input_typeids[i] != UNKNOWNOID)
554                         && (input_typeids[i] != InvalidOid))
555                         current_type = input_typeids[i];
556                 else
557                         unknownOids = TRUE;
558         }
559
560         if (unknownOids && (current_type != UNKNOWNOID))
561         {
562                 for (current_candidate = candidates;
563                          current_candidate != NULL;
564                          current_candidate = current_candidate->next)
565                 {
566                         current_typeids = current_candidate->args;
567                         nmatch = 0;
568                         for (i = 0; i < nargs; i++)
569                         {
570                                 if (current_type == current_typeids[i])
571                                         nmatch++;
572                         }
573                         if (nmatch == nargs)
574                                 return current_candidate->oid;
575                 }
576         }
577
578         /*
579          * Second try: same algorithm as for unknown resolution in
580          * parse_func.c.
581          *
582          * We do this by examining each unknown argument position to see if we
583          * can determine a "type category" for it.      If any candidate has an
584          * input datatype of STRING category, use STRING category (this bias
585          * towards STRING is appropriate since unknown-type literals look like
586          * strings).  Otherwise, if all the candidates agree on the type
587          * category of this argument position, use that category.  Otherwise,
588          * fail because we cannot determine a category.
589          *
590          * If we are able to determine a type category, also notice whether any
591          * of the candidates takes a preferred datatype within the category.
592          *
593          * Having completed this examination, remove candidates that accept the
594          * wrong category at any unknown position.      Also, if at least one
595          * candidate accepted a preferred type at a position, remove
596          * candidates that accept non-preferred types.
597          *
598          * If we are down to one candidate at the end, we win.
599          */
600         resolved_unknowns = false;
601         for (i = 0; i < nargs; i++)
602         {
603                 bool            have_conflict;
604
605                 if (input_typeids[i] != UNKNOWNOID)
606                         continue;
607                 resolved_unknowns = true;               /* assume we can do it */
608                 slot_category[i] = INVALID_TYPE;
609                 slot_has_preferred_type[i] = false;
610                 have_conflict = false;
611                 for (current_candidate = candidates;
612                          current_candidate != NULL;
613                          current_candidate = current_candidate->next)
614                 {
615                         current_typeids = current_candidate->args;
616                         current_type = current_typeids[i];
617                         current_category = TypeCategory(current_type);
618                         if (slot_category[i] == INVALID_TYPE)
619                         {
620                                 /* first candidate */
621                                 slot_category[i] = current_category;
622                                 slot_has_preferred_type[i] =
623                                         IsPreferredType(current_category, current_type);
624                         }
625                         else if (current_category == slot_category[i])
626                         {
627                                 /* more candidates in same category */
628                                 slot_has_preferred_type[i] |=
629                                         IsPreferredType(current_category, current_type);
630                         }
631                         else
632                         {
633                                 /* category conflict! */
634                                 if (current_category == STRING_TYPE)
635                                 {
636                                         /* STRING always wins if available */
637                                         slot_category[i] = current_category;
638                                         slot_has_preferred_type[i] =
639                                                 IsPreferredType(current_category, current_type);
640                                 }
641                                 else
642                                 {
643                                         /*
644                                          * Remember conflict, but keep going (might find
645                                          * STRING)
646                                          */
647                                         have_conflict = true;
648                                 }
649                         }
650                 }
651                 if (have_conflict && slot_category[i] != STRING_TYPE)
652                 {
653                         /* Failed to resolve category conflict at this position */
654                         resolved_unknowns = false;
655                         break;
656                 }
657         }
658
659         if (resolved_unknowns)
660         {
661                 /* Strip non-matching candidates */
662                 ncandidates = 0;
663                 last_candidate = NULL;
664                 for (current_candidate = candidates;
665                          current_candidate != NULL;
666                          current_candidate = current_candidate->next)
667                 {
668                         bool            keepit = true;
669
670                         current_typeids = current_candidate->args;
671                         for (i = 0; i < nargs; i++)
672                         {
673                                 if (input_typeids[i] != UNKNOWNOID)
674                                         continue;
675                                 current_type = current_typeids[i];
676                                 current_category = TypeCategory(current_type);
677                                 if (current_category != slot_category[i])
678                                 {
679                                         keepit = false;
680                                         break;
681                                 }
682                                 if (slot_has_preferred_type[i] &&
683                                         !IsPreferredType(current_category, current_type))
684                                 {
685                                         keepit = false;
686                                         break;
687                                 }
688                         }
689                         if (keepit)
690                         {
691                                 /* keep this candidate */
692                                 last_candidate = current_candidate;
693                                 ncandidates++;
694                         }
695                         else
696                         {
697                                 /* forget this candidate */
698                                 if (last_candidate)
699                                         last_candidate->next = current_candidate->next;
700                                 else
701                                         candidates = current_candidate->next;
702                         }
703                 }
704                 if (last_candidate)             /* terminate rebuilt list */
705                         last_candidate->next = NULL;
706         }
707
708         if (ncandidates == 1)
709                 return candidates->oid;
710
711         return InvalidOid;                      /* failed to determine a unique candidate */
712 }       /* oper_select_candidate() */
713
714
715 /* oper() -- search for a binary operator
716  * Given operator name, types of arg1 and arg2, return oper struct.
717  *
718  * IMPORTANT: the returned operator (if any) is only promised to be
719  * coercion-compatible with the input datatypes.  Do not use this if
720  * you need an exact- or binary-compatible match; see compatible_oper.
721  *
722  * If no matching operator found, return NULL if noError is true,
723  * raise an error if it is false.
724  *
725  * NOTE: on success, the returned object is a syscache entry.  The caller
726  * must ReleaseSysCache() the entry when done with it.
727  */
728 Operator
729 oper(List *opname, Oid ltypeId, Oid rtypeId, bool noError)
730 {
731         FuncCandidateList clist;
732         Oid                     operOid;
733         Oid                     inputOids[2];
734         HeapTuple       tup = NULL;
735
736         /* Get binary operators of given name */
737         clist = OpernameGetCandidates(opname, 'b');
738
739         /* No operators found? Then fail... */
740         if (clist != NULL)
741         {
742                 /*
743                  * Check for an "exact" match.
744                  */
745                 operOid = binary_oper_exact(ltypeId, rtypeId, clist);
746                 if (!OidIsValid(operOid))
747                 {
748                         /*
749                          * Otherwise, search for the most suitable candidate.
750                          */
751
752                         /*
753                          * Unspecified type for one of the arguments? then use the
754                          * other
755                          */
756                         if (rtypeId == InvalidOid)
757                                 rtypeId = ltypeId;
758                         else if (ltypeId == InvalidOid)
759                                 ltypeId = rtypeId;
760                         inputOids[0] = ltypeId;
761                         inputOids[1] = rtypeId;
762                         operOid = oper_select_candidate(2, inputOids, clist);
763                 }
764                 if (OidIsValid(operOid))
765                         tup = SearchSysCache(OPEROID,
766                                                                  ObjectIdGetDatum(operOid),
767                                                                  0, 0, 0);
768         }
769
770         if (!HeapTupleIsValid(tup) && !noError)
771                 op_error(opname, ltypeId, rtypeId);
772
773         return (Operator) tup;
774 }
775
776 /* compatible_oper()
777  *      given an opname and input datatypes, find a compatible binary operator
778  *
779  *      This is tighter than oper() because it will not return an operator that
780  *      requires coercion of the input datatypes (but binary-compatible operators
781  *      are accepted).  Otherwise, the semantics are the same.
782  */
783 Operator
784 compatible_oper(List *op, Oid arg1, Oid arg2, bool noError)
785 {
786         Operator        optup;
787         Form_pg_operator opform;
788
789         /* oper() will find the best available match */
790         optup = oper(op, arg1, arg2, noError);
791         if (optup == (Operator) NULL)
792                 return (Operator) NULL; /* must be noError case */
793
794         /* but is it good enough? */
795         opform = (Form_pg_operator) GETSTRUCT(optup);
796         if (IsBinaryCoercible(arg1, opform->oprleft) &&
797                 IsBinaryCoercible(arg2, opform->oprright))
798                 return optup;
799
800         /* nope... */
801         ReleaseSysCache(optup);
802
803         if (!noError)
804                 op_error(op, arg1, arg2);
805
806         return (Operator) NULL;
807 }
808
809 /* compatible_oper_opid() -- get OID of a binary operator
810  *
811  * This is a convenience routine that extracts only the operator OID
812  * from the result of compatible_oper().  InvalidOid is returned if the
813  * lookup fails and noError is true.
814  */
815 Oid
816 compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
817 {
818         Operator        optup;
819         Oid                     result;
820
821         optup = compatible_oper(op, arg1, arg2, noError);
822         if (optup != NULL)
823         {
824                 result = oprid(optup);
825                 ReleaseSysCache(optup);
826                 return result;
827         }
828         return InvalidOid;
829 }
830
831
832 /* right_oper() -- search for a unary right operator (operator on right)
833  * Given operator name and type of arg, return oper struct.
834  *
835  * IMPORTANT: the returned operator (if any) is only promised to be
836  * coercion-compatible with the input datatype.  Do not use this if
837  * you need an exact- or binary-compatible match.
838  *
839  * If no matching operator found, return NULL if noError is true,
840  * raise an error if it is false.
841  *
842  * NOTE: on success, the returned object is a syscache entry.  The caller
843  * must ReleaseSysCache() the entry when done with it.
844  */
845 Operator
846 right_oper(List *op, Oid arg, bool noError)
847 {
848         FuncCandidateList clist;
849         Oid                     operOid = InvalidOid;
850         HeapTuple       tup = NULL;
851
852         /* Find candidates */
853         clist = OpernameGetCandidates(op, 'r');
854
855         if (clist != NULL)
856         {
857                 /*
858                  * First, quickly check to see if there is an exactly matching
859                  * operator (there can be only one such entry in the list).
860                  */
861                 FuncCandidateList clisti;
862
863                 for (clisti = clist; clisti != NULL; clisti = clisti->next)
864                 {
865                         if (arg == clisti->args[0])
866                         {
867                                 operOid = clisti->oid;
868                                 break;
869                         }
870                 }
871
872                 if (!OidIsValid(operOid))
873                 {
874                         /*
875                          * We must run oper_select_candidate even if only one
876                          * candidate, otherwise we may falsely return a
877                          * non-type-compatible operator.
878                          */
879                         operOid = oper_select_candidate(1, &arg, clist);
880                 }
881                 if (OidIsValid(operOid))
882                         tup = SearchSysCache(OPEROID,
883                                                                  ObjectIdGetDatum(operOid),
884                                                                  0, 0, 0);
885         }
886
887         if (!HeapTupleIsValid(tup) && !noError)
888                 unary_op_error(op, arg, FALSE);
889
890         return (Operator) tup;
891 }
892
893
894 /* left_oper() -- search for a unary left operator (operator on left)
895  * Given operator name and type of arg, return oper struct.
896  *
897  * IMPORTANT: the returned operator (if any) is only promised to be
898  * coercion-compatible with the input datatype.  Do not use this if
899  * you need an exact- or binary-compatible match.
900  *
901  * If no matching operator found, return NULL if noError is true,
902  * raise an error if it is false.
903  *
904  * NOTE: on success, the returned object is a syscache entry.  The caller
905  * must ReleaseSysCache() the entry when done with it.
906  */
907 Operator
908 left_oper(List *op, Oid arg, bool noError)
909 {
910         FuncCandidateList clist;
911         Oid                     operOid = InvalidOid;
912         HeapTuple       tup = NULL;
913
914         /* Find candidates */
915         clist = OpernameGetCandidates(op, 'l');
916
917         if (clist != NULL)
918         {
919                 /*
920                  * First, quickly check to see if there is an exactly matching
921                  * operator (there can be only one such entry in the list).
922                  *
923                  * The returned list has args in the form (0, oprright).  Move the
924                  * useful data into args[0] to keep oper_select_candidate simple.
925                  * XXX we are assuming here that we may scribble on the list!
926                  */
927                 FuncCandidateList clisti;
928
929                 for (clisti = clist; clisti != NULL; clisti = clisti->next)
930                 {
931                         clisti->args[0] = clisti->args[1];
932                         if (arg == clisti->args[0])
933                         {
934                                 operOid = clisti->oid;
935                                 break;
936                         }
937                 }
938
939                 if (!OidIsValid(operOid))
940                 {
941                         /*
942                          * We must run oper_select_candidate even if only one
943                          * candidate, otherwise we may falsely return a
944                          * non-type-compatible operator.
945                          */
946                         operOid = oper_select_candidate(1, &arg, clist);
947                 }
948                 if (OidIsValid(operOid))
949                         tup = SearchSysCache(OPEROID,
950                                                                  ObjectIdGetDatum(operOid),
951                                                                  0, 0, 0);
952         }
953
954         if (!HeapTupleIsValid(tup) && !noError)
955                 unary_op_error(op, arg, TRUE);
956
957         return (Operator) tup;
958 }
959
960
961 /* op_error()
962  * Give a somewhat useful error message when the operator for two types
963  * is not found.
964  */
965 static void
966 op_error(List *op, Oid arg1, Oid arg2)
967 {
968         if (!typeidIsValid(arg1))
969                 elog(ERROR, "Left hand side of operator '%s' has an unknown type"
970                          "\n\tProbably a bad attribute name",
971                          NameListToString(op));
972
973         if (!typeidIsValid(arg2))
974                 elog(ERROR, "Right hand side of operator %s has an unknown type"
975                          "\n\tProbably a bad attribute name",
976                          NameListToString(op));
977
978         elog(ERROR, "Unable to identify an operator '%s' for types '%s' and '%s'"
979                  "\n\tYou will have to retype this query using an explicit cast",
980                  NameListToString(op),
981                  format_type_be(arg1), format_type_be(arg2));
982 }
983
984 /* unary_op_error()
985  * Give a somewhat useful error message when the operator for one type
986  * is not found.
987  */
988 static void
989 unary_op_error(List *op, Oid arg, bool is_left_op)
990 {
991         if (!typeidIsValid(arg))
992         {
993                 if (is_left_op)
994                         elog(ERROR, "operand of prefix operator '%s' has an unknown type"
995                                  "\n\t(probably an invalid column reference)",
996                                  NameListToString(op));
997                 else
998                         elog(ERROR, "operand of postfix operator '%s' has an unknown type"
999                                  "\n\t(probably an invalid column reference)",
1000                                  NameListToString(op));
1001         }
1002         else
1003         {
1004                 if (is_left_op)
1005                         elog(ERROR, "Unable to identify a prefix operator '%s' for type '%s'"
1006                            "\n\tYou may need to add parentheses or an explicit cast",
1007                                  NameListToString(op), format_type_be(arg));
1008                 else
1009                         elog(ERROR, "Unable to identify a postfix operator '%s' for type '%s'"
1010                            "\n\tYou may need to add parentheses or an explicit cast",
1011                                  NameListToString(op), format_type_be(arg));
1012         }
1013 }
1014
1015
1016 /*
1017  * make_op()
1018  *              Operator expression construction.
1019  *
1020  * Transform operator expression ensuring type compatibility.
1021  * This is where some type conversion happens.
1022  *
1023  * As with coerce_type, pstate may be NULL if no special unknown-Param
1024  * processing is wanted.
1025  */
1026 Expr *
1027 make_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree)
1028 {
1029         Oid                     ltypeId,
1030                                 rtypeId;
1031         Operator        tup;
1032         Expr       *result;
1033
1034         /* Select the operator */
1035         if (rtree == NULL)
1036         {
1037                 /* right operator */
1038                 ltypeId = exprType(ltree);
1039                 rtypeId = InvalidOid;
1040                 tup = right_oper(opname, ltypeId, false);
1041         }
1042         else if (ltree == NULL)
1043         {
1044                 /* left operator */
1045                 rtypeId = exprType(rtree);
1046                 ltypeId = InvalidOid;
1047                 tup = left_oper(opname, rtypeId, false);
1048         }
1049         else
1050         {
1051                 /* otherwise, binary operator */
1052                 ltypeId = exprType(ltree);
1053                 rtypeId = exprType(rtree);
1054                 tup = oper(opname, ltypeId, rtypeId, false);
1055         }
1056
1057         /* Do typecasting and build the expression tree */
1058         result = make_op_expr(pstate, tup, ltree, rtree, ltypeId, rtypeId);
1059
1060         ReleaseSysCache(tup);
1061
1062         return result;
1063 }
1064
1065
1066 /*
1067  * make_op_expr()
1068  *              Build operator expression using an already-looked-up operator.
1069  *
1070  * As with coerce_type, pstate may be NULL if no special unknown-Param
1071  * processing is wanted.
1072  */
1073 Expr *
1074 make_op_expr(ParseState *pstate, Operator op,
1075                          Node *ltree, Node *rtree,
1076                          Oid ltypeId, Oid rtypeId)
1077 {
1078         Form_pg_operator opform = (Form_pg_operator) GETSTRUCT(op);
1079         Oid                     actual_arg_types[2];
1080         Oid                     declared_arg_types[2];
1081         int                     nargs;
1082         List       *args;
1083         Oid                     rettype;
1084         OpExpr     *result;
1085
1086         if (rtree == NULL)
1087         {
1088                 /* right operator */
1089                 args = makeList1(ltree);
1090                 actual_arg_types[0] = ltypeId;
1091                 declared_arg_types[0] = opform->oprleft;
1092                 nargs = 1;
1093         }
1094         else if (ltree == NULL)
1095         {
1096                 /* left operator */
1097                 args = makeList1(rtree);
1098                 actual_arg_types[0] = rtypeId;
1099                 declared_arg_types[0] = opform->oprright;
1100                 nargs = 1;
1101         }
1102         else
1103         {
1104                 /* otherwise, binary operator */
1105                 args = makeList2(ltree, rtree);
1106                 actual_arg_types[0] = ltypeId;
1107                 actual_arg_types[1] = rtypeId;
1108                 declared_arg_types[0] = opform->oprleft;
1109                 declared_arg_types[1] = opform->oprright;
1110                 nargs = 2;
1111         }
1112
1113         /*
1114          * enforce consistency with ANYARRAY and ANYELEMENT argument and
1115          * return types, possibly adjusting return type or declared_arg_types
1116          * (which will be used as the cast destination by make_fn_arguments)
1117          */
1118         rettype = enforce_generic_type_consistency(actual_arg_types,
1119                                                                                            declared_arg_types,
1120                                                                                            nargs,
1121                                                                                            opform->oprresult);
1122
1123         /* perform the necessary typecasting of arguments */
1124         make_fn_arguments(pstate, args, actual_arg_types, declared_arg_types);
1125
1126         /* and build the expression node */
1127         result = makeNode(OpExpr);
1128         result->opno = oprid(op);
1129         result->opfuncid = InvalidOid;
1130         result->opresulttype = rettype;
1131         result->opretset = get_func_retset(opform->oprcode);
1132         result->args = args;
1133
1134         return (Expr *) result;
1135 }