PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
parse_oper.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * parse_oper.c
4  * handle operator things for parser
5  *
6  * Portions Copyright (c) 1996-2017, 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 {
54  Oid left_arg; /* Left input OID, or 0 if prefix op */
55  Oid right_arg; /* Right input OID, or 0 if postfix op */
57 } OprCacheKey;
58 
59 typedef struct OprCacheEntry
60 {
61  /* the hash lookup key MUST BE FIRST */
63 
64  Oid opr_oid; /* OID of the resolved operator */
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);
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
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
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
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)
206  else
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
244 {
245  return HeapTupleGetOid(op);
246 }
247 
248 /* given operator tuple, return the underlying function's OID */
249 Oid
251 {
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
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
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
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;
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
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
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
523 right_oper(ParseState *pstate, List *op, Oid arg, bool noError, int location)
524 {
525  Oid operOid;
526  OprCacheKey key;
527  bool key_ok;
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
602 left_oper(ParseState *pstate, List *op, Oid arg, bool noError, int location)
603 {
604  Oid operOid;
605  OprCacheKey key;
606  bool key_ok;
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 *
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 
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
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 *
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  /* if it returns a set, check that's OK */
843  if (result->opretset)
844  check_srf_call_placement(pstate, location);
845 
846  ReleaseSysCache(tup);
847 
848  return (Expr *) result;
849 }
850 
851 /*
852  * make_scalar_array_op()
853  * Build expression tree for "scalar op ANY/ALL (array)" construct.
854  */
855 Expr *
857  bool useOr,
858  Node *ltree, Node *rtree,
859  int location)
860 {
861  Oid ltypeId,
862  rtypeId,
863  atypeId,
864  res_atypeId;
865  Operator tup;
866  Form_pg_operator opform;
867  Oid actual_arg_types[2];
868  Oid declared_arg_types[2];
869  List *args;
870  Oid rettype;
871  ScalarArrayOpExpr *result;
872 
873  ltypeId = exprType(ltree);
874  atypeId = exprType(rtree);
875 
876  /*
877  * The right-hand input of the operator will be the element type of the
878  * array. However, if we currently have just an untyped literal on the
879  * right, stay with that and hope we can resolve the operator.
880  */
881  if (atypeId == UNKNOWNOID)
882  rtypeId = UNKNOWNOID;
883  else
884  {
885  rtypeId = get_base_element_type(atypeId);
886  if (!OidIsValid(rtypeId))
887  ereport(ERROR,
888  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
889  errmsg("op ANY/ALL (array) requires array on right side"),
890  parser_errposition(pstate, location)));
891  }
892 
893  /* Now resolve the operator */
894  tup = oper(pstate, opname, ltypeId, rtypeId, false, location);
895  opform = (Form_pg_operator) GETSTRUCT(tup);
896 
897  /* Check it's not a shell */
898  if (!RegProcedureIsValid(opform->oprcode))
899  ereport(ERROR,
900  (errcode(ERRCODE_UNDEFINED_FUNCTION),
901  errmsg("operator is only a shell: %s",
902  op_signature_string(opname,
903  opform->oprkind,
904  opform->oprleft,
905  opform->oprright)),
906  parser_errposition(pstate, location)));
907 
908  args = list_make2(ltree, rtree);
909  actual_arg_types[0] = ltypeId;
910  actual_arg_types[1] = rtypeId;
911  declared_arg_types[0] = opform->oprleft;
912  declared_arg_types[1] = opform->oprright;
913 
914  /*
915  * enforce consistency with polymorphic argument and return types,
916  * possibly adjusting return type or declared_arg_types (which will be
917  * used as the cast destination by make_fn_arguments)
918  */
919  rettype = enforce_generic_type_consistency(actual_arg_types,
920  declared_arg_types,
921  2,
922  opform->oprresult,
923  false);
924 
925  /*
926  * Check that operator result is boolean
927  */
928  if (rettype != BOOLOID)
929  ereport(ERROR,
930  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
931  errmsg("op ANY/ALL (array) requires operator to yield boolean"),
932  parser_errposition(pstate, location)));
933  if (get_func_retset(opform->oprcode))
934  ereport(ERROR,
935  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
936  errmsg("op ANY/ALL (array) requires operator not to return a set"),
937  parser_errposition(pstate, location)));
938 
939  /*
940  * Now switch back to the array type on the right, arranging for any
941  * needed cast to be applied. Beware of polymorphic operators here;
942  * enforce_generic_type_consistency may or may not have replaced a
943  * polymorphic type with a real one.
944  */
945  if (IsPolymorphicType(declared_arg_types[1]))
946  {
947  /* assume the actual array type is OK */
948  res_atypeId = atypeId;
949  }
950  else
951  {
952  res_atypeId = get_array_type(declared_arg_types[1]);
953  if (!OidIsValid(res_atypeId))
954  ereport(ERROR,
955  (errcode(ERRCODE_UNDEFINED_OBJECT),
956  errmsg("could not find array type for data type %s",
957  format_type_be(declared_arg_types[1])),
958  parser_errposition(pstate, location)));
959  }
960  actual_arg_types[1] = atypeId;
961  declared_arg_types[1] = res_atypeId;
962 
963  /* perform the necessary typecasting of arguments */
964  make_fn_arguments(pstate, args, actual_arg_types, declared_arg_types);
965 
966  /* and build the expression node */
967  result = makeNode(ScalarArrayOpExpr);
968  result->opno = oprid(tup);
969  result->opfuncid = opform->oprcode;
970  result->useOr = useOr;
971  /* inputcollid will be set by parse_collate.c */
972  result->args = args;
973  result->location = location;
974 
975  ReleaseSysCache(tup);
976 
977  return (Expr *) result;
978 }
979 
980 
981 /*
982  * Lookaside cache to speed operator lookup. Possibly this should be in
983  * a separate module under utils/cache/ ?
984  *
985  * The idea here is that the mapping from operator name and given argument
986  * types is constant for a given search path (or single specified schema OID)
987  * so long as the contents of pg_operator and pg_cast don't change. And that
988  * mapping is pretty expensive to compute, especially for ambiguous operators;
989  * this is mainly because there are a *lot* of instances of popular operator
990  * names such as "=", and we have to check each one to see which is the
991  * best match. So once we have identified the correct mapping, we save it
992  * in a cache that need only be flushed on pg_operator or pg_cast change.
993  * (pg_cast must be considered because changes in the set of implicit casts
994  * affect the set of applicable operators for any given input datatype.)
995  *
996  * XXX in principle, ALTER TABLE ... INHERIT could affect the mapping as
997  * well, but we disregard that since there's no convenient way to find out
998  * about it, and it seems a pretty far-fetched corner-case anyway.
999  *
1000  * Note: at some point it might be worth doing a similar cache for function
1001  * lookups. However, the potential gain is a lot less since (a) function
1002  * names are generally not overloaded as heavily as operator names, and
1003  * (b) we'd have to flush on pg_proc updates, which are probably a good
1004  * deal more common than pg_operator updates.
1005  */
1006 
1007 /* The operator cache hashtable */
1009 
1010 
1011 /*
1012  * make_oper_cache_key
1013  * Fill the lookup key struct given operator name and arg types.
1014  *
1015  * Returns TRUE if successful, FALSE if the search_path overflowed
1016  * (hence no caching is possible).
1017  *
1018  * pstate/location are used only to report the error position; pass NULL/-1
1019  * if not available.
1020  */
1021 static bool
1023  Oid ltypeId, Oid rtypeId, int location)
1024 {
1025  char *schemaname;
1026  char *opername;
1027 
1028  /* deconstruct the name list */
1029  DeconstructQualifiedName(opname, &schemaname, &opername);
1030 
1031  /* ensure zero-fill for stable hashing */
1032  MemSet(key, 0, sizeof(OprCacheKey));
1033 
1034  /* save operator name and input types into key */
1035  strlcpy(key->oprname, opername, NAMEDATALEN);
1036  key->left_arg = ltypeId;
1037  key->right_arg = rtypeId;
1038 
1039  if (schemaname)
1040  {
1041  ParseCallbackState pcbstate;
1042 
1043  /* search only in exact schema given */
1044  setup_parser_errposition_callback(&pcbstate, pstate, location);
1045  key->search_path[0] = LookupExplicitNamespace(schemaname, false);
1047  }
1048  else
1049  {
1050  /* get the active search path */
1053  return false; /* oops, didn't fit */
1054  }
1055 
1056  return true;
1057 }
1058 
1059 /*
1060  * find_oper_cache_entry
1061  *
1062  * Look for a cache entry matching the given key. If found, return the
1063  * contained operator OID, else return InvalidOid.
1064  */
1065 static Oid
1067 {
1068  OprCacheEntry *oprentry;
1069 
1070  if (OprCacheHash == NULL)
1071  {
1072  /* First time through: initialize the hash table */
1073  HASHCTL ctl;
1074 
1075  MemSet(&ctl, 0, sizeof(ctl));
1076  ctl.keysize = sizeof(OprCacheKey);
1077  ctl.entrysize = sizeof(OprCacheEntry);
1078  OprCacheHash = hash_create("Operator lookup cache", 256,
1079  &ctl, HASH_ELEM | HASH_BLOBS);
1080 
1081  /* Arrange to flush cache on pg_operator and pg_cast changes */
1084  (Datum) 0);
1087  (Datum) 0);
1088  }
1089 
1090  /* Look for an existing entry */
1091  oprentry = (OprCacheEntry *) hash_search(OprCacheHash,
1092  (void *) key,
1093  HASH_FIND, NULL);
1094  if (oprentry == NULL)
1095  return InvalidOid;
1096 
1097  return oprentry->opr_oid;
1098 }
1099 
1100 /*
1101  * make_oper_cache_entry
1102  *
1103  * Insert a cache entry for the given key.
1104  */
1105 static void
1107 {
1108  OprCacheEntry *oprentry;
1109 
1110  Assert(OprCacheHash != NULL);
1111 
1112  oprentry = (OprCacheEntry *) hash_search(OprCacheHash,
1113  (void *) key,
1114  HASH_ENTER, NULL);
1115  oprentry->opr_oid = opr_oid;
1116 }
1117 
1118 /*
1119  * Callback for pg_operator and pg_cast inval events
1120  */
1121 static void
1122 InvalidateOprCacheCallBack(Datum arg, int cacheid, uint32 hashvalue)
1123 {
1125  OprCacheEntry *hentry;
1126 
1127  Assert(OprCacheHash != NULL);
1128 
1129  /* Currently we just flush all entries; hard to be smarter ... */
1130  hash_seq_init(&status, OprCacheHash);
1131 
1132  while ((hentry = (OprCacheEntry *) hash_seq_search(&status)) != NULL)
1133  {
1134  if (hash_search(OprCacheHash,
1135  (void *) &hentry->key,
1136  HASH_REMOVE, NULL) == NULL)
1137  elog(ERROR, "hash table corrupted");
1138  }
1139 }
#define list_make2(x1, x2)
Definition: pg_list.h:134
Oid LookupOperNameTypeNames(ParseState *pstate, List *opername, TypeName *oprleft, TypeName *oprright, bool noError, int location)
Definition: parse_oper.c:142
static void InvalidateOprCacheCallBack(Datum arg, int cacheid, uint32 hashvalue)
Definition: parse_oper.c:1122
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Definition: namespace.c:2687
int errhint(const char *fmt,...)
Definition: elog.c:987
Expr * make_scalar_array_op(ParseState *pstate, List *opname, bool useOr, Node *ltree, Node *rtree, int location)
Definition: parse_oper.c:856
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define HASH_ELEM
Definition: hsearch.h:87
int func_match_argtypes(int nargs, Oid *input_typeids, FuncCandidateList raw_candidates, FuncCandidateList *candidates)
Definition: parse_func.c:792
Oid oprid(Operator op)
Definition: parse_oper.c:243
Oid get_array_type(Oid typid)
Definition: lsyscache.c:2480
Size entrysize
Definition: hsearch.h:73
Definition: nodes.h:508
#define TYPECACHE_EQ_OPR
Definition: typcache.h:110
Oid left_arg
Definition: parse_oper.c:54
int errcode(int sqlerrcode)
Definition: elog.c:575
#define MemSet(start, val, len)
Definition: c.h:852
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
Expr * make_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree, int location)
Definition: parse_oper.c:740
void DeconstructQualifiedName(List *names, char **nspname_p, char **objname_p)
Definition: namespace.c:2603
Oid LookupOperName(ParseState *pstate, List *opername, Oid oprleft, Oid oprright, bool noError, int location)
Definition: parse_oper.c:102
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
void make_fn_arguments(ParseState *pstate, List *fargs, Oid *actual_arg_types, Oid *declared_arg_types)
Definition: parse_func.c:1692
unsigned int Oid
Definition: postgres_ext.h:31
Oid oprfuncid(Operator op)
Definition: parse_oper.c:250
OprCacheKey key
Definition: parse_oper.c:62
static const char * op_signature_string(List *op, char oprkind, Oid arg1, Oid arg2)
Definition: parse_oper.c:686
#define OidIsValid(objectId)
Definition: c.h:533
int fetch_search_path_array(Oid *sarray, int sarray_len)
Definition: namespace.c:4058
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:149
FuncCandidateList OpernameGetCandidates(List *names, char oprkind, bool missing_schema_ok)
Definition: namespace.c:1546
#define list_make1(x1)
Definition: pg_list.h:133
#define NAMEDATALEN
Oid OpernameGetOprid(List *names, Oid oprleft, Oid oprright)
Definition: namespace.c:1444
Definition: dynahash.c:193
Oid opresulttype
Definition: primnodes.h:475
Oid args[FLEXIBLE_ARRAY_MEMBER]
Definition: namespace.h:37
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:159
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
#define IsPolymorphicType(typid)
Definition: pg_type.h:733
Oid enforce_generic_type_consistency(Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
Operator left_oper(ParseState *pstate, List *op, Oid arg, bool noError, int location)
Definition: parse_oper.c:602
Operator right_oper(ParseState *pstate, List *op, Oid arg, bool noError, int location)
Definition: parse_oper.c:523
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:189
Oid search_path[MAX_CACHED_PATH_LEN]
Definition: parse_oper.c:56
struct OprCacheKey OprCacheKey
int location
Definition: primnodes.h:480
#define RegProcedureIsValid(p)
Definition: c.h:535
FuncDetailCode
Definition: parse_func.h:22
unsigned int uint32
Definition: c.h:265
static Oid find_oper_cache_entry(OprCacheKey *key)
Definition: parse_oper.c:1066
#define TYPECACHE_GT_OPR
Definition: typcache.h:112
static Oid binary_oper_exact(List *opname, Oid arg1, Oid arg2)
Definition: parse_oper.c:267
struct OprCacheEntry OprCacheEntry
struct _FuncCandidateList * next
Definition: namespace.h:30
#define ereport(elevel, rest)
Definition: elog.h:122
Operator compatible_oper(ParseState *pstate, List *op, Oid arg1, Oid arg2, bool noError, int location)
Definition: parse_oper.c:455
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:143
Definition: ltree.h:19
bool IsBinaryCoercible(Oid srctype, Oid targettype)
char oprname[NAMEDATALEN]
Definition: parse_oper.c:53
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
char * NameListToString(List *names)
Definition: namespace.c:2897
bool get_func_retset(Oid funcid)
Definition: lsyscache.c:1514
#define HASH_BLOBS
Definition: hsearch.h:88
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1379
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:301
uintptr_t Datum
Definition: postgres.h:374
static void op_error(ParseState *pstate, List *op, char oprkind, Oid arg1, Oid arg2, FuncDetailCode fdresult, int location)
Definition: parse_oper.c:707
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1083
Oid opfuncid
Definition: primnodes.h:474
static void make_oper_cache_entry(OprCacheKey *key, Oid opr_oid)
Definition: parse_oper.c:1106
Size keysize
Definition: hsearch.h:72
void check_srf_call_placement(ParseState *pstate, int location)
Definition: parse_func.c:2057
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:191
#define InvalidOid
Definition: postgres_ext.h:36
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define makeNode(_type_)
Definition: nodes.h:556
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
void get_sort_group_operators(Oid argtype, bool needLT, bool needEQ, bool needGT, Oid *ltOpr, Oid *eqOpr, Oid *gtOpr, bool *isHashable)
Definition: parse_oper.c:185
static bool make_oper_cache_key(ParseState *pstate, OprCacheKey *key, List *opname, Oid ltypeId, Oid rtypeId, int location)
Definition: parse_oper.c:1022
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1353
#define BOOLOID
Definition: pg_type.h:288
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1343
#define UNKNOWNOID
Definition: pg_type.h:423
FormData_pg_operator* Form_pg_operator
Definition: pg_operator.h:57
static FuncDetailCode oper_select_candidate(int nargs, Oid *input_typeids, FuncCandidateList candidates, Oid *operOid)
Definition: parse_oper.c:317
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2525
Oid right_arg
Definition: parse_oper.c:55
FuncCandidateList func_select_candidate(int nargs, Oid *input_typeids, FuncCandidateList candidates)
Definition: parse_func.c:877
int errmsg(const char *fmt,...)
Definition: elog.c:797
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:492
#define MAX_CACHED_PATH_LEN
Definition: parse_oper.c:49
#define TYPECACHE_LT_OPR
Definition: typcache.h:111
void * arg
Oid opno
Definition: primnodes.h:473
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
List * args
Definition: primnodes.h:479
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
Definition: parse_oper.c:375
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:222
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2239
Definition: pg_list.h:45
#define TYPECACHE_HASH_PROC
Definition: typcache.h:114
static HTAB * OprCacheHash
Definition: parse_oper.c:1008
bool opretset
Definition: primnodes.h:476
Oid LookupTypeNameOid(ParseState *pstate, const TypeName *typeName, bool missing_ok)
Definition: parse_type.c:215