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