]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_oper.c
Improve the plan cache invalidation mechanism to make it invalidate plans
[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-2008, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/parser/parse_oper.c,v 1.106 2008/09/09 18:58:08 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "postgres.h"
17
18 #include "catalog/pg_operator.h"
19 #include "catalog/pg_type.h"
20 #include "lib/stringinfo.h"
21 #include "nodes/nodeFuncs.h"
22 #include "parser/parse_coerce.h"
23 #include "parser/parse_func.h"
24 #include "parser/parse_oper.h"
25 #include "parser/parse_type.h"
26 #include "utils/builtins.h"
27 #include "utils/hsearch.h"
28 #include "utils/inval.h"
29 #include "utils/lsyscache.h"
30 #include "utils/syscache.h"
31 #include "utils/typcache.h"
32
33
34 /*
35  * The lookup key for the operator lookaside hash table.  Unused bits must be
36  * zeroes to ensure hashing works consistently --- in particular, oprname
37  * must be zero-padded and any unused entries in search_path must be zero.
38  *
39  * search_path contains the actual search_path with which the entry was
40  * derived (minus temp namespace if any), or else the single specified
41  * schema OID if we are looking up an explicitly-qualified operator name.
42  *
43  * search_path has to be fixed-length since the hashtable code insists on
44  * fixed-size keys.  If your search path is longer than that, we just punt
45  * and don't cache anything.
46  */
47
48 /* If your search_path is longer than this, sucks to be you ... */
49 #define MAX_CACHED_PATH_LEN             16
50
51 typedef struct OprCacheKey
52 {
53         char            oprname[NAMEDATALEN];
54         Oid                     left_arg;               /* Left input OID, or 0 if prefix op */
55         Oid                     right_arg;              /* Right input OID, or 0 if postfix op */
56         Oid                     search_path[MAX_CACHED_PATH_LEN];
57 } OprCacheKey;
58
59 typedef struct OprCacheEntry
60 {
61         /* the hash lookup key MUST BE FIRST */
62         OprCacheKey     key;
63
64         Oid                     opr_oid;                /* OID of the resolved operator */
65 } OprCacheEntry;
66
67
68 static Oid      binary_oper_exact(List *opname, Oid arg1, Oid arg2);
69 static FuncDetailCode oper_select_candidate(int nargs,
70                                           Oid *input_typeids,
71                                           FuncCandidateList candidates,
72                                           Oid *operOid);
73 static const char *op_signature_string(List *op, char oprkind,
74                                         Oid arg1, Oid arg2);
75 static void op_error(ParseState *pstate, List *op, char oprkind,
76                  Oid arg1, Oid arg2,
77                  FuncDetailCode fdresult, int location);
78 static bool make_oper_cache_key(OprCacheKey *key, List *opname,
79                                                                 Oid ltypeId, Oid rtypeId);
80 static Oid      find_oper_cache_entry(OprCacheKey *key);
81 static void make_oper_cache_entry(OprCacheKey *key, Oid opr_oid);
82 static void InvalidateOprCacheCallBack(Datum arg, int cacheid, ItemPointer tuplePtr);
83
84
85 /*
86  * LookupOperName
87  *              Given a possibly-qualified operator name and exact input datatypes,
88  *              look up the operator.
89  *
90  * Pass oprleft = InvalidOid for a prefix op, oprright = InvalidOid for
91  * a postfix op.
92  *
93  * If the operator name is not schema-qualified, it is sought in the current
94  * namespace search path.
95  *
96  * If the operator is not found, we return InvalidOid if noError is true,
97  * else raise an error.  pstate and location are used only to report the
98  * error position; pass NULL/-1 if not available.
99  */
100 Oid
101 LookupOperName(ParseState *pstate, List *opername, Oid oprleft, Oid oprright,
102                            bool noError, int location)
103 {
104         Oid                     result;
105
106         result = OpernameGetOprid(opername, oprleft, oprright);
107         if (OidIsValid(result))
108                 return result;
109
110         /* we don't use op_error here because only an exact match is wanted */
111         if (!noError)
112         {
113                 char            oprkind;
114
115                 if (!OidIsValid(oprleft))
116                         oprkind = 'l';
117                 else if (!OidIsValid(oprright))
118                         oprkind = 'r';
119                 else
120                         oprkind = 'b';
121
122                 ereport(ERROR,
123                                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
124                                  errmsg("operator does not exist: %s",
125                                                 op_signature_string(opername, oprkind,
126                                                                                         oprleft, oprright)),
127                                  parser_errposition(pstate, location)));
128         }
129
130         return InvalidOid;
131 }
132
133 /*
134  * LookupOperNameTypeNames
135  *              Like LookupOperName, but the argument types are specified by
136  *              TypeName nodes.
137  *
138  * Pass oprleft = NULL for a prefix op, oprright = NULL for a postfix op.
139  */
140 Oid
141 LookupOperNameTypeNames(ParseState *pstate, List *opername,
142                                                 TypeName *oprleft, TypeName *oprright,
143                                                 bool noError, int location)
144 {
145         Oid                     leftoid,
146                                 rightoid;
147
148         if (oprleft == NULL)
149                 leftoid = InvalidOid;
150         else
151                 leftoid = typenameTypeId(pstate, oprleft, NULL);
152
153         if (oprright == NULL)
154                 rightoid = InvalidOid;
155         else
156                 rightoid = typenameTypeId(pstate, oprright, NULL);
157
158         return LookupOperName(pstate, opername, leftoid, rightoid,
159                                                   noError, location);
160 }
161
162 /*
163  * get_sort_group_operators - get default sorting/grouping operators for type
164  *
165  * We fetch the "<", "=", and ">" operators all at once to reduce lookup
166  * overhead (knowing that most callers will be interested in at least two).
167  * However, a given datatype might have only an "=" operator, if it is
168  * hashable but not sortable.  (Other combinations of present and missing
169  * operators shouldn't happen, unless the system catalogs are messed up.)
170  *
171  * If an operator is missing and the corresponding needXX flag is true,
172  * throw a standard error message, else return InvalidOid.
173  *
174  * Callers can pass NULL pointers for any results they don't care to get.
175  *
176  * Note: the results are guaranteed to be exact or binary-compatible matches,
177  * since most callers are not prepared to cope with adding any run-time type
178  * coercion steps.
179  */
180 void
181 get_sort_group_operators(Oid argtype,
182                                                  bool needLT, bool needEQ, bool needGT,
183                                                  Oid *ltOpr, Oid *eqOpr, Oid *gtOpr)
184 {
185         TypeCacheEntry *typentry;
186         Oid                     lt_opr;
187         Oid                     eq_opr;
188         Oid                     gt_opr;
189
190         /*
191          * Look up the operators using the type cache.
192          *
193          * Note: the search algorithm used by typcache.c ensures that the results
194          * are consistent, ie all from the same opclass.
195          */
196         typentry = lookup_type_cache(argtype,
197                                         TYPECACHE_LT_OPR | TYPECACHE_EQ_OPR | TYPECACHE_GT_OPR);
198         lt_opr = typentry->lt_opr;
199         eq_opr = typentry->eq_opr;
200         gt_opr = typentry->gt_opr;
201
202         /*
203          * If the datatype is an array, then we can use array_lt and friends ...
204          * but only if there are suitable operators for the element type.  (This
205          * check is not in the raw typcache.c code ... should it be?)  Testing
206          * all three operator IDs here should be redundant.
207          */
208         if (lt_opr == ARRAY_LT_OP ||
209                 eq_opr == ARRAY_EQ_OP ||
210                 gt_opr == ARRAY_GT_OP)
211         {
212                 Oid                     elem_type = get_element_type(argtype);
213
214                 if (OidIsValid(elem_type))
215                 {
216                         typentry = lookup_type_cache(elem_type,
217                                         TYPECACHE_LT_OPR | TYPECACHE_EQ_OPR | TYPECACHE_GT_OPR);
218                         if (!OidIsValid(typentry->lt_opr))
219                                 lt_opr = InvalidOid;    /* element type has no "<" */
220                         if (!OidIsValid(typentry->eq_opr))
221                                 eq_opr = InvalidOid;    /* element type has no "=" */
222                         if (!OidIsValid(typentry->gt_opr))
223                                 gt_opr = InvalidOid;    /* element type has no ">" */
224                 }
225                 else
226                         lt_opr = eq_opr = gt_opr = InvalidOid;  /* bogus array type? */
227         }
228
229         /* Report errors if needed */
230         if ((needLT && !OidIsValid(lt_opr)) ||
231                 (needGT && !OidIsValid(gt_opr)))
232                 ereport(ERROR,
233                                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
234                                  errmsg("could not identify an ordering operator for type %s",
235                                                 format_type_be(argtype)),
236                  errhint("Use an explicit ordering operator or modify the query.")));
237         if (needEQ && !OidIsValid(eq_opr))
238                 ereport(ERROR,
239                                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
240                                  errmsg("could not identify an equality operator for type %s",
241                                                 format_type_be(argtype))));
242
243         /* Return results as needed */
244         if (ltOpr)
245                 *ltOpr = lt_opr;
246         if (eqOpr)
247                 *eqOpr = eq_opr;
248         if (gtOpr)
249                 *gtOpr = gt_opr;
250 }
251
252
253 /* given operator tuple, return the operator OID */
254 Oid
255 oprid(Operator op)
256 {
257         return HeapTupleGetOid(op);
258 }
259
260 /* given operator tuple, return the underlying function's OID */
261 Oid
262 oprfuncid(Operator op)
263 {
264         Form_pg_operator pgopform = (Form_pg_operator) GETSTRUCT(op);
265
266         return pgopform->oprcode;
267 }
268
269
270 /* binary_oper_exact()
271  * Check for an "exact" match to the specified operand types.
272  *
273  * If one operand is an unknown literal, assume it should be taken to be
274  * the same type as the other operand for this purpose.  Also, consider
275  * the possibility that the other operand is a domain type that needs to
276  * be reduced to its base type to find an "exact" match.
277  */
278 static Oid
279 binary_oper_exact(List *opname, Oid arg1, Oid arg2)
280 {
281         Oid                     result;
282         bool            was_unknown = false;
283
284         /* Unspecified type for one of the arguments? then use the other */
285         if ((arg1 == UNKNOWNOID) && (arg2 != InvalidOid))
286         {
287                 arg1 = arg2;
288                 was_unknown = true;
289         }
290         else if ((arg2 == UNKNOWNOID) && (arg1 != InvalidOid))
291         {
292                 arg2 = arg1;
293                 was_unknown = true;
294         }
295
296         result = OpernameGetOprid(opname, arg1, arg2);
297         if (OidIsValid(result))
298                 return result;
299
300         if (was_unknown)
301         {
302                 /* arg1 and arg2 are the same here, need only look at arg1 */
303                 Oid                     basetype = getBaseType(arg1);
304
305                 if (basetype != arg1)
306                 {
307                         result = OpernameGetOprid(opname, basetype, basetype);
308                         if (OidIsValid(result))
309                                 return result;
310                 }
311         }
312
313         return InvalidOid;
314 }
315
316
317 /* oper_select_candidate()
318  *              Given the input argtype array and one or more candidates
319  *              for the operator, attempt to resolve the conflict.
320  *
321  * Returns FUNCDETAIL_NOTFOUND, FUNCDETAIL_MULTIPLE, or FUNCDETAIL_NORMAL.
322  * In the success case the Oid of the best candidate is stored in *operOid.
323  *
324  * Note that the caller has already determined that there is no candidate
325  * exactly matching the input argtype(s).  Incompatible candidates are not yet
326  * pruned away, however.
327  */
328 static FuncDetailCode
329 oper_select_candidate(int nargs,
330                                           Oid *input_typeids,
331                                           FuncCandidateList candidates,
332                                           Oid *operOid)         /* output argument */
333 {
334         int                     ncandidates;
335
336         /*
337          * Delete any candidates that cannot actually accept the given input
338          * types, whether directly or by coercion.
339          */
340         ncandidates = func_match_argtypes(nargs, input_typeids,
341                                                                           candidates, &candidates);
342
343         /* Done if no candidate or only one candidate survives */
344         if (ncandidates == 0)
345         {
346                 *operOid = InvalidOid;
347                 return FUNCDETAIL_NOTFOUND;
348         }
349         if (ncandidates == 1)
350         {
351                 *operOid = candidates->oid;
352                 return FUNCDETAIL_NORMAL;
353         }
354
355         /*
356          * Use the same heuristics as for ambiguous functions to resolve the
357          * conflict.
358          */
359         candidates = func_select_candidate(nargs, input_typeids, candidates);
360
361         if (candidates)
362         {
363                 *operOid = candidates->oid;
364                 return FUNCDETAIL_NORMAL;
365         }
366
367         *operOid = InvalidOid;
368         return FUNCDETAIL_MULTIPLE; /* failed to select a best candidate */
369 }
370
371
372 /* oper() -- search for a binary operator
373  * Given operator name, types of arg1 and arg2, return oper struct.
374  *
375  * IMPORTANT: the returned operator (if any) is only promised to be
376  * coercion-compatible with the input datatypes.  Do not use this if
377  * you need an exact- or binary-compatible match; see compatible_oper.
378  *
379  * If no matching operator found, return NULL if noError is true,
380  * raise an error if it is false.  pstate and location are used only to report
381  * the error position; pass NULL/-1 if not available.
382  *
383  * NOTE: on success, the returned object is a syscache entry.  The caller
384  * must ReleaseSysCache() the entry when done with it.
385  */
386 Operator
387 oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId,
388          bool noError, int location)
389 {
390         Oid                     operOid;
391         OprCacheKey     key;
392         bool            key_ok;
393         FuncDetailCode fdresult = FUNCDETAIL_NOTFOUND;
394         HeapTuple       tup = NULL;
395
396         /*
397          * Try to find the mapping in the lookaside cache.
398          */
399         key_ok = make_oper_cache_key(&key, opname, ltypeId, rtypeId);
400         if (key_ok)
401         {
402                 operOid = find_oper_cache_entry(&key);
403                 if (OidIsValid(operOid))
404                 {
405                         tup = SearchSysCache(OPEROID,
406                                                                  ObjectIdGetDatum(operOid),
407                                                                  0, 0, 0);
408                         if (HeapTupleIsValid(tup))
409                                 return (Operator) tup;
410                 }
411         }
412
413         /*
414          * First try for an "exact" match.
415          */
416         operOid = binary_oper_exact(opname, ltypeId, rtypeId);
417         if (!OidIsValid(operOid))
418         {
419                 /*
420                  * Otherwise, search for the most suitable candidate.
421                  */
422                 FuncCandidateList clist;
423
424                 /* Get binary operators of given name */
425                 clist = OpernameGetCandidates(opname, 'b');
426
427                 /* No operators found? Then fail... */
428                 if (clist != NULL)
429                 {
430                         /*
431                          * Unspecified type for one of the arguments? then use the other
432                          * (XXX this is probably dead code?)
433                          */
434                         Oid                     inputOids[2];
435
436                         if (rtypeId == InvalidOid)
437                                 rtypeId = ltypeId;
438                         else if (ltypeId == InvalidOid)
439                                 ltypeId = rtypeId;
440                         inputOids[0] = ltypeId;
441                         inputOids[1] = rtypeId;
442                         fdresult = oper_select_candidate(2, inputOids, clist, &operOid);
443                 }
444         }
445
446         if (OidIsValid(operOid))
447                 tup = SearchSysCache(OPEROID,
448                                                          ObjectIdGetDatum(operOid),
449                                                          0, 0, 0);
450
451         if (HeapTupleIsValid(tup))
452         {
453                 if (key_ok)
454                         make_oper_cache_entry(&key, operOid);
455         }
456         else if (!noError)
457                 op_error(pstate, opname, 'b', ltypeId, rtypeId, fdresult, location);
458
459         return (Operator) tup;
460 }
461
462 /* compatible_oper()
463  *      given an opname and input datatypes, find a compatible binary operator
464  *
465  *      This is tighter than oper() because it will not return an operator that
466  *      requires coercion of the input datatypes (but binary-compatible operators
467  *      are accepted).  Otherwise, the semantics are the same.
468  */
469 Operator
470 compatible_oper(ParseState *pstate, List *op, Oid arg1, Oid arg2,
471                                 bool noError, int location)
472 {
473         Operator        optup;
474         Form_pg_operator opform;
475
476         /* oper() will find the best available match */
477         optup = oper(pstate, op, arg1, arg2, noError, location);
478         if (optup == (Operator) NULL)
479                 return (Operator) NULL; /* must be noError case */
480
481         /* but is it good enough? */
482         opform = (Form_pg_operator) GETSTRUCT(optup);
483         if (IsBinaryCoercible(arg1, opform->oprleft) &&
484                 IsBinaryCoercible(arg2, opform->oprright))
485                 return optup;
486
487         /* nope... */
488         ReleaseSysCache(optup);
489
490         if (!noError)
491                 ereport(ERROR,
492                                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
493                                  errmsg("operator requires run-time type coercion: %s",
494                                                 op_signature_string(op, 'b', arg1, arg2)),
495                                  parser_errposition(pstate, location)));
496
497         return (Operator) NULL;
498 }
499
500 /* compatible_oper_opid() -- get OID of a binary operator
501  *
502  * This is a convenience routine that extracts only the operator OID
503  * from the result of compatible_oper().  InvalidOid is returned if the
504  * lookup fails and noError is true.
505  */
506 Oid
507 compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
508 {
509         Operator        optup;
510         Oid                     result;
511
512         optup = compatible_oper(NULL, op, arg1, arg2, noError, -1);
513         if (optup != NULL)
514         {
515                 result = oprid(optup);
516                 ReleaseSysCache(optup);
517                 return result;
518         }
519         return InvalidOid;
520 }
521
522
523 /* right_oper() -- search for a unary right operator (postfix operator)
524  * Given operator name and type of arg, return oper struct.
525  *
526  * IMPORTANT: the returned operator (if any) is only promised to be
527  * coercion-compatible with the input datatype.  Do not use this if
528  * you need an exact- or binary-compatible match.
529  *
530  * If no matching operator found, return NULL if noError is true,
531  * raise an error if it is false.  pstate and location are used only to report
532  * the error position; pass NULL/-1 if not available.
533  *
534  * NOTE: on success, the returned object is a syscache entry.  The caller
535  * must ReleaseSysCache() the entry when done with it.
536  */
537 Operator
538 right_oper(ParseState *pstate, List *op, Oid arg, bool noError, int location)
539 {
540         Oid                     operOid;
541         OprCacheKey     key;
542         bool            key_ok;
543         FuncDetailCode fdresult = FUNCDETAIL_NOTFOUND;
544         HeapTuple       tup = NULL;
545
546         /*
547          * Try to find the mapping in the lookaside cache.
548          */
549         key_ok = make_oper_cache_key(&key, op, arg, InvalidOid);
550         if (key_ok)
551         {
552                 operOid = find_oper_cache_entry(&key);
553                 if (OidIsValid(operOid))
554                 {
555                         tup = SearchSysCache(OPEROID,
556                                                                  ObjectIdGetDatum(operOid),
557                                                                  0, 0, 0);
558                         if (HeapTupleIsValid(tup))
559                                 return (Operator) tup;
560                 }
561         }
562
563         /*
564          * First try for an "exact" match.
565          */
566         operOid = OpernameGetOprid(op, arg, InvalidOid);
567         if (!OidIsValid(operOid))
568         {
569                 /*
570                  * Otherwise, search for the most suitable candidate.
571                  */
572                 FuncCandidateList clist;
573
574                 /* Get postfix operators of given name */
575                 clist = OpernameGetCandidates(op, 'r');
576
577                 /* No operators found? Then fail... */
578                 if (clist != NULL)
579                 {
580                         /*
581                          * We must run oper_select_candidate even if only one candidate,
582                          * otherwise we may falsely return a non-type-compatible operator.
583                          */
584                         fdresult = oper_select_candidate(1, &arg, clist, &operOid);
585                 }
586         }
587
588         if (OidIsValid(operOid))
589                 tup = SearchSysCache(OPEROID,
590                                                          ObjectIdGetDatum(operOid),
591                                                          0, 0, 0);
592
593         if (HeapTupleIsValid(tup))
594         {
595                 if (key_ok)
596                         make_oper_cache_entry(&key, operOid);
597         }
598         else if (!noError)
599                 op_error(pstate, op, 'r', arg, InvalidOid, fdresult, location);
600
601         return (Operator) tup;
602 }
603
604
605 /* left_oper() -- search for a unary left operator (prefix operator)
606  * Given operator name and type of arg, return oper struct.
607  *
608  * IMPORTANT: the returned operator (if any) is only promised to be
609  * coercion-compatible with the input datatype.  Do not use this if
610  * you need an exact- or binary-compatible match.
611  *
612  * If no matching operator found, return NULL if noError is true,
613  * raise an error if it is false.  pstate and location are used only to report
614  * the error position; pass NULL/-1 if not available.
615  *
616  * NOTE: on success, the returned object is a syscache entry.  The caller
617  * must ReleaseSysCache() the entry when done with it.
618  */
619 Operator
620 left_oper(ParseState *pstate, List *op, Oid arg, bool noError, int location)
621 {
622         Oid                     operOid;
623         OprCacheKey     key;
624         bool            key_ok;
625         FuncDetailCode fdresult = FUNCDETAIL_NOTFOUND;
626         HeapTuple       tup = NULL;
627
628         /*
629          * Try to find the mapping in the lookaside cache.
630          */
631         key_ok = make_oper_cache_key(&key, op, InvalidOid, arg);
632         if (key_ok)
633         {
634                 operOid = find_oper_cache_entry(&key);
635                 if (OidIsValid(operOid))
636                 {
637                         tup = SearchSysCache(OPEROID,
638                                                                  ObjectIdGetDatum(operOid),
639                                                                  0, 0, 0);
640                         if (HeapTupleIsValid(tup))
641                                 return (Operator) tup;
642                 }
643         }
644
645         /*
646          * First try for an "exact" match.
647          */
648         operOid = OpernameGetOprid(op, InvalidOid, arg);
649         if (!OidIsValid(operOid))
650         {
651                 /*
652                  * Otherwise, search for the most suitable candidate.
653                  */
654                 FuncCandidateList clist;
655
656                 /* Get prefix operators of given name */
657                 clist = OpernameGetCandidates(op, 'l');
658
659                 /* No operators found? Then fail... */
660                 if (clist != NULL)
661                 {
662                         /*
663                          * The returned list has args in the form (0, oprright). Move the
664                          * useful data into args[0] to keep oper_select_candidate simple.
665                          * XXX we are assuming here that we may scribble on the list!
666                          */
667                         FuncCandidateList clisti;
668
669                         for (clisti = clist; clisti != NULL; clisti = clisti->next)
670                         {
671                                 clisti->args[0] = clisti->args[1];
672                         }
673
674                         /*
675                          * We must run oper_select_candidate even if only one candidate,
676                          * otherwise we may falsely return a non-type-compatible operator.
677                          */
678                         fdresult = oper_select_candidate(1, &arg, clist, &operOid);
679                 }
680         }
681
682         if (OidIsValid(operOid))
683                 tup = SearchSysCache(OPEROID,
684                                                          ObjectIdGetDatum(operOid),
685                                                          0, 0, 0);
686
687         if (HeapTupleIsValid(tup))
688         {
689                 if (key_ok)
690                         make_oper_cache_entry(&key, operOid);
691         }
692         else if (!noError)
693                 op_error(pstate, op, 'l', InvalidOid, arg, fdresult, location);
694
695         return (Operator) tup;
696 }
697
698 /*
699  * op_signature_string
700  *              Build a string representing an operator name, including arg type(s).
701  *              The result is something like "integer + integer".
702  *
703  * This is typically used in the construction of operator-not-found error
704  * messages.
705  */
706 static const char *
707 op_signature_string(List *op, char oprkind, Oid arg1, Oid arg2)
708 {
709         StringInfoData argbuf;
710
711         initStringInfo(&argbuf);
712
713         if (oprkind != 'l')
714                 appendStringInfo(&argbuf, "%s ", format_type_be(arg1));
715
716         appendStringInfoString(&argbuf, NameListToString(op));
717
718         if (oprkind != 'r')
719                 appendStringInfo(&argbuf, " %s", format_type_be(arg2));
720
721         return argbuf.data;                     /* return palloc'd string buffer */
722 }
723
724 /*
725  * op_error - utility routine to complain about an unresolvable operator
726  */
727 static void
728 op_error(ParseState *pstate, List *op, char oprkind,
729                  Oid arg1, Oid arg2,
730                  FuncDetailCode fdresult, int location)
731 {
732         if (fdresult == FUNCDETAIL_MULTIPLE)
733                 ereport(ERROR,
734                                 (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
735                                  errmsg("operator is not unique: %s",
736                                                 op_signature_string(op, oprkind, arg1, arg2)),
737                                  errhint("Could not choose a best candidate operator. "
738                                                  "You might need to add explicit type casts."),
739                                  parser_errposition(pstate, location)));
740         else
741                 ereport(ERROR,
742                                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
743                                  errmsg("operator does not exist: %s",
744                                                 op_signature_string(op, oprkind, arg1, arg2)),
745                   errhint("No operator matches the given name and argument type(s). "
746                                   "You might need to add explicit type casts."),
747                                  parser_errposition(pstate, location)));
748 }
749
750 /*
751  * make_op()
752  *              Operator expression construction.
753  *
754  * Transform operator expression ensuring type compatibility.
755  * This is where some type conversion happens.
756  *
757  * As with coerce_type, pstate may be NULL if no special unknown-Param
758  * processing is wanted.
759  */
760 Expr *
761 make_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree,
762                 int location)
763 {
764         Oid                     ltypeId,
765                                 rtypeId;
766         Operator        tup;
767         Form_pg_operator opform;
768         Oid                     actual_arg_types[2];
769         Oid                     declared_arg_types[2];
770         int                     nargs;
771         List       *args;
772         Oid                     rettype;
773         OpExpr     *result;
774
775         /* Select the operator */
776         if (rtree == NULL)
777         {
778                 /* right operator */
779                 ltypeId = exprType(ltree);
780                 rtypeId = InvalidOid;
781                 tup = right_oper(pstate, opname, ltypeId, false, location);
782         }
783         else if (ltree == NULL)
784         {
785                 /* left operator */
786                 rtypeId = exprType(rtree);
787                 ltypeId = InvalidOid;
788                 tup = left_oper(pstate, opname, rtypeId, false, location);
789         }
790         else
791         {
792                 /* otherwise, binary operator */
793                 ltypeId = exprType(ltree);
794                 rtypeId = exprType(rtree);
795                 tup = oper(pstate, opname, ltypeId, rtypeId, false, location);
796         }
797
798         opform = (Form_pg_operator) GETSTRUCT(tup);
799
800         /* Check it's not a shell */
801         if (!RegProcedureIsValid(opform->oprcode))
802                 ereport(ERROR,
803                                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
804                                  errmsg("operator is only a shell: %s",
805                                                 op_signature_string(opname,
806                                                                                         opform->oprkind,
807                                                                                         opform->oprleft,
808                                                                                         opform->oprright)),
809                                  parser_errposition(pstate, location)));
810
811         /* Do typecasting and build the expression tree */
812         if (rtree == NULL)
813         {
814                 /* right operator */
815                 args = list_make1(ltree);
816                 actual_arg_types[0] = ltypeId;
817                 declared_arg_types[0] = opform->oprleft;
818                 nargs = 1;
819         }
820         else if (ltree == NULL)
821         {
822                 /* left operator */
823                 args = list_make1(rtree);
824                 actual_arg_types[0] = rtypeId;
825                 declared_arg_types[0] = opform->oprright;
826                 nargs = 1;
827         }
828         else
829         {
830                 /* otherwise, binary operator */
831                 args = list_make2(ltree, rtree);
832                 actual_arg_types[0] = ltypeId;
833                 actual_arg_types[1] = rtypeId;
834                 declared_arg_types[0] = opform->oprleft;
835                 declared_arg_types[1] = opform->oprright;
836                 nargs = 2;
837         }
838
839         /*
840          * enforce consistency with polymorphic argument and return types,
841          * possibly adjusting return type or declared_arg_types (which will be
842          * used as the cast destination by make_fn_arguments)
843          */
844         rettype = enforce_generic_type_consistency(actual_arg_types,
845                                                                                            declared_arg_types,
846                                                                                            nargs,
847                                                                                            opform->oprresult,
848                                                                                            false);
849
850         /* perform the necessary typecasting of arguments */
851         make_fn_arguments(pstate, args, actual_arg_types, declared_arg_types);
852
853         /* and build the expression node */
854         result = makeNode(OpExpr);
855         result->opno = oprid(tup);
856         result->opfuncid = opform->oprcode;
857         result->opresulttype = rettype;
858         result->opretset = get_func_retset(opform->oprcode);
859         result->args = args;
860         result->location = location;
861
862         ReleaseSysCache(tup);
863
864         return (Expr *) result;
865 }
866
867 /*
868  * make_scalar_array_op()
869  *              Build expression tree for "scalar op ANY/ALL (array)" construct.
870  */
871 Expr *
872 make_scalar_array_op(ParseState *pstate, List *opname,
873                                          bool useOr,
874                                          Node *ltree, Node *rtree,
875                                          int location)
876 {
877         Oid                     ltypeId,
878                                 rtypeId,
879                                 atypeId,
880                                 res_atypeId;
881         Operator        tup;
882         Form_pg_operator opform;
883         Oid                     actual_arg_types[2];
884         Oid                     declared_arg_types[2];
885         List       *args;
886         Oid                     rettype;
887         ScalarArrayOpExpr *result;
888
889         ltypeId = exprType(ltree);
890         atypeId = exprType(rtree);
891
892         /*
893          * The right-hand input of the operator will be the element type of the
894          * array.  However, if we currently have just an untyped literal on the
895          * right, stay with that and hope we can resolve the operator.
896          */
897         if (atypeId == UNKNOWNOID)
898                 rtypeId = UNKNOWNOID;
899         else
900         {
901                 rtypeId = get_element_type(atypeId);
902                 if (!OidIsValid(rtypeId))
903                         ereport(ERROR,
904                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
905                                    errmsg("op ANY/ALL (array) requires array on right side"),
906                                          parser_errposition(pstate, location)));
907         }
908
909         /* Now resolve the operator */
910         tup = oper(pstate, opname, ltypeId, rtypeId, false, location);
911         opform = (Form_pg_operator) GETSTRUCT(tup);
912
913         /* Check it's not a shell */
914         if (!RegProcedureIsValid(opform->oprcode))
915                 ereport(ERROR,
916                                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
917                                  errmsg("operator is only a shell: %s",
918                                                 op_signature_string(opname,
919                                                                                         opform->oprkind,
920                                                                                         opform->oprleft,
921                                                                                         opform->oprright)),
922                                  parser_errposition(pstate, location)));
923
924         args = list_make2(ltree, rtree);
925         actual_arg_types[0] = ltypeId;
926         actual_arg_types[1] = rtypeId;
927         declared_arg_types[0] = opform->oprleft;
928         declared_arg_types[1] = opform->oprright;
929
930         /*
931          * enforce consistency with polymorphic argument and return types,
932          * possibly adjusting return type or declared_arg_types (which will be
933          * used as the cast destination by make_fn_arguments)
934          */
935         rettype = enforce_generic_type_consistency(actual_arg_types,
936                                                                                            declared_arg_types,
937                                                                                            2,
938                                                                                            opform->oprresult,
939                                                                                            false);
940
941         /*
942          * Check that operator result is boolean
943          */
944         if (rettype != BOOLOID)
945                 ereport(ERROR,
946                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
947                          errmsg("op ANY/ALL (array) requires operator to yield boolean"),
948                                  parser_errposition(pstate, location)));
949         if (get_func_retset(opform->oprcode))
950                 ereport(ERROR,
951                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
952                   errmsg("op ANY/ALL (array) requires operator not to return a set"),
953                                  parser_errposition(pstate, location)));
954
955         /*
956          * Now switch back to the array type on the right, arranging for any
957          * needed cast to be applied.  Beware of polymorphic operators here;
958          * enforce_generic_type_consistency may or may not have replaced a
959          * polymorphic type with a real one.
960          */
961         if (IsPolymorphicType(declared_arg_types[1]))
962         {
963                 /* assume the actual array type is OK */
964                 res_atypeId = atypeId;
965         }
966         else
967         {
968                 res_atypeId = get_array_type(declared_arg_types[1]);
969                 if (!OidIsValid(res_atypeId))
970                         ereport(ERROR,
971                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
972                                          errmsg("could not find array type for data type %s",
973                                                         format_type_be(declared_arg_types[1])),
974                                          parser_errposition(pstate, location)));
975         }
976         actual_arg_types[1] = atypeId;
977         declared_arg_types[1] = res_atypeId;
978
979         /* perform the necessary typecasting of arguments */
980         make_fn_arguments(pstate, args, actual_arg_types, declared_arg_types);
981
982         /* and build the expression node */
983         result = makeNode(ScalarArrayOpExpr);
984         result->opno = oprid(tup);
985         result->opfuncid = opform->oprcode;
986         result->useOr = useOr;
987         result->args = args;
988         result->location = location;
989
990         ReleaseSysCache(tup);
991
992         return (Expr *) result;
993 }
994
995
996 /*
997  * Lookaside cache to speed operator lookup.  Possibly this should be in
998  * a separate module under utils/cache/ ?
999  *
1000  * The idea here is that the mapping from operator name and given argument
1001  * types is constant for a given search path (or single specified schema OID)
1002  * so long as the contents of pg_operator and pg_cast don't change.  And that
1003  * mapping is pretty expensive to compute, especially for ambiguous operators;
1004  * this is mainly because there are a *lot* of instances of popular operator
1005  * names such as "=", and we have to check each one to see which is the
1006  * best match.  So once we have identified the correct mapping, we save it
1007  * in a cache that need only be flushed on pg_operator or pg_cast change.
1008  * (pg_cast must be considered because changes in the set of implicit casts
1009  * affect the set of applicable operators for any given input datatype.)
1010  *
1011  * XXX in principle, ALTER TABLE ... INHERIT could affect the mapping as
1012  * well, but we disregard that since there's no convenient way to find out
1013  * about it, and it seems a pretty far-fetched corner-case anyway.
1014  *
1015  * Note: at some point it might be worth doing a similar cache for function
1016  * lookups.  However, the potential gain is a lot less since (a) function
1017  * names are generally not overloaded as heavily as operator names, and
1018  * (b) we'd have to flush on pg_proc updates, which are probably a good
1019  * deal more common than pg_operator updates.
1020  */
1021
1022 /* The operator cache hashtable */
1023 static HTAB *OprCacheHash = NULL;
1024
1025
1026 /*
1027  * make_oper_cache_key
1028  *              Fill the lookup key struct given operator name and arg types.
1029  *
1030  * Returns TRUE if successful, FALSE if the search_path overflowed
1031  * (hence no caching is possible).
1032  */
1033 static bool
1034 make_oper_cache_key(OprCacheKey *key, List *opname, Oid ltypeId, Oid rtypeId)
1035 {
1036         char       *schemaname;
1037         char       *opername;
1038
1039         /* deconstruct the name list */
1040         DeconstructQualifiedName(opname, &schemaname, &opername);
1041
1042         /* ensure zero-fill for stable hashing */
1043         MemSet(key, 0, sizeof(OprCacheKey));
1044
1045         /* save operator name and input types into key */
1046         strlcpy(key->oprname, opername, NAMEDATALEN);
1047         key->left_arg = ltypeId;
1048         key->right_arg = rtypeId;
1049
1050         if (schemaname)
1051         {
1052                 /* search only in exact schema given */
1053                 key->search_path[0] = LookupExplicitNamespace(schemaname);
1054         }
1055         else
1056         {
1057                 /* get the active search path */
1058                 if (fetch_search_path_array(key->search_path,
1059                                                                         MAX_CACHED_PATH_LEN) > MAX_CACHED_PATH_LEN)
1060                         return false;           /* oops, didn't fit */
1061         }
1062
1063         return true;
1064 }
1065
1066 /*
1067  * find_oper_cache_entry
1068  *
1069  * Look for a cache entry matching the given key.  If found, return the
1070  * contained operator OID, else return InvalidOid.
1071  */
1072 static Oid
1073 find_oper_cache_entry(OprCacheKey *key)
1074 {
1075         OprCacheEntry *oprentry;
1076
1077         if (OprCacheHash == NULL)
1078         {
1079                 /* First time through: initialize the hash table */
1080                 HASHCTL         ctl;
1081
1082                 if (!CacheMemoryContext)
1083                         CreateCacheMemoryContext();
1084
1085                 MemSet(&ctl, 0, sizeof(ctl));
1086                 ctl.keysize = sizeof(OprCacheKey);
1087                 ctl.entrysize = sizeof(OprCacheEntry);
1088                 ctl.hash = tag_hash;
1089                 OprCacheHash = hash_create("Operator lookup cache", 256,
1090                                                                         &ctl, HASH_ELEM | HASH_FUNCTION);
1091
1092                 /* Arrange to flush cache on pg_operator and pg_cast changes */
1093                 CacheRegisterSyscacheCallback(OPERNAMENSP,
1094                                                                           InvalidateOprCacheCallBack,
1095                                                                           (Datum) 0);
1096                 CacheRegisterSyscacheCallback(CASTSOURCETARGET,
1097                                                                           InvalidateOprCacheCallBack,
1098                                                                           (Datum) 0);
1099         }
1100
1101         /* Look for an existing entry */
1102         oprentry = (OprCacheEntry *) hash_search(OprCacheHash,
1103                                                                                          (void *) key,
1104                                                                                          HASH_FIND, NULL);
1105         if (oprentry == NULL)
1106                 return InvalidOid;
1107
1108         return oprentry->opr_oid;
1109 }
1110
1111 /*
1112  * make_oper_cache_entry
1113  *
1114  * Insert a cache entry for the given key.
1115  */
1116 static void
1117 make_oper_cache_entry(OprCacheKey *key, Oid opr_oid)
1118 {
1119         OprCacheEntry *oprentry;
1120
1121         Assert(OprCacheHash != NULL);
1122
1123         oprentry = (OprCacheEntry *) hash_search(OprCacheHash,
1124                                                                                          (void *) key,
1125                                                                                          HASH_ENTER, NULL);
1126         oprentry->opr_oid = opr_oid;
1127 }
1128
1129 /*
1130  * Callback for pg_operator and pg_cast inval events
1131  */
1132 static void
1133 InvalidateOprCacheCallBack(Datum arg, int cacheid, ItemPointer tuplePtr)
1134 {
1135         HASH_SEQ_STATUS status;
1136         OprCacheEntry *hentry;
1137
1138         Assert(OprCacheHash != NULL);
1139
1140         /* Currently we just flush all entries; hard to be smarter ... */
1141         hash_seq_init(&status, OprCacheHash);
1142
1143         while ((hentry = (OprCacheEntry *) hash_seq_search(&status)) != NULL)
1144         {
1145                 if (hash_search(OprCacheHash,
1146                                                 (void *) &hentry->key,
1147                                                 HASH_REMOVE, NULL) == NULL)
1148                         elog(ERROR, "hash table corrupted");
1149         }
1150 }