1 /*-------------------------------------------------------------------------
4 * handle operator things for parser
6 * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/parser/parse_oper.c
13 *-------------------------------------------------------------------------
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"
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.
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.
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.
47 /* If your search_path is longer than this, sucks to be you ... */
48 #define MAX_CACHED_PATH_LEN 16
50 typedef struct OprCacheKey
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];
58 typedef struct OprCacheEntry
60 /* the hash lookup key MUST BE FIRST */
63 Oid opr_oid; /* OID of the resolved operator */
67 static Oid binary_oper_exact(List *opname, Oid arg1, Oid arg2);
68 static FuncDetailCode oper_select_candidate(int nargs,
70 FuncCandidateList candidates,
72 static const char *op_signature_string(List *op, char oprkind,
74 static void op_error(ParseState *pstate, List *op, char oprkind,
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);
86 * Given a possibly-qualified operator name and exact input datatypes,
87 * look up the operator.
89 * Pass oprleft = InvalidOid for a prefix op, oprright = InvalidOid for
92 * If the operator name is not schema-qualified, it is sought in the current
93 * namespace search path.
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.
100 LookupOperName(ParseState *pstate, List *opername, Oid oprleft, Oid oprright,
101 bool noError, int location)
105 result = OpernameGetOprid(opername, oprleft, oprright);
106 if (OidIsValid(result))
109 /* we don't use op_error here because only an exact match is wanted */
114 if (!OidIsValid(oprleft))
116 else if (!OidIsValid(oprright))
122 (errcode(ERRCODE_UNDEFINED_FUNCTION),
123 errmsg("operator does not exist: %s",
124 op_signature_string(opername, oprkind,
126 parser_errposition(pstate, location)));
133 * LookupOperNameTypeNames
134 * Like LookupOperName, but the argument types are specified by
137 * Pass oprleft = NULL for a prefix op, oprright = NULL for a postfix op.
140 LookupOperNameTypeNames(ParseState *pstate, List *opername,
141 TypeName *oprleft, TypeName *oprright,
142 bool noError, int location)
148 leftoid = InvalidOid;
150 leftoid = typenameTypeId(pstate, oprleft);
152 if (oprright == NULL)
153 rightoid = InvalidOid;
155 rightoid = typenameTypeId(pstate, oprright);
157 return LookupOperName(pstate, opername, leftoid, rightoid,
162 * get_sort_group_operators - get default sorting/grouping operators for type
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.)
170 * If an operator is missing and the corresponding needXX flag is true,
171 * throw a standard error message, else return InvalidOid.
173 * In addition to the operator OIDs themselves, this function can identify
174 * whether the "=" operator is hashable.
176 * Callers can pass NULL pointers for any results they don't care to get.
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
183 get_sort_group_operators(Oid argtype,
184 bool needLT, bool needEQ, bool needGT,
185 Oid *ltOpr, Oid *eqOpr, Oid *gtOpr,
188 TypeCacheEntry *typentry;
196 * Look up the operators using the type cache.
198 * Note: the search algorithm used by typcache.c ensures that the results
199 * are consistent, ie all from matching opclasses.
201 if (isHashable != NULL)
202 cache_flags = TYPECACHE_LT_OPR | TYPECACHE_EQ_OPR | TYPECACHE_GT_OPR |
205 cache_flags = TYPECACHE_LT_OPR | TYPECACHE_EQ_OPR | TYPECACHE_GT_OPR;
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);
213 /* Report errors if needed */
214 if ((needLT && !OidIsValid(lt_opr)) ||
215 (needGT && !OidIsValid(gt_opr)))
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))
223 (errcode(ERRCODE_UNDEFINED_FUNCTION),
224 errmsg("could not identify an equality operator for type %s",
225 format_type_be(argtype))));
227 /* Return results as needed */
235 *isHashable = hashable;
239 /* given operator tuple, return the operator OID */
243 return HeapTupleGetOid(op);
246 /* given operator tuple, return the underlying function's OID */
248 oprfuncid(Operator op)
250 Form_pg_operator pgopform = (Form_pg_operator) GETSTRUCT(op);
252 return pgopform->oprcode;
256 /* binary_oper_exact()
257 * Check for an "exact" match to the specified operand types.
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.
265 binary_oper_exact(List *opname, Oid arg1, Oid arg2)
268 bool was_unknown = false;
270 /* Unspecified type for one of the arguments? then use the other */
271 if ((arg1 == UNKNOWNOID) && (arg2 != InvalidOid))
276 else if ((arg2 == UNKNOWNOID) && (arg1 != InvalidOid))
282 result = OpernameGetOprid(opname, arg1, arg2);
283 if (OidIsValid(result))
288 /* arg1 and arg2 are the same here, need only look at arg1 */
289 Oid basetype = getBaseType(arg1);
291 if (basetype != arg1)
293 result = OpernameGetOprid(opname, basetype, basetype);
294 if (OidIsValid(result))
303 /* oper_select_candidate()
304 * Given the input argtype array and one or more candidates
305 * for the operator, attempt to resolve the conflict.
307 * Returns FUNCDETAIL_NOTFOUND, FUNCDETAIL_MULTIPLE, or FUNCDETAIL_NORMAL.
308 * In the success case the Oid of the best candidate is stored in *operOid.
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.
314 static FuncDetailCode
315 oper_select_candidate(int nargs,
317 FuncCandidateList candidates,
318 Oid *operOid) /* output argument */
323 * Delete any candidates that cannot actually accept the given input
324 * types, whether directly or by coercion.
326 ncandidates = func_match_argtypes(nargs, input_typeids,
327 candidates, &candidates);
329 /* Done if no candidate or only one candidate survives */
330 if (ncandidates == 0)
332 *operOid = InvalidOid;
333 return FUNCDETAIL_NOTFOUND;
335 if (ncandidates == 1)
337 *operOid = candidates->oid;
338 return FUNCDETAIL_NORMAL;
342 * Use the same heuristics as for ambiguous functions to resolve the
345 candidates = func_select_candidate(nargs, input_typeids, candidates);
349 *operOid = candidates->oid;
350 return FUNCDETAIL_NORMAL;
353 *operOid = InvalidOid;
354 return FUNCDETAIL_MULTIPLE; /* failed to select a best candidate */
358 /* oper() -- search for a binary operator
359 * Given operator name, types of arg1 and arg2, return oper struct.
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.
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.
369 * NOTE: on success, the returned object is a syscache entry. The caller
370 * must ReleaseSysCache() the entry when done with it.
373 oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId,
374 bool noError, int location)
379 FuncDetailCode fdresult = FUNCDETAIL_NOTFOUND;
380 HeapTuple tup = NULL;
383 * Try to find the mapping in the lookaside cache.
385 key_ok = make_oper_cache_key(&key, opname, ltypeId, rtypeId);
388 operOid = find_oper_cache_entry(&key);
389 if (OidIsValid(operOid))
391 tup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operOid));
392 if (HeapTupleIsValid(tup))
393 return (Operator) tup;
398 * First try for an "exact" match.
400 operOid = binary_oper_exact(opname, ltypeId, rtypeId);
401 if (!OidIsValid(operOid))
404 * Otherwise, search for the most suitable candidate.
406 FuncCandidateList clist;
408 /* Get binary operators of given name */
409 clist = OpernameGetCandidates(opname, 'b');
411 /* No operators found? Then fail... */
415 * Unspecified type for one of the arguments? then use the other
416 * (XXX this is probably dead code?)
420 if (rtypeId == InvalidOid)
422 else if (ltypeId == InvalidOid)
424 inputOids[0] = ltypeId;
425 inputOids[1] = rtypeId;
426 fdresult = oper_select_candidate(2, inputOids, clist, &operOid);
430 if (OidIsValid(operOid))
431 tup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operOid));
433 if (HeapTupleIsValid(tup))
436 make_oper_cache_entry(&key, operOid);
439 op_error(pstate, opname, 'b', ltypeId, rtypeId, fdresult, location);
441 return (Operator) tup;
445 * given an opname and input datatypes, find a compatible binary operator
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.
452 compatible_oper(ParseState *pstate, List *op, Oid arg1, Oid arg2,
453 bool noError, int location)
456 Form_pg_operator opform;
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 */
463 /* but is it good enough? */
464 opform = (Form_pg_operator) GETSTRUCT(optup);
465 if (IsBinaryCoercible(arg1, opform->oprleft) &&
466 IsBinaryCoercible(arg2, opform->oprright))
470 ReleaseSysCache(optup);
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)));
479 return (Operator) NULL;
482 /* compatible_oper_opid() -- get OID of a binary operator
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.
489 compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
494 optup = compatible_oper(NULL, op, arg1, arg2, noError, -1);
497 result = oprid(optup);
498 ReleaseSysCache(optup);
505 /* right_oper() -- search for a unary right operator (postfix operator)
506 * Given operator name and type of arg, return oper struct.
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.
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.
516 * NOTE: on success, the returned object is a syscache entry. The caller
517 * must ReleaseSysCache() the entry when done with it.
520 right_oper(ParseState *pstate, List *op, Oid arg, bool noError, int location)
525 FuncDetailCode fdresult = FUNCDETAIL_NOTFOUND;
526 HeapTuple tup = NULL;
529 * Try to find the mapping in the lookaside cache.
531 key_ok = make_oper_cache_key(&key, op, arg, InvalidOid);
534 operOid = find_oper_cache_entry(&key);
535 if (OidIsValid(operOid))
537 tup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operOid));
538 if (HeapTupleIsValid(tup))
539 return (Operator) tup;
544 * First try for an "exact" match.
546 operOid = OpernameGetOprid(op, arg, InvalidOid);
547 if (!OidIsValid(operOid))
550 * Otherwise, search for the most suitable candidate.
552 FuncCandidateList clist;
554 /* Get postfix operators of given name */
555 clist = OpernameGetCandidates(op, 'r');
557 /* No operators found? Then fail... */
561 * We must run oper_select_candidate even if only one candidate,
562 * otherwise we may falsely return a non-type-compatible operator.
564 fdresult = oper_select_candidate(1, &arg, clist, &operOid);
568 if (OidIsValid(operOid))
569 tup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operOid));
571 if (HeapTupleIsValid(tup))
574 make_oper_cache_entry(&key, operOid);
577 op_error(pstate, op, 'r', arg, InvalidOid, fdresult, location);
579 return (Operator) tup;
583 /* left_oper() -- search for a unary left operator (prefix operator)
584 * Given operator name and type of arg, return oper struct.
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.
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.
594 * NOTE: on success, the returned object is a syscache entry. The caller
595 * must ReleaseSysCache() the entry when done with it.
598 left_oper(ParseState *pstate, List *op, Oid arg, bool noError, int location)
603 FuncDetailCode fdresult = FUNCDETAIL_NOTFOUND;
604 HeapTuple tup = NULL;
607 * Try to find the mapping in the lookaside cache.
609 key_ok = make_oper_cache_key(&key, op, InvalidOid, arg);
612 operOid = find_oper_cache_entry(&key);
613 if (OidIsValid(operOid))
615 tup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operOid));
616 if (HeapTupleIsValid(tup))
617 return (Operator) tup;
622 * First try for an "exact" match.
624 operOid = OpernameGetOprid(op, InvalidOid, arg);
625 if (!OidIsValid(operOid))
628 * Otherwise, search for the most suitable candidate.
630 FuncCandidateList clist;
632 /* Get prefix operators of given name */
633 clist = OpernameGetCandidates(op, 'l');
635 /* No operators found? Then fail... */
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!
643 FuncCandidateList clisti;
645 for (clisti = clist; clisti != NULL; clisti = clisti->next)
647 clisti->args[0] = clisti->args[1];
651 * We must run oper_select_candidate even if only one candidate,
652 * otherwise we may falsely return a non-type-compatible operator.
654 fdresult = oper_select_candidate(1, &arg, clist, &operOid);
658 if (OidIsValid(operOid))
659 tup = SearchSysCache1(OPEROID, ObjectIdGetDatum(operOid));
661 if (HeapTupleIsValid(tup))
664 make_oper_cache_entry(&key, operOid);
667 op_error(pstate, op, 'l', InvalidOid, arg, fdresult, location);
669 return (Operator) tup;
673 * op_signature_string
674 * Build a string representing an operator name, including arg type(s).
675 * The result is something like "integer + integer".
677 * This is typically used in the construction of operator-not-found error
681 op_signature_string(List *op, char oprkind, Oid arg1, Oid arg2)
683 StringInfoData argbuf;
685 initStringInfo(&argbuf);
688 appendStringInfo(&argbuf, "%s ", format_type_be(arg1));
690 appendStringInfoString(&argbuf, NameListToString(op));
693 appendStringInfo(&argbuf, " %s", format_type_be(arg2));
695 return argbuf.data; /* return palloc'd string buffer */
699 * op_error - utility routine to complain about an unresolvable operator
702 op_error(ParseState *pstate, List *op, char oprkind,
704 FuncDetailCode fdresult, int location)
706 if (fdresult == FUNCDETAIL_MULTIPLE)
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)));
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)));
726 * Operator expression construction.
728 * Transform operator expression ensuring type compatibility.
729 * This is where some type conversion happens.
731 * As with coerce_type, pstate may be NULL if no special unknown-Param
732 * processing is wanted.
735 make_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree,
741 Form_pg_operator opform;
742 Oid actual_arg_types[2];
743 Oid declared_arg_types[2];
749 /* Select the operator */
753 ltypeId = exprType(ltree);
754 rtypeId = InvalidOid;
755 tup = right_oper(pstate, opname, ltypeId, false, location);
757 else if (ltree == NULL)
760 rtypeId = exprType(rtree);
761 ltypeId = InvalidOid;
762 tup = left_oper(pstate, opname, rtypeId, false, location);
766 /* otherwise, binary operator */
767 ltypeId = exprType(ltree);
768 rtypeId = exprType(rtree);
769 tup = oper(pstate, opname, ltypeId, rtypeId, false, location);
772 opform = (Form_pg_operator) GETSTRUCT(tup);
774 /* Check it's not a shell */
775 if (!RegProcedureIsValid(opform->oprcode))
777 (errcode(ERRCODE_UNDEFINED_FUNCTION),
778 errmsg("operator is only a shell: %s",
779 op_signature_string(opname,
783 parser_errposition(pstate, location)));
785 /* Do typecasting and build the expression tree */
789 args = list_make1(ltree);
790 actual_arg_types[0] = ltypeId;
791 declared_arg_types[0] = opform->oprleft;
794 else if (ltree == NULL)
797 args = list_make1(rtree);
798 actual_arg_types[0] = rtypeId;
799 declared_arg_types[0] = opform->oprright;
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;
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)
818 rettype = enforce_generic_type_consistency(actual_arg_types,
824 /* perform the necessary typecasting of arguments */
825 make_fn_arguments(pstate, args, actual_arg_types, declared_arg_types);
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 */
835 result->location = location;
837 ReleaseSysCache(tup);
839 return (Expr *) result;
843 * make_scalar_array_op()
844 * Build expression tree for "scalar op ANY/ALL (array)" construct.
847 make_scalar_array_op(ParseState *pstate, List *opname,
849 Node *ltree, Node *rtree,
857 Form_pg_operator opform;
858 Oid actual_arg_types[2];
859 Oid declared_arg_types[2];
862 ScalarArrayOpExpr *result;
864 ltypeId = exprType(ltree);
865 atypeId = exprType(rtree);
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.
872 if (atypeId == UNKNOWNOID)
873 rtypeId = UNKNOWNOID;
876 rtypeId = get_base_element_type(atypeId);
877 if (!OidIsValid(rtypeId))
879 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
880 errmsg("op ANY/ALL (array) requires array on right side"),
881 parser_errposition(pstate, location)));
884 /* Now resolve the operator */
885 tup = oper(pstate, opname, ltypeId, rtypeId, false, location);
886 opform = (Form_pg_operator) GETSTRUCT(tup);
888 /* Check it's not a shell */
889 if (!RegProcedureIsValid(opform->oprcode))
891 (errcode(ERRCODE_UNDEFINED_FUNCTION),
892 errmsg("operator is only a shell: %s",
893 op_signature_string(opname,
897 parser_errposition(pstate, location)));
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;
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)
910 rettype = enforce_generic_type_consistency(actual_arg_types,
917 * Check that operator result is boolean
919 if (rettype != BOOLOID)
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))
926 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
927 errmsg("op ANY/ALL (array) requires operator not to return a set"),
928 parser_errposition(pstate, location)));
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.
936 if (IsPolymorphicType(declared_arg_types[1]))
938 /* assume the actual array type is OK */
939 res_atypeId = atypeId;
943 res_atypeId = get_array_type(declared_arg_types[1]);
944 if (!OidIsValid(res_atypeId))
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)));
951 actual_arg_types[1] = atypeId;
952 declared_arg_types[1] = res_atypeId;
954 /* perform the necessary typecasting of arguments */
955 make_fn_arguments(pstate, args, actual_arg_types, declared_arg_types);
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 */
964 result->location = location;
966 ReleaseSysCache(tup);
968 return (Expr *) result;
973 * Lookaside cache to speed operator lookup. Possibly this should be in
974 * a separate module under utils/cache/ ?
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.)
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.
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.
998 /* The operator cache hashtable */
999 static HTAB *OprCacheHash = NULL;
1003 * make_oper_cache_key
1004 * Fill the lookup key struct given operator name and arg types.
1006 * Returns TRUE if successful, FALSE if the search_path overflowed
1007 * (hence no caching is possible).
1010 make_oper_cache_key(OprCacheKey *key, List *opname, Oid ltypeId, Oid rtypeId)
1015 /* deconstruct the name list */
1016 DeconstructQualifiedName(opname, &schemaname, &opername);
1018 /* ensure zero-fill for stable hashing */
1019 MemSet(key, 0, sizeof(OprCacheKey));
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;
1028 /* search only in exact schema given */
1029 key->search_path[0] = LookupExplicitNamespace(schemaname);
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 */
1043 * find_oper_cache_entry
1045 * Look for a cache entry matching the given key. If found, return the
1046 * contained operator OID, else return InvalidOid.
1049 find_oper_cache_entry(OprCacheKey *key)
1051 OprCacheEntry *oprentry;
1053 if (OprCacheHash == NULL)
1055 /* First time through: initialize the hash table */
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);
1065 /* Arrange to flush cache on pg_operator and pg_cast changes */
1066 CacheRegisterSyscacheCallback(OPERNAMENSP,
1067 InvalidateOprCacheCallBack,
1069 CacheRegisterSyscacheCallback(CASTSOURCETARGET,
1070 InvalidateOprCacheCallBack,
1074 /* Look for an existing entry */
1075 oprentry = (OprCacheEntry *) hash_search(OprCacheHash,
1078 if (oprentry == NULL)
1081 return oprentry->opr_oid;
1085 * make_oper_cache_entry
1087 * Insert a cache entry for the given key.
1090 make_oper_cache_entry(OprCacheKey *key, Oid opr_oid)
1092 OprCacheEntry *oprentry;
1094 Assert(OprCacheHash != NULL);
1096 oprentry = (OprCacheEntry *) hash_search(OprCacheHash,
1099 oprentry->opr_oid = opr_oid;
1103 * Callback for pg_operator and pg_cast inval events
1106 InvalidateOprCacheCallBack(Datum arg, int cacheid, uint32 hashvalue)
1108 HASH_SEQ_STATUS status;
1109 OprCacheEntry *hentry;
1111 Assert(OprCacheHash != NULL);
1113 /* Currently we just flush all entries; hard to be smarter ... */
1114 hash_seq_init(&status, OprCacheHash);
1116 while ((hentry = (OprCacheEntry *) hash_seq_search(&status)) != NULL)
1118 if (hash_search(OprCacheHash,
1119 (void *) &hentry->key,
1120 HASH_REMOVE, NULL) == NULL)
1121 elog(ERROR, "hash table corrupted");