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