Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * rangetypes.c
4 : * I/O functions, operators, and support functions for range types.
5 : *
6 : * The stored (serialized) format of a range value is:
7 : *
8 : * 4 bytes: varlena header
9 : * 4 bytes: range type's OID
10 : * Lower boundary value, if any, aligned according to subtype's typalign
11 : * Upper boundary value, if any, aligned according to subtype's typalign
12 : * 1 byte for flags
13 : *
14 : * This representation is chosen to avoid needing any padding before the
15 : * lower boundary value, even when it requires double alignment. We can
16 : * expect that the varlena header is presented to us on a suitably aligned
17 : * boundary (possibly after detoasting), and then the lower boundary is too.
18 : * Note that this means we can't work with a packed (short varlena header)
19 : * value; we must detoast it first.
20 : *
21 : *
22 : * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
23 : * Portions Copyright (c) 1994, Regents of the University of California
24 : *
25 : *
26 : * IDENTIFICATION
27 : * src/backend/utils/adt/rangetypes.c
28 : *
29 : *-------------------------------------------------------------------------
30 : */
31 : #include "postgres.h"
32 :
33 : #include "common/hashfn.h"
34 : #include "funcapi.h"
35 : #include "libpq/pqformat.h"
36 : #include "miscadmin.h"
37 : #include "nodes/makefuncs.h"
38 : #include "nodes/miscnodes.h"
39 : #include "nodes/supportnodes.h"
40 : #include "optimizer/clauses.h"
41 : #include "optimizer/cost.h"
42 : #include "optimizer/optimizer.h"
43 : #include "utils/builtins.h"
44 : #include "utils/date.h"
45 : #include "utils/lsyscache.h"
46 : #include "utils/rangetypes.h"
47 : #include "utils/sortsupport.h"
48 : #include "utils/timestamp.h"
49 : #include "varatt.h"
50 :
51 :
52 : /* fn_extra cache entry for one of the range I/O functions */
53 : typedef struct RangeIOData
54 : {
55 : TypeCacheEntry *typcache; /* range type's typcache entry */
56 : FmgrInfo typioproc; /* element type's I/O function */
57 : Oid typioparam; /* element type's I/O parameter */
58 : } RangeIOData;
59 :
60 :
61 : static RangeIOData *get_range_io_data(FunctionCallInfo fcinfo, Oid rngtypid,
62 : IOFuncSelector func);
63 : static int range_fast_cmp(Datum a, Datum b, SortSupport ssup);
64 : static char range_parse_flags(const char *flags_str);
65 : static bool range_parse(const char *string, char *flags, char **lbound_str,
66 : char **ubound_str, Node *escontext);
67 : static const char *range_parse_bound(const char *string, const char *ptr,
68 : char **bound_str, bool *infinite,
69 : Node *escontext);
70 : static char *range_deparse(char flags, const char *lbound_str,
71 : const char *ubound_str);
72 : static char *range_bound_escape(const char *value);
73 : static Size datum_compute_size(Size data_length, Datum val, bool typbyval,
74 : char typalign, int16 typlen, char typstorage);
75 : static Pointer datum_write(Pointer ptr, Datum datum, bool typbyval,
76 : char typalign, int16 typlen, char typstorage);
77 : static Node *find_simplified_clause(PlannerInfo *root,
78 : Expr *rangeExpr, Expr *elemExpr);
79 : static Expr *build_bound_expr(Expr *elemExpr, Datum val,
80 : bool isLowerBound, bool isInclusive,
81 : TypeCacheEntry *typeCache,
82 : Oid opfamily, Oid rng_collation);
83 :
84 :
85 : /*
86 : *----------------------------------------------------------
87 : * I/O FUNCTIONS
88 : *----------------------------------------------------------
89 : */
90 :
91 : Datum
92 7126 : range_in(PG_FUNCTION_ARGS)
93 : {
94 7126 : char *input_str = PG_GETARG_CSTRING(0);
95 7126 : Oid rngtypoid = PG_GETARG_OID(1);
96 7126 : Oid typmod = PG_GETARG_INT32(2);
97 7126 : Node *escontext = fcinfo->context;
98 : RangeType *range;
99 : RangeIOData *cache;
100 : char flags;
101 : char *lbound_str;
102 : char *ubound_str;
103 : RangeBound lower;
104 : RangeBound upper;
105 :
106 7126 : check_stack_depth(); /* recurses when subtype is a range type */
107 :
108 7126 : cache = get_range_io_data(fcinfo, rngtypoid, IOFunc_input);
109 :
110 : /* parse */
111 7126 : if (!range_parse(input_str, &flags, &lbound_str, &ubound_str, escontext))
112 18 : PG_RETURN_NULL();
113 :
114 : /* call element type's input function */
115 7030 : if (RANGE_HAS_LBOUND(flags))
116 6290 : if (!InputFunctionCallSafe(&cache->typioproc, lbound_str,
117 : cache->typioparam, typmod,
118 : escontext, &lower.val))
119 0 : PG_RETURN_NULL();
120 7030 : if (RANGE_HAS_UBOUND(flags))
121 6194 : if (!InputFunctionCallSafe(&cache->typioproc, ubound_str,
122 : cache->typioparam, typmod,
123 : escontext, &upper.val))
124 24 : PG_RETURN_NULL();
125 :
126 7006 : lower.infinite = (flags & RANGE_LB_INF) != 0;
127 7006 : lower.inclusive = (flags & RANGE_LB_INC) != 0;
128 7006 : lower.lower = true;
129 7006 : upper.infinite = (flags & RANGE_UB_INF) != 0;
130 7006 : upper.inclusive = (flags & RANGE_UB_INC) != 0;
131 7006 : upper.lower = false;
132 :
133 : /* serialize and canonicalize */
134 7006 : range = make_range(cache->typcache, &lower, &upper,
135 7006 : flags & RANGE_EMPTY, escontext);
136 :
137 6988 : PG_RETURN_RANGE_P(range);
138 : }
139 :
140 : Datum
141 108246 : range_out(PG_FUNCTION_ARGS)
142 : {
143 108246 : RangeType *range = PG_GETARG_RANGE_P(0);
144 : char *output_str;
145 : RangeIOData *cache;
146 : char flags;
147 108246 : char *lbound_str = NULL;
148 108246 : char *ubound_str = NULL;
149 : RangeBound lower;
150 : RangeBound upper;
151 : bool empty;
152 :
153 108246 : check_stack_depth(); /* recurses when subtype is a range type */
154 :
155 108246 : cache = get_range_io_data(fcinfo, RangeTypeGetOid(range), IOFunc_output);
156 :
157 : /* deserialize */
158 108246 : range_deserialize(cache->typcache, range, &lower, &upper, &empty);
159 108246 : flags = range_get_flags(range);
160 :
161 : /* call element type's output function */
162 108246 : if (RANGE_HAS_LBOUND(flags))
163 88830 : lbound_str = OutputFunctionCall(&cache->typioproc, lower.val);
164 108246 : if (RANGE_HAS_UBOUND(flags))
165 88692 : ubound_str = OutputFunctionCall(&cache->typioproc, upper.val);
166 :
167 : /* construct result string */
168 108246 : output_str = range_deparse(flags, lbound_str, ubound_str);
169 :
170 108246 : PG_RETURN_CSTRING(output_str);
171 : }
172 :
173 : /*
174 : * Binary representation: The first byte is the flags, then the lower bound
175 : * (if present), then the upper bound (if present). Each bound is represented
176 : * by a 4-byte length header and the binary representation of that bound (as
177 : * returned by a call to the send function for the subtype).
178 : */
179 :
180 : Datum
181 0 : range_recv(PG_FUNCTION_ARGS)
182 : {
183 0 : StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
184 0 : Oid rngtypoid = PG_GETARG_OID(1);
185 0 : int32 typmod = PG_GETARG_INT32(2);
186 : RangeType *range;
187 : RangeIOData *cache;
188 : char flags;
189 : RangeBound lower;
190 : RangeBound upper;
191 :
192 0 : check_stack_depth(); /* recurses when subtype is a range type */
193 :
194 0 : cache = get_range_io_data(fcinfo, rngtypoid, IOFunc_receive);
195 :
196 : /* receive the flags... */
197 0 : flags = (unsigned char) pq_getmsgbyte(buf);
198 :
199 : /*
200 : * Mask out any unsupported flags, particularly RANGE_xB_NULL which would
201 : * confuse following tests. Note that range_serialize will take care of
202 : * cleaning up any inconsistencies in the remaining flags.
203 : */
204 0 : flags &= (RANGE_EMPTY |
205 : RANGE_LB_INC |
206 : RANGE_LB_INF |
207 : RANGE_UB_INC |
208 : RANGE_UB_INF);
209 :
210 : /* receive the bounds ... */
211 0 : if (RANGE_HAS_LBOUND(flags))
212 : {
213 0 : uint32 bound_len = pq_getmsgint(buf, 4);
214 0 : const char *bound_data = pq_getmsgbytes(buf, bound_len);
215 : StringInfoData bound_buf;
216 :
217 0 : initStringInfo(&bound_buf);
218 0 : appendBinaryStringInfo(&bound_buf, bound_data, bound_len);
219 :
220 0 : lower.val = ReceiveFunctionCall(&cache->typioproc,
221 : &bound_buf,
222 : cache->typioparam,
223 : typmod);
224 0 : pfree(bound_buf.data);
225 : }
226 : else
227 0 : lower.val = (Datum) 0;
228 :
229 0 : if (RANGE_HAS_UBOUND(flags))
230 : {
231 0 : uint32 bound_len = pq_getmsgint(buf, 4);
232 0 : const char *bound_data = pq_getmsgbytes(buf, bound_len);
233 : StringInfoData bound_buf;
234 :
235 0 : initStringInfo(&bound_buf);
236 0 : appendBinaryStringInfo(&bound_buf, bound_data, bound_len);
237 :
238 0 : upper.val = ReceiveFunctionCall(&cache->typioproc,
239 : &bound_buf,
240 : cache->typioparam,
241 : typmod);
242 0 : pfree(bound_buf.data);
243 : }
244 : else
245 0 : upper.val = (Datum) 0;
246 :
247 0 : pq_getmsgend(buf);
248 :
249 : /* finish constructing RangeBound representation */
250 0 : lower.infinite = (flags & RANGE_LB_INF) != 0;
251 0 : lower.inclusive = (flags & RANGE_LB_INC) != 0;
252 0 : lower.lower = true;
253 0 : upper.infinite = (flags & RANGE_UB_INF) != 0;
254 0 : upper.inclusive = (flags & RANGE_UB_INC) != 0;
255 0 : upper.lower = false;
256 :
257 : /* serialize and canonicalize */
258 0 : range = make_range(cache->typcache, &lower, &upper,
259 0 : flags & RANGE_EMPTY, NULL);
260 :
261 0 : PG_RETURN_RANGE_P(range);
262 : }
263 :
264 : Datum
265 0 : range_send(PG_FUNCTION_ARGS)
266 : {
267 0 : RangeType *range = PG_GETARG_RANGE_P(0);
268 : StringInfoData buf;
269 : RangeIOData *cache;
270 : char flags;
271 : RangeBound lower;
272 : RangeBound upper;
273 : bool empty;
274 :
275 0 : check_stack_depth(); /* recurses when subtype is a range type */
276 :
277 0 : initStringInfo(&buf);
278 :
279 0 : cache = get_range_io_data(fcinfo, RangeTypeGetOid(range), IOFunc_send);
280 :
281 : /* deserialize */
282 0 : range_deserialize(cache->typcache, range, &lower, &upper, &empty);
283 0 : flags = range_get_flags(range);
284 :
285 : /* construct output */
286 0 : pq_begintypsend(&buf);
287 :
288 0 : pq_sendbyte(&buf, flags);
289 :
290 0 : if (RANGE_HAS_LBOUND(flags))
291 : {
292 0 : bytea *bound = SendFunctionCall(&cache->typioproc, lower.val);
293 0 : uint32 bound_len = VARSIZE(bound) - VARHDRSZ;
294 0 : char *bound_data = VARDATA(bound);
295 :
296 0 : pq_sendint32(&buf, bound_len);
297 0 : pq_sendbytes(&buf, bound_data, bound_len);
298 : }
299 :
300 0 : if (RANGE_HAS_UBOUND(flags))
301 : {
302 0 : bytea *bound = SendFunctionCall(&cache->typioproc, upper.val);
303 0 : uint32 bound_len = VARSIZE(bound) - VARHDRSZ;
304 0 : char *bound_data = VARDATA(bound);
305 :
306 0 : pq_sendint32(&buf, bound_len);
307 0 : pq_sendbytes(&buf, bound_data, bound_len);
308 : }
309 :
310 0 : PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
311 : }
312 :
313 : /*
314 : * get_range_io_data: get cached information needed for range type I/O
315 : *
316 : * The range I/O functions need a bit more cached info than other range
317 : * functions, so they store a RangeIOData struct in fn_extra, not just a
318 : * pointer to a type cache entry.
319 : */
320 : static RangeIOData *
321 115372 : get_range_io_data(FunctionCallInfo fcinfo, Oid rngtypid, IOFuncSelector func)
322 : {
323 115372 : RangeIOData *cache = (RangeIOData *) fcinfo->flinfo->fn_extra;
324 :
325 115372 : if (cache == NULL || cache->typcache->type_id != rngtypid)
326 : {
327 : int16 typlen;
328 : bool typbyval;
329 : char typalign;
330 : char typdelim;
331 : Oid typiofunc;
332 :
333 10412 : cache = (RangeIOData *) MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
334 : sizeof(RangeIOData));
335 10412 : cache->typcache = lookup_type_cache(rngtypid, TYPECACHE_RANGE_INFO);
336 10412 : if (cache->typcache->rngelemtype == NULL)
337 0 : elog(ERROR, "type %u is not a range type", rngtypid);
338 :
339 : /* get_type_io_data does more than we need, but is convenient */
340 10412 : get_type_io_data(cache->typcache->rngelemtype->type_id,
341 : func,
342 : &typlen,
343 : &typbyval,
344 : &typalign,
345 : &typdelim,
346 : &cache->typioparam,
347 : &typiofunc);
348 :
349 10412 : if (!OidIsValid(typiofunc))
350 : {
351 : /* this could only happen for receive or send */
352 0 : if (func == IOFunc_receive)
353 0 : ereport(ERROR,
354 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
355 : errmsg("no binary input function available for type %s",
356 : format_type_be(cache->typcache->rngelemtype->type_id))));
357 : else
358 0 : ereport(ERROR,
359 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
360 : errmsg("no binary output function available for type %s",
361 : format_type_be(cache->typcache->rngelemtype->type_id))));
362 : }
363 10412 : fmgr_info_cxt(typiofunc, &cache->typioproc,
364 10412 : fcinfo->flinfo->fn_mcxt);
365 :
366 10412 : fcinfo->flinfo->fn_extra = cache;
367 : }
368 :
369 115372 : return cache;
370 : }
371 :
372 :
373 : /*
374 : *----------------------------------------------------------
375 : * GENERIC FUNCTIONS
376 : *----------------------------------------------------------
377 : */
378 :
379 : /* Construct standard-form range value from two arguments */
380 : Datum
381 110106 : range_constructor2(PG_FUNCTION_ARGS)
382 : {
383 110106 : Datum arg1 = PG_GETARG_DATUM(0);
384 110106 : Datum arg2 = PG_GETARG_DATUM(1);
385 110106 : Oid rngtypid = get_fn_expr_rettype(fcinfo->flinfo);
386 : RangeType *range;
387 : TypeCacheEntry *typcache;
388 : RangeBound lower;
389 : RangeBound upper;
390 :
391 110106 : typcache = range_get_typcache(fcinfo, rngtypid);
392 :
393 110106 : lower.val = PG_ARGISNULL(0) ? (Datum) 0 : arg1;
394 110106 : lower.infinite = PG_ARGISNULL(0);
395 110106 : lower.inclusive = true;
396 110106 : lower.lower = true;
397 :
398 110106 : upper.val = PG_ARGISNULL(1) ? (Datum) 0 : arg2;
399 110106 : upper.infinite = PG_ARGISNULL(1);
400 110106 : upper.inclusive = false;
401 110106 : upper.lower = false;
402 :
403 110106 : range = make_range(typcache, &lower, &upper, false, NULL);
404 :
405 110070 : PG_RETURN_RANGE_P(range);
406 : }
407 :
408 : /* Construct general range value from three arguments */
409 : Datum
410 5208 : range_constructor3(PG_FUNCTION_ARGS)
411 : {
412 5208 : Datum arg1 = PG_GETARG_DATUM(0);
413 5208 : Datum arg2 = PG_GETARG_DATUM(1);
414 5208 : Oid rngtypid = get_fn_expr_rettype(fcinfo->flinfo);
415 : RangeType *range;
416 : TypeCacheEntry *typcache;
417 : RangeBound lower;
418 : RangeBound upper;
419 : char flags;
420 :
421 5208 : typcache = range_get_typcache(fcinfo, rngtypid);
422 :
423 5208 : if (PG_ARGISNULL(2))
424 0 : ereport(ERROR,
425 : (errcode(ERRCODE_DATA_EXCEPTION),
426 : errmsg("range constructor flags argument must not be null")));
427 :
428 5208 : flags = range_parse_flags(text_to_cstring(PG_GETARG_TEXT_PP(2)));
429 :
430 5208 : lower.val = PG_ARGISNULL(0) ? (Datum) 0 : arg1;
431 5208 : lower.infinite = PG_ARGISNULL(0);
432 5208 : lower.inclusive = (flags & RANGE_LB_INC) != 0;
433 5208 : lower.lower = true;
434 :
435 5208 : upper.val = PG_ARGISNULL(1) ? (Datum) 0 : arg2;
436 5208 : upper.infinite = PG_ARGISNULL(1);
437 5208 : upper.inclusive = (flags & RANGE_UB_INC) != 0;
438 5208 : upper.lower = false;
439 :
440 5208 : range = make_range(typcache, &lower, &upper, false, NULL);
441 :
442 5208 : PG_RETURN_RANGE_P(range);
443 : }
444 :
445 :
446 : /* range -> subtype functions */
447 :
448 : /* extract lower bound value */
449 : Datum
450 258 : range_lower(PG_FUNCTION_ARGS)
451 : {
452 258 : RangeType *r1 = PG_GETARG_RANGE_P(0);
453 : TypeCacheEntry *typcache;
454 : RangeBound lower;
455 : RangeBound upper;
456 : bool empty;
457 :
458 258 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
459 :
460 258 : range_deserialize(typcache, r1, &lower, &upper, &empty);
461 :
462 : /* Return NULL if there's no finite lower bound */
463 258 : if (empty || lower.infinite)
464 36 : PG_RETURN_NULL();
465 :
466 222 : PG_RETURN_DATUM(lower.val);
467 : }
468 :
469 : /* extract upper bound value */
470 : Datum
471 228 : range_upper(PG_FUNCTION_ARGS)
472 : {
473 228 : RangeType *r1 = PG_GETARG_RANGE_P(0);
474 : TypeCacheEntry *typcache;
475 : RangeBound lower;
476 : RangeBound upper;
477 : bool empty;
478 :
479 228 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
480 :
481 228 : range_deserialize(typcache, r1, &lower, &upper, &empty);
482 :
483 : /* Return NULL if there's no finite upper bound */
484 228 : if (empty || upper.infinite)
485 36 : PG_RETURN_NULL();
486 :
487 192 : PG_RETURN_DATUM(upper.val);
488 : }
489 :
490 :
491 : /* range -> bool functions */
492 :
493 : /* is range empty? */
494 : Datum
495 2196 : range_empty(PG_FUNCTION_ARGS)
496 : {
497 2196 : RangeType *r1 = PG_GETARG_RANGE_P(0);
498 2196 : char flags = range_get_flags(r1);
499 :
500 2196 : PG_RETURN_BOOL(flags & RANGE_EMPTY);
501 : }
502 :
503 : /* is lower bound inclusive? */
504 : Datum
505 72 : range_lower_inc(PG_FUNCTION_ARGS)
506 : {
507 72 : RangeType *r1 = PG_GETARG_RANGE_P(0);
508 72 : char flags = range_get_flags(r1);
509 :
510 72 : PG_RETURN_BOOL(flags & RANGE_LB_INC);
511 : }
512 :
513 : /* is upper bound inclusive? */
514 : Datum
515 72 : range_upper_inc(PG_FUNCTION_ARGS)
516 : {
517 72 : RangeType *r1 = PG_GETARG_RANGE_P(0);
518 72 : char flags = range_get_flags(r1);
519 :
520 72 : PG_RETURN_BOOL(flags & RANGE_UB_INC);
521 : }
522 :
523 : /* is lower bound infinite? */
524 : Datum
525 72 : range_lower_inf(PG_FUNCTION_ARGS)
526 : {
527 72 : RangeType *r1 = PG_GETARG_RANGE_P(0);
528 72 : char flags = range_get_flags(r1);
529 :
530 72 : PG_RETURN_BOOL(flags & RANGE_LB_INF);
531 : }
532 :
533 : /* is upper bound infinite? */
534 : Datum
535 72 : range_upper_inf(PG_FUNCTION_ARGS)
536 : {
537 72 : RangeType *r1 = PG_GETARG_RANGE_P(0);
538 72 : char flags = range_get_flags(r1);
539 :
540 72 : PG_RETURN_BOOL(flags & RANGE_UB_INF);
541 : }
542 :
543 :
544 : /* range, element -> bool functions */
545 :
546 : /* contains? */
547 : Datum
548 76200 : range_contains_elem(PG_FUNCTION_ARGS)
549 : {
550 76200 : RangeType *r = PG_GETARG_RANGE_P(0);
551 76200 : Datum val = PG_GETARG_DATUM(1);
552 : TypeCacheEntry *typcache;
553 :
554 76200 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
555 :
556 76200 : PG_RETURN_BOOL(range_contains_elem_internal(typcache, r, val));
557 : }
558 :
559 : /* contained by? */
560 : Datum
561 84 : elem_contained_by_range(PG_FUNCTION_ARGS)
562 : {
563 84 : Datum val = PG_GETARG_DATUM(0);
564 84 : RangeType *r = PG_GETARG_RANGE_P(1);
565 : TypeCacheEntry *typcache;
566 :
567 84 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
568 :
569 84 : PG_RETURN_BOOL(range_contains_elem_internal(typcache, r, val));
570 : }
571 :
572 :
573 : /* range, range -> bool functions */
574 :
575 : /* equality (internal version) */
576 : bool
577 158918 : range_eq_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
578 : {
579 : RangeBound lower1,
580 : lower2;
581 : RangeBound upper1,
582 : upper2;
583 : bool empty1,
584 : empty2;
585 :
586 : /* Different types should be prevented by ANYRANGE matching rules */
587 158918 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
588 0 : elog(ERROR, "range types do not match");
589 :
590 158918 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
591 158918 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
592 :
593 158918 : if (empty1 && empty2)
594 7566 : return true;
595 151352 : if (empty1 != empty2)
596 13512 : return false;
597 :
598 137840 : if (range_cmp_bounds(typcache, &lower1, &lower2) != 0)
599 80718 : return false;
600 :
601 57122 : if (range_cmp_bounds(typcache, &upper1, &upper2) != 0)
602 33588 : return false;
603 :
604 23534 : return true;
605 : }
606 :
607 : /* equality */
608 : Datum
609 79234 : range_eq(PG_FUNCTION_ARGS)
610 : {
611 79234 : RangeType *r1 = PG_GETARG_RANGE_P(0);
612 79234 : RangeType *r2 = PG_GETARG_RANGE_P(1);
613 : TypeCacheEntry *typcache;
614 :
615 79234 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
616 :
617 79234 : PG_RETURN_BOOL(range_eq_internal(typcache, r1, r2));
618 : }
619 :
620 : /* inequality (internal version) */
621 : bool
622 0 : range_ne_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
623 : {
624 0 : return (!range_eq_internal(typcache, r1, r2));
625 : }
626 :
627 : /* inequality */
628 : Datum
629 0 : range_ne(PG_FUNCTION_ARGS)
630 : {
631 0 : RangeType *r1 = PG_GETARG_RANGE_P(0);
632 0 : RangeType *r2 = PG_GETARG_RANGE_P(1);
633 : TypeCacheEntry *typcache;
634 :
635 0 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
636 :
637 0 : PG_RETURN_BOOL(range_ne_internal(typcache, r1, r2));
638 : }
639 :
640 : /* contains? */
641 : Datum
642 154470 : range_contains(PG_FUNCTION_ARGS)
643 : {
644 154470 : RangeType *r1 = PG_GETARG_RANGE_P(0);
645 154470 : RangeType *r2 = PG_GETARG_RANGE_P(1);
646 : TypeCacheEntry *typcache;
647 :
648 154470 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
649 :
650 154470 : PG_RETURN_BOOL(range_contains_internal(typcache, r1, r2));
651 : }
652 :
653 : /* contained by? */
654 : Datum
655 76932 : range_contained_by(PG_FUNCTION_ARGS)
656 : {
657 76932 : RangeType *r1 = PG_GETARG_RANGE_P(0);
658 76932 : RangeType *r2 = PG_GETARG_RANGE_P(1);
659 : TypeCacheEntry *typcache;
660 :
661 76932 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
662 :
663 76932 : PG_RETURN_BOOL(range_contained_by_internal(typcache, r1, r2));
664 : }
665 :
666 : /* strictly left of? (internal version) */
667 : bool
668 122182 : range_before_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
669 : {
670 : RangeBound lower1,
671 : lower2;
672 : RangeBound upper1,
673 : upper2;
674 : bool empty1,
675 : empty2;
676 :
677 : /* Different types should be prevented by ANYRANGE matching rules */
678 122182 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
679 0 : elog(ERROR, "range types do not match");
680 :
681 122182 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
682 122182 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
683 :
684 : /* An empty range is neither before nor after any other range */
685 122182 : if (empty1 || empty2)
686 14910 : return false;
687 :
688 107272 : return (range_cmp_bounds(typcache, &upper1, &lower2) < 0);
689 : }
690 :
691 : /* strictly left of? */
692 : Datum
693 78918 : range_before(PG_FUNCTION_ARGS)
694 : {
695 78918 : RangeType *r1 = PG_GETARG_RANGE_P(0);
696 78918 : RangeType *r2 = PG_GETARG_RANGE_P(1);
697 : TypeCacheEntry *typcache;
698 :
699 78918 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
700 :
701 78918 : PG_RETURN_BOOL(range_before_internal(typcache, r1, r2));
702 : }
703 :
704 : /* strictly right of? (internal version) */
705 : bool
706 198364 : range_after_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
707 : {
708 : RangeBound lower1,
709 : lower2;
710 : RangeBound upper1,
711 : upper2;
712 : bool empty1,
713 : empty2;
714 :
715 : /* Different types should be prevented by ANYRANGE matching rules */
716 198364 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
717 0 : elog(ERROR, "range types do not match");
718 :
719 198364 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
720 198364 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
721 :
722 : /* An empty range is neither before nor after any other range */
723 198364 : if (empty1 || empty2)
724 14310 : return false;
725 :
726 184054 : return (range_cmp_bounds(typcache, &lower1, &upper2) > 0);
727 : }
728 :
729 : /* strictly right of? */
730 : Datum
731 78306 : range_after(PG_FUNCTION_ARGS)
732 : {
733 78306 : RangeType *r1 = PG_GETARG_RANGE_P(0);
734 78306 : RangeType *r2 = PG_GETARG_RANGE_P(1);
735 : TypeCacheEntry *typcache;
736 :
737 78306 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
738 :
739 78306 : PG_RETURN_BOOL(range_after_internal(typcache, r1, r2));
740 : }
741 :
742 : /*
743 : * Check if two bounds A and B are "adjacent", where A is an upper bound and B
744 : * is a lower bound. For the bounds to be adjacent, each subtype value must
745 : * satisfy strictly one of the bounds: there are no values which satisfy both
746 : * bounds (i.e. less than A and greater than B); and there are no values which
747 : * satisfy neither bound (i.e. greater than A and less than B).
748 : *
749 : * For discrete ranges, we rely on the canonicalization function to see if A..B
750 : * normalizes to empty. (If there is no canonicalization function, it's
751 : * impossible for such a range to normalize to empty, so we needn't bother to
752 : * try.)
753 : *
754 : * If A == B, the ranges are adjacent only if the bounds have different
755 : * inclusive flags (i.e., exactly one of the ranges includes the common
756 : * boundary point).
757 : *
758 : * And if A > B then the ranges are not adjacent in this order.
759 : */
760 : bool
761 469242 : bounds_adjacent(TypeCacheEntry *typcache, RangeBound boundA, RangeBound boundB)
762 : {
763 : int cmp;
764 :
765 : Assert(!boundA.lower && boundB.lower);
766 :
767 469242 : cmp = range_cmp_bound_values(typcache, &boundA, &boundB);
768 469242 : if (cmp < 0)
769 : {
770 : RangeType *r;
771 :
772 : /*
773 : * Bounds do not overlap; see if there are points in between.
774 : */
775 :
776 : /* in a continuous subtype, there are assumed to be points between */
777 143316 : if (!OidIsValid(typcache->rng_canonical_finfo.fn_oid))
778 924 : return false;
779 :
780 : /*
781 : * The bounds are of a discrete range type; so make a range A..B and
782 : * see if it's empty.
783 : */
784 :
785 : /* flip the inclusion flags */
786 142392 : boundA.inclusive = !boundA.inclusive;
787 142392 : boundB.inclusive = !boundB.inclusive;
788 : /* change upper/lower labels to avoid Assert failures */
789 142392 : boundA.lower = true;
790 142392 : boundB.lower = false;
791 142392 : r = make_range(typcache, &boundA, &boundB, false, NULL);
792 142392 : return RangeIsEmpty(r);
793 : }
794 325926 : else if (cmp == 0)
795 1892 : return boundA.inclusive != boundB.inclusive;
796 : else
797 324034 : return false; /* bounds overlap */
798 : }
799 :
800 : /* adjacent to (but not overlapping)? (internal version) */
801 : bool
802 142128 : range_adjacent_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
803 : {
804 : RangeBound lower1,
805 : lower2;
806 : RangeBound upper1,
807 : upper2;
808 : bool empty1,
809 : empty2;
810 :
811 : /* Different types should be prevented by ANYRANGE matching rules */
812 142128 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
813 0 : elog(ERROR, "range types do not match");
814 :
815 142128 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
816 142128 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
817 :
818 : /* An empty range is not adjacent to any other range */
819 142128 : if (empty1 || empty2)
820 12000 : return false;
821 :
822 : /*
823 : * Given two ranges A..B and C..D, the ranges are adjacent if and only if
824 : * B is adjacent to C, or D is adjacent to A.
825 : */
826 258748 : return (bounds_adjacent(typcache, upper1, lower2) ||
827 128620 : bounds_adjacent(typcache, upper2, lower1));
828 : }
829 :
830 : /* adjacent to (but not overlapping)? */
831 : Datum
832 74436 : range_adjacent(PG_FUNCTION_ARGS)
833 : {
834 74436 : RangeType *r1 = PG_GETARG_RANGE_P(0);
835 74436 : RangeType *r2 = PG_GETARG_RANGE_P(1);
836 : TypeCacheEntry *typcache;
837 :
838 74436 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
839 :
840 74436 : PG_RETURN_BOOL(range_adjacent_internal(typcache, r1, r2));
841 : }
842 :
843 : /* overlaps? (internal version) */
844 : bool
845 96928 : range_overlaps_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
846 : {
847 : RangeBound lower1,
848 : lower2;
849 : RangeBound upper1,
850 : upper2;
851 : bool empty1,
852 : empty2;
853 :
854 : /* Different types should be prevented by ANYRANGE matching rules */
855 96928 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
856 0 : elog(ERROR, "range types do not match");
857 :
858 96928 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
859 96928 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
860 :
861 : /* An empty range does not overlap any other range */
862 96928 : if (empty1 || empty2)
863 14100 : return false;
864 :
865 159046 : if (range_cmp_bounds(typcache, &lower1, &lower2) >= 0 &&
866 76218 : range_cmp_bounds(typcache, &lower1, &upper2) <= 0)
867 5244 : return true;
868 :
869 84194 : if (range_cmp_bounds(typcache, &lower2, &lower1) >= 0 &&
870 6610 : range_cmp_bounds(typcache, &lower2, &upper1) <= 0)
871 5992 : return true;
872 :
873 71592 : return false;
874 : }
875 :
876 : /* overlaps? */
877 : Datum
878 77432 : range_overlaps(PG_FUNCTION_ARGS)
879 : {
880 77432 : RangeType *r1 = PG_GETARG_RANGE_P(0);
881 77432 : RangeType *r2 = PG_GETARG_RANGE_P(1);
882 : TypeCacheEntry *typcache;
883 :
884 77432 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
885 :
886 77432 : PG_RETURN_BOOL(range_overlaps_internal(typcache, r1, r2));
887 : }
888 :
889 : /* does not extend to right of? (internal version) */
890 : bool
891 130550 : range_overleft_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
892 : {
893 : RangeBound lower1,
894 : lower2;
895 : RangeBound upper1,
896 : upper2;
897 : bool empty1,
898 : empty2;
899 :
900 : /* Different types should be prevented by ANYRANGE matching rules */
901 130550 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
902 0 : elog(ERROR, "range types do not match");
903 :
904 130550 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
905 130550 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
906 :
907 : /* An empty range is neither before nor after any other range */
908 130550 : if (empty1 || empty2)
909 13146 : return false;
910 :
911 117404 : if (range_cmp_bounds(typcache, &upper1, &upper2) <= 0)
912 40626 : return true;
913 :
914 76778 : return false;
915 : }
916 :
917 : /* does not extend to right of? */
918 : Datum
919 76506 : range_overleft(PG_FUNCTION_ARGS)
920 : {
921 76506 : RangeType *r1 = PG_GETARG_RANGE_P(0);
922 76506 : RangeType *r2 = PG_GETARG_RANGE_P(1);
923 : TypeCacheEntry *typcache;
924 :
925 76506 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
926 :
927 76506 : PG_RETURN_BOOL(range_overleft_internal(typcache, r1, r2));
928 : }
929 :
930 : /* does not extend to left of? (internal version) */
931 : bool
932 218040 : range_overright_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
933 : {
934 : RangeBound lower1,
935 : lower2;
936 : RangeBound upper1,
937 : upper2;
938 : bool empty1,
939 : empty2;
940 :
941 : /* Different types should be prevented by ANYRANGE matching rules */
942 218040 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
943 0 : elog(ERROR, "range types do not match");
944 :
945 218040 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
946 218040 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
947 :
948 : /* An empty range is neither before nor after any other range */
949 218040 : if (empty1 || empty2)
950 13146 : return false;
951 :
952 204894 : if (range_cmp_bounds(typcache, &lower1, &lower2) >= 0)
953 190958 : return true;
954 :
955 13936 : return false;
956 : }
957 :
958 : /* does not extend to left of? */
959 : Datum
960 76500 : range_overright(PG_FUNCTION_ARGS)
961 : {
962 76500 : RangeType *r1 = PG_GETARG_RANGE_P(0);
963 76500 : RangeType *r2 = PG_GETARG_RANGE_P(1);
964 : TypeCacheEntry *typcache;
965 :
966 76500 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
967 :
968 76500 : PG_RETURN_BOOL(range_overright_internal(typcache, r1, r2));
969 : }
970 :
971 :
972 : /* range, range -> range functions */
973 :
974 : /* set difference */
975 : Datum
976 30 : range_minus(PG_FUNCTION_ARGS)
977 : {
978 30 : RangeType *r1 = PG_GETARG_RANGE_P(0);
979 30 : RangeType *r2 = PG_GETARG_RANGE_P(1);
980 : RangeType *ret;
981 : TypeCacheEntry *typcache;
982 :
983 : /* Different types should be prevented by ANYRANGE matching rules */
984 30 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
985 0 : elog(ERROR, "range types do not match");
986 :
987 30 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
988 :
989 30 : ret = range_minus_internal(typcache, r1, r2);
990 30 : if (ret)
991 30 : PG_RETURN_RANGE_P(ret);
992 : else
993 0 : PG_RETURN_NULL();
994 : }
995 :
996 : RangeType *
997 162 : range_minus_internal(TypeCacheEntry *typcache, RangeType *r1, RangeType *r2)
998 : {
999 : RangeBound lower1,
1000 : lower2;
1001 : RangeBound upper1,
1002 : upper2;
1003 : bool empty1,
1004 : empty2;
1005 : int cmp_l1l2,
1006 : cmp_l1u2,
1007 : cmp_u1l2,
1008 : cmp_u1u2;
1009 :
1010 162 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
1011 162 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
1012 :
1013 : /* if either is empty, r1 is the correct answer */
1014 162 : if (empty1 || empty2)
1015 0 : return r1;
1016 :
1017 162 : cmp_l1l2 = range_cmp_bounds(typcache, &lower1, &lower2);
1018 162 : cmp_l1u2 = range_cmp_bounds(typcache, &lower1, &upper2);
1019 162 : cmp_u1l2 = range_cmp_bounds(typcache, &upper1, &lower2);
1020 162 : cmp_u1u2 = range_cmp_bounds(typcache, &upper1, &upper2);
1021 :
1022 162 : if (cmp_l1l2 < 0 && cmp_u1u2 > 0)
1023 0 : ereport(ERROR,
1024 : (errcode(ERRCODE_DATA_EXCEPTION),
1025 : errmsg("result of range difference would not be contiguous")));
1026 :
1027 162 : if (cmp_l1u2 > 0 || cmp_u1l2 < 0)
1028 12 : return r1;
1029 :
1030 150 : if (cmp_l1l2 >= 0 && cmp_u1u2 <= 0)
1031 78 : return make_empty_range(typcache);
1032 :
1033 72 : if (cmp_l1l2 <= 0 && cmp_u1l2 >= 0 && cmp_u1u2 <= 0)
1034 : {
1035 36 : lower2.inclusive = !lower2.inclusive;
1036 36 : lower2.lower = false; /* it will become the upper bound */
1037 36 : return make_range(typcache, &lower1, &lower2, false, NULL);
1038 : }
1039 :
1040 36 : if (cmp_l1l2 >= 0 && cmp_u1u2 >= 0 && cmp_l1u2 <= 0)
1041 : {
1042 36 : upper2.inclusive = !upper2.inclusive;
1043 36 : upper2.lower = true; /* it will become the lower bound */
1044 36 : return make_range(typcache, &upper2, &upper1, false, NULL);
1045 : }
1046 :
1047 0 : elog(ERROR, "unexpected case in range_minus");
1048 : return NULL;
1049 : }
1050 :
1051 : /*
1052 : * Set union. If strict is true, it is an error that the two input ranges
1053 : * are not adjacent or overlapping.
1054 : */
1055 : RangeType *
1056 1574 : range_union_internal(TypeCacheEntry *typcache, RangeType *r1, RangeType *r2,
1057 : bool strict)
1058 : {
1059 : RangeBound lower1,
1060 : lower2;
1061 : RangeBound upper1,
1062 : upper2;
1063 : bool empty1,
1064 : empty2;
1065 : RangeBound *result_lower;
1066 : RangeBound *result_upper;
1067 :
1068 : /* Different types should be prevented by ANYRANGE matching rules */
1069 1574 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
1070 0 : elog(ERROR, "range types do not match");
1071 :
1072 1574 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
1073 1574 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
1074 :
1075 : /* if either is empty, the other is the correct answer */
1076 1574 : if (empty1)
1077 6 : return r2;
1078 1568 : if (empty2)
1079 0 : return r1;
1080 :
1081 1568 : if (strict &&
1082 138 : !range_overlaps_internal(typcache, r1, r2) &&
1083 12 : !range_adjacent_internal(typcache, r1, r2))
1084 6 : ereport(ERROR,
1085 : (errcode(ERRCODE_DATA_EXCEPTION),
1086 : errmsg("result of range union would not be contiguous")));
1087 :
1088 1562 : if (range_cmp_bounds(typcache, &lower1, &lower2) < 0)
1089 1526 : result_lower = &lower1;
1090 : else
1091 36 : result_lower = &lower2;
1092 :
1093 1562 : if (range_cmp_bounds(typcache, &upper1, &upper2) > 0)
1094 48 : result_upper = &upper1;
1095 : else
1096 1514 : result_upper = &upper2;
1097 :
1098 1562 : return make_range(typcache, result_lower, result_upper, false, NULL);
1099 : }
1100 :
1101 : Datum
1102 18 : range_union(PG_FUNCTION_ARGS)
1103 : {
1104 18 : RangeType *r1 = PG_GETARG_RANGE_P(0);
1105 18 : RangeType *r2 = PG_GETARG_RANGE_P(1);
1106 : TypeCacheEntry *typcache;
1107 :
1108 18 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
1109 :
1110 18 : PG_RETURN_RANGE_P(range_union_internal(typcache, r1, r2, true));
1111 : }
1112 :
1113 : /*
1114 : * range merge: like set union, except also allow and account for non-adjacent
1115 : * input ranges.
1116 : */
1117 : Datum
1118 30 : range_merge(PG_FUNCTION_ARGS)
1119 : {
1120 30 : RangeType *r1 = PG_GETARG_RANGE_P(0);
1121 30 : RangeType *r2 = PG_GETARG_RANGE_P(1);
1122 : TypeCacheEntry *typcache;
1123 :
1124 30 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
1125 :
1126 30 : PG_RETURN_RANGE_P(range_union_internal(typcache, r1, r2, false));
1127 : }
1128 :
1129 : /* set intersection */
1130 : Datum
1131 142 : range_intersect(PG_FUNCTION_ARGS)
1132 : {
1133 142 : RangeType *r1 = PG_GETARG_RANGE_P(0);
1134 142 : RangeType *r2 = PG_GETARG_RANGE_P(1);
1135 : TypeCacheEntry *typcache;
1136 :
1137 : /* Different types should be prevented by ANYRANGE matching rules */
1138 142 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
1139 0 : elog(ERROR, "range types do not match");
1140 :
1141 142 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
1142 :
1143 142 : PG_RETURN_RANGE_P(range_intersect_internal(typcache, r1, r2));
1144 : }
1145 :
1146 : RangeType *
1147 442 : range_intersect_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
1148 : {
1149 : RangeBound lower1,
1150 : lower2;
1151 : RangeBound upper1,
1152 : upper2;
1153 : bool empty1,
1154 : empty2;
1155 : RangeBound *result_lower;
1156 : RangeBound *result_upper;
1157 :
1158 442 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
1159 442 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
1160 :
1161 442 : if (empty1 || empty2 || !range_overlaps_internal(typcache, r1, r2))
1162 30 : return make_empty_range(typcache);
1163 :
1164 412 : if (range_cmp_bounds(typcache, &lower1, &lower2) >= 0)
1165 302 : result_lower = &lower1;
1166 : else
1167 110 : result_lower = &lower2;
1168 :
1169 412 : if (range_cmp_bounds(typcache, &upper1, &upper2) <= 0)
1170 314 : result_upper = &upper1;
1171 : else
1172 98 : result_upper = &upper2;
1173 :
1174 412 : return make_range(typcache, result_lower, result_upper, false, NULL);
1175 : }
1176 :
1177 : /* range, range -> range, range functions */
1178 :
1179 : /*
1180 : * range_split_internal - if r2 intersects the middle of r1, leaving non-empty
1181 : * ranges on both sides, then return true and set output1 and output2 to the
1182 : * results of r1 - r2 (in order). Otherwise return false and don't set output1
1183 : * or output2. Neither input range should be empty.
1184 : */
1185 : bool
1186 264 : range_split_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2,
1187 : RangeType **output1, RangeType **output2)
1188 : {
1189 : RangeBound lower1,
1190 : lower2;
1191 : RangeBound upper1,
1192 : upper2;
1193 : bool empty1,
1194 : empty2;
1195 :
1196 264 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
1197 264 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
1198 :
1199 420 : if (range_cmp_bounds(typcache, &lower1, &lower2) < 0 &&
1200 156 : range_cmp_bounds(typcache, &upper1, &upper2) > 0)
1201 : {
1202 : /*
1203 : * Need to invert inclusive/exclusive for the lower2 and upper2
1204 : * points. They can't be infinite though. We're allowed to overwrite
1205 : * these RangeBounds since they only exist locally.
1206 : */
1207 36 : lower2.inclusive = !lower2.inclusive;
1208 36 : lower2.lower = false;
1209 36 : upper2.inclusive = !upper2.inclusive;
1210 36 : upper2.lower = true;
1211 :
1212 36 : *output1 = make_range(typcache, &lower1, &lower2, false, NULL);
1213 36 : *output2 = make_range(typcache, &upper2, &upper1, false, NULL);
1214 36 : return true;
1215 : }
1216 :
1217 228 : return false;
1218 : }
1219 :
1220 : /*
1221 : * range_minus_multi - like range_minus but as a SRF to accommodate splits,
1222 : * with no result rows if the result would be empty.
1223 : */
1224 : Datum
1225 108 : range_minus_multi(PG_FUNCTION_ARGS)
1226 : {
1227 : struct range_minus_multi_fctx
1228 : {
1229 : RangeType *rs[2];
1230 : int n;
1231 : };
1232 :
1233 : FuncCallContext *funcctx;
1234 : struct range_minus_multi_fctx *fctx;
1235 : MemoryContext oldcontext;
1236 :
1237 : /* stuff done only on the first call of the function */
1238 108 : if (SRF_IS_FIRSTCALL())
1239 : {
1240 : RangeType *r1;
1241 : RangeType *r2;
1242 : Oid rngtypid;
1243 : TypeCacheEntry *typcache;
1244 :
1245 : /* create a function context for cross-call persistence */
1246 54 : funcctx = SRF_FIRSTCALL_INIT();
1247 :
1248 : /*
1249 : * switch to memory context appropriate for multiple function calls
1250 : */
1251 54 : oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1252 :
1253 54 : r1 = PG_GETARG_RANGE_P(0);
1254 54 : r2 = PG_GETARG_RANGE_P(1);
1255 :
1256 : /* Different types should be prevented by ANYRANGE matching rules */
1257 54 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
1258 0 : elog(ERROR, "range types do not match");
1259 :
1260 : /* allocate memory for user context */
1261 54 : fctx = (struct range_minus_multi_fctx *) palloc(sizeof(struct range_minus_multi_fctx));
1262 :
1263 : /*
1264 : * Initialize state. We can't store the range typcache in fn_extra
1265 : * because the caller uses that for the SRF state.
1266 : */
1267 54 : rngtypid = RangeTypeGetOid(r1);
1268 54 : typcache = lookup_type_cache(rngtypid, TYPECACHE_RANGE_INFO);
1269 54 : if (typcache->rngelemtype == NULL)
1270 0 : elog(ERROR, "type %u is not a range type", rngtypid);
1271 54 : range_minus_multi_internal(typcache, r1, r2, fctx->rs, &fctx->n);
1272 :
1273 54 : funcctx->user_fctx = fctx;
1274 54 : MemoryContextSwitchTo(oldcontext);
1275 : }
1276 :
1277 : /* stuff done on every call of the function */
1278 108 : funcctx = SRF_PERCALL_SETUP();
1279 108 : fctx = funcctx->user_fctx;
1280 :
1281 108 : if (funcctx->call_cntr < fctx->n)
1282 : {
1283 : /*
1284 : * We must keep these on separate lines because SRF_RETURN_NEXT does
1285 : * call_cntr++:
1286 : */
1287 54 : RangeType *ret = fctx->rs[funcctx->call_cntr];
1288 :
1289 54 : SRF_RETURN_NEXT(funcctx, RangeTypePGetDatum(ret));
1290 : }
1291 : else
1292 : /* do when there is no more left */
1293 54 : SRF_RETURN_DONE(funcctx);
1294 : }
1295 :
1296 : /*
1297 : * range_minus_multi_internal - Subtracts r2 from r1
1298 : *
1299 : * The subtraction can produce zero, one, or two resulting ranges. We return
1300 : * the results by setting outputs and outputn to the ranges remaining and their
1301 : * count (respectively). The results will never contain empty ranges and will
1302 : * be ordered. Caller should set outputs to a two-element array of RangeType
1303 : * pointers.
1304 : */
1305 : void
1306 54 : range_minus_multi_internal(TypeCacheEntry *typcache, RangeType *r1,
1307 : RangeType *r2, RangeType **outputs, int *outputn)
1308 : {
1309 : int cmp_l1l2,
1310 : cmp_l1u2,
1311 : cmp_u1l2,
1312 : cmp_u1u2;
1313 : RangeBound lower1,
1314 : lower2;
1315 : RangeBound upper1,
1316 : upper2;
1317 : bool empty1,
1318 : empty2;
1319 :
1320 54 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
1321 54 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
1322 :
1323 54 : if (empty1)
1324 : {
1325 : /* if r1 is empty then r1 - r2 is empty, so return zero results */
1326 6 : *outputn = 0;
1327 12 : return;
1328 : }
1329 48 : else if (empty2)
1330 : {
1331 : /* r2 is empty so the result is just r1 (which we know is not empty) */
1332 6 : outputs[0] = r1;
1333 6 : *outputn = 1;
1334 6 : return;
1335 : }
1336 :
1337 : /*
1338 : * Use the same logic as range_minus_internal, but support the split case
1339 : */
1340 42 : cmp_l1l2 = range_cmp_bounds(typcache, &lower1, &lower2);
1341 42 : cmp_l1u2 = range_cmp_bounds(typcache, &lower1, &upper2);
1342 42 : cmp_u1l2 = range_cmp_bounds(typcache, &upper1, &lower2);
1343 42 : cmp_u1u2 = range_cmp_bounds(typcache, &upper1, &upper2);
1344 :
1345 42 : if (cmp_l1l2 < 0 && cmp_u1u2 > 0)
1346 : {
1347 12 : lower2.inclusive = !lower2.inclusive;
1348 12 : lower2.lower = false; /* it will become the upper bound */
1349 12 : outputs[0] = make_range(typcache, &lower1, &lower2, false, NULL);
1350 :
1351 12 : upper2.inclusive = !upper2.inclusive;
1352 12 : upper2.lower = true; /* it will become the lower bound */
1353 12 : outputs[1] = make_range(typcache, &upper2, &upper1, false, NULL);
1354 :
1355 12 : *outputn = 2;
1356 : }
1357 30 : else if (cmp_l1u2 > 0 || cmp_u1l2 < 0)
1358 : {
1359 12 : outputs[0] = r1;
1360 12 : *outputn = 1;
1361 : }
1362 18 : else if (cmp_l1l2 >= 0 && cmp_u1u2 <= 0)
1363 : {
1364 6 : *outputn = 0;
1365 : }
1366 12 : else if (cmp_l1l2 <= 0 && cmp_u1l2 >= 0 && cmp_u1u2 <= 0)
1367 : {
1368 12 : lower2.inclusive = !lower2.inclusive;
1369 12 : lower2.lower = false; /* it will become the upper bound */
1370 12 : outputs[0] = make_range(typcache, &lower1, &lower2, false, NULL);
1371 12 : *outputn = 1;
1372 : }
1373 0 : else if (cmp_l1l2 >= 0 && cmp_u1u2 >= 0 && cmp_l1u2 <= 0)
1374 : {
1375 0 : upper2.inclusive = !upper2.inclusive;
1376 0 : upper2.lower = true; /* it will become the lower bound */
1377 0 : outputs[0] = make_range(typcache, &upper2, &upper1, false, NULL);
1378 0 : *outputn = 1;
1379 : }
1380 : else
1381 : {
1382 0 : elog(ERROR, "unexpected case in range_minus_multi");
1383 : }
1384 : }
1385 :
1386 : /* range -> range aggregate functions */
1387 :
1388 : Datum
1389 42 : range_intersect_agg_transfn(PG_FUNCTION_ARGS)
1390 : {
1391 : MemoryContext aggContext;
1392 : Oid rngtypoid;
1393 : TypeCacheEntry *typcache;
1394 : RangeType *result;
1395 : RangeType *current;
1396 :
1397 42 : if (!AggCheckCallContext(fcinfo, &aggContext))
1398 0 : elog(ERROR, "range_intersect_agg_transfn called in non-aggregate context");
1399 :
1400 42 : rngtypoid = get_fn_expr_argtype(fcinfo->flinfo, 1);
1401 42 : if (!type_is_range(rngtypoid))
1402 0 : elog(ERROR, "range_intersect_agg must be called with a range");
1403 :
1404 42 : typcache = range_get_typcache(fcinfo, rngtypoid);
1405 :
1406 : /* strictness ensures these are non-null */
1407 42 : result = PG_GETARG_RANGE_P(0);
1408 42 : current = PG_GETARG_RANGE_P(1);
1409 :
1410 42 : result = range_intersect_internal(typcache, result, current);
1411 42 : PG_RETURN_RANGE_P(result);
1412 : }
1413 :
1414 :
1415 : /* Btree support */
1416 :
1417 : /* btree comparator */
1418 : Datum
1419 18708 : range_cmp(PG_FUNCTION_ARGS)
1420 : {
1421 18708 : RangeType *r1 = PG_GETARG_RANGE_P(0);
1422 18708 : RangeType *r2 = PG_GETARG_RANGE_P(1);
1423 : TypeCacheEntry *typcache;
1424 : RangeBound lower1,
1425 : lower2;
1426 : RangeBound upper1,
1427 : upper2;
1428 : bool empty1,
1429 : empty2;
1430 : int cmp;
1431 :
1432 18708 : check_stack_depth(); /* recurses when subtype is a range type */
1433 :
1434 : /* Different types should be prevented by ANYRANGE matching rules */
1435 18708 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
1436 0 : elog(ERROR, "range types do not match");
1437 :
1438 18708 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
1439 :
1440 18708 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
1441 18708 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
1442 :
1443 : /* For b-tree use, empty ranges sort before all else */
1444 18708 : if (empty1 && empty2)
1445 2634 : cmp = 0;
1446 16074 : else if (empty1)
1447 3474 : cmp = -1;
1448 12600 : else if (empty2)
1449 2040 : cmp = 1;
1450 : else
1451 : {
1452 10560 : cmp = range_cmp_bounds(typcache, &lower1, &lower2);
1453 10560 : if (cmp == 0)
1454 540 : cmp = range_cmp_bounds(typcache, &upper1, &upper2);
1455 : }
1456 :
1457 18708 : PG_FREE_IF_COPY(r1, 0);
1458 18708 : PG_FREE_IF_COPY(r2, 1);
1459 :
1460 18708 : PG_RETURN_INT32(cmp);
1461 : }
1462 :
1463 : /* Sort support strategy routine */
1464 : Datum
1465 1756 : range_sortsupport(PG_FUNCTION_ARGS)
1466 : {
1467 1756 : SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
1468 :
1469 1756 : ssup->comparator = range_fast_cmp;
1470 1756 : ssup->ssup_extra = NULL;
1471 :
1472 1756 : PG_RETURN_VOID();
1473 : }
1474 :
1475 : /* like range_cmp, but uses the new sortsupport interface */
1476 : static int
1477 540712 : range_fast_cmp(Datum a, Datum b, SortSupport ssup)
1478 : {
1479 540712 : RangeType *range_a = DatumGetRangeTypeP(a);
1480 540712 : RangeType *range_b = DatumGetRangeTypeP(b);
1481 : TypeCacheEntry *typcache;
1482 : RangeBound lower1,
1483 : lower2;
1484 : RangeBound upper1,
1485 : upper2;
1486 : bool empty1,
1487 : empty2;
1488 : int cmp;
1489 :
1490 : /* cache the range info between calls */
1491 540712 : if (ssup->ssup_extra == NULL)
1492 : {
1493 : Assert(RangeTypeGetOid(range_a) == RangeTypeGetOid(range_b));
1494 382 : ssup->ssup_extra =
1495 382 : lookup_type_cache(RangeTypeGetOid(range_a), TYPECACHE_RANGE_INFO);
1496 : }
1497 540712 : typcache = ssup->ssup_extra;
1498 :
1499 540712 : range_deserialize(typcache, range_a, &lower1, &upper1, &empty1);
1500 540712 : range_deserialize(typcache, range_b, &lower2, &upper2, &empty2);
1501 :
1502 : /* For b-tree use, empty ranges sort before all else */
1503 540712 : if (empty1 && empty2)
1504 76080 : cmp = 0;
1505 464632 : else if (empty1)
1506 18324 : cmp = -1;
1507 446308 : else if (empty2)
1508 1464 : cmp = 1;
1509 : else
1510 : {
1511 444844 : cmp = range_cmp_bounds(typcache, &lower1, &lower2);
1512 444844 : if (cmp == 0)
1513 32310 : cmp = range_cmp_bounds(typcache, &upper1, &upper2);
1514 : }
1515 :
1516 540712 : if ((Pointer) range_a != DatumGetPointer(a))
1517 540712 : pfree(range_a);
1518 540712 : if ((Pointer) range_b != DatumGetPointer(b))
1519 540712 : pfree(range_b);
1520 :
1521 540712 : return cmp;
1522 : }
1523 :
1524 :
1525 : /* inequality operators using the range_cmp function */
1526 : Datum
1527 1338 : range_lt(PG_FUNCTION_ARGS)
1528 : {
1529 1338 : int cmp = DatumGetInt32(range_cmp(fcinfo));
1530 :
1531 1338 : PG_RETURN_BOOL(cmp < 0);
1532 : }
1533 :
1534 : Datum
1535 3012 : range_le(PG_FUNCTION_ARGS)
1536 : {
1537 3012 : int cmp = DatumGetInt32(range_cmp(fcinfo));
1538 :
1539 3012 : PG_RETURN_BOOL(cmp <= 0);
1540 : }
1541 :
1542 : Datum
1543 3036 : range_ge(PG_FUNCTION_ARGS)
1544 : {
1545 3036 : int cmp = DatumGetInt32(range_cmp(fcinfo));
1546 :
1547 3036 : PG_RETURN_BOOL(cmp >= 0);
1548 : }
1549 :
1550 : Datum
1551 3072 : range_gt(PG_FUNCTION_ARGS)
1552 : {
1553 3072 : int cmp = DatumGetInt32(range_cmp(fcinfo));
1554 :
1555 3072 : PG_RETURN_BOOL(cmp > 0);
1556 : }
1557 :
1558 : /* Hash support */
1559 :
1560 : /* hash a range value */
1561 : Datum
1562 210 : hash_range(PG_FUNCTION_ARGS)
1563 : {
1564 210 : RangeType *r = PG_GETARG_RANGE_P(0);
1565 : uint32 result;
1566 : TypeCacheEntry *typcache;
1567 : TypeCacheEntry *scache;
1568 : RangeBound lower;
1569 : RangeBound upper;
1570 : bool empty;
1571 : char flags;
1572 : uint32 lower_hash;
1573 : uint32 upper_hash;
1574 :
1575 210 : check_stack_depth(); /* recurses when subtype is a range type */
1576 :
1577 210 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
1578 :
1579 : /* deserialize */
1580 210 : range_deserialize(typcache, r, &lower, &upper, &empty);
1581 210 : flags = range_get_flags(r);
1582 :
1583 : /*
1584 : * Look up the element type's hash function, if not done already.
1585 : */
1586 210 : scache = typcache->rngelemtype;
1587 210 : if (!OidIsValid(scache->hash_proc_finfo.fn_oid))
1588 : {
1589 6 : scache = lookup_type_cache(scache->type_id, TYPECACHE_HASH_PROC_FINFO);
1590 6 : if (!OidIsValid(scache->hash_proc_finfo.fn_oid))
1591 0 : ereport(ERROR,
1592 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
1593 : errmsg("could not identify a hash function for type %s",
1594 : format_type_be(scache->type_id))));
1595 : }
1596 :
1597 : /*
1598 : * Apply the hash function to each bound.
1599 : */
1600 210 : if (RANGE_HAS_LBOUND(flags))
1601 144 : lower_hash = DatumGetUInt32(FunctionCall1Coll(&scache->hash_proc_finfo,
1602 : typcache->rng_collation,
1603 : lower.val));
1604 : else
1605 66 : lower_hash = 0;
1606 :
1607 210 : if (RANGE_HAS_UBOUND(flags))
1608 156 : upper_hash = DatumGetUInt32(FunctionCall1Coll(&scache->hash_proc_finfo,
1609 : typcache->rng_collation,
1610 : upper.val));
1611 : else
1612 54 : upper_hash = 0;
1613 :
1614 : /* Merge hashes of flags and bounds */
1615 210 : result = hash_bytes_uint32((uint32) flags);
1616 210 : result ^= lower_hash;
1617 210 : result = pg_rotate_left32(result, 1);
1618 210 : result ^= upper_hash;
1619 :
1620 210 : PG_RETURN_INT32(result);
1621 : }
1622 :
1623 : /*
1624 : * Returns 64-bit value by hashing a value to a 64-bit value, with a seed.
1625 : * Otherwise, similar to hash_range.
1626 : */
1627 : Datum
1628 60 : hash_range_extended(PG_FUNCTION_ARGS)
1629 : {
1630 60 : RangeType *r = PG_GETARG_RANGE_P(0);
1631 60 : Datum seed = PG_GETARG_DATUM(1);
1632 : uint64 result;
1633 : TypeCacheEntry *typcache;
1634 : TypeCacheEntry *scache;
1635 : RangeBound lower;
1636 : RangeBound upper;
1637 : bool empty;
1638 : char flags;
1639 : uint64 lower_hash;
1640 : uint64 upper_hash;
1641 :
1642 60 : check_stack_depth();
1643 :
1644 60 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
1645 :
1646 60 : range_deserialize(typcache, r, &lower, &upper, &empty);
1647 60 : flags = range_get_flags(r);
1648 :
1649 60 : scache = typcache->rngelemtype;
1650 60 : if (!OidIsValid(scache->hash_extended_proc_finfo.fn_oid))
1651 : {
1652 0 : scache = lookup_type_cache(scache->type_id,
1653 : TYPECACHE_HASH_EXTENDED_PROC_FINFO);
1654 0 : if (!OidIsValid(scache->hash_extended_proc_finfo.fn_oid))
1655 0 : ereport(ERROR,
1656 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
1657 : errmsg("could not identify a hash function for type %s",
1658 : format_type_be(scache->type_id))));
1659 : }
1660 :
1661 60 : if (RANGE_HAS_LBOUND(flags))
1662 60 : lower_hash = DatumGetUInt64(FunctionCall2Coll(&scache->hash_extended_proc_finfo,
1663 : typcache->rng_collation,
1664 : lower.val,
1665 : seed));
1666 : else
1667 0 : lower_hash = 0;
1668 :
1669 60 : if (RANGE_HAS_UBOUND(flags))
1670 60 : upper_hash = DatumGetUInt64(FunctionCall2Coll(&scache->hash_extended_proc_finfo,
1671 : typcache->rng_collation,
1672 : upper.val,
1673 : seed));
1674 : else
1675 0 : upper_hash = 0;
1676 :
1677 : /* Merge hashes of flags and bounds */
1678 60 : result = DatumGetUInt64(hash_uint32_extended((uint32) flags,
1679 60 : DatumGetInt64(seed)));
1680 60 : result ^= lower_hash;
1681 60 : result = ROTATE_HIGH_AND_LOW_32BITS(result);
1682 60 : result ^= upper_hash;
1683 :
1684 60 : PG_RETURN_UINT64(result);
1685 : }
1686 :
1687 : /*
1688 : *----------------------------------------------------------
1689 : * CANONICAL FUNCTIONS
1690 : *
1691 : * Functions for specific built-in range types.
1692 : *----------------------------------------------------------
1693 : */
1694 :
1695 : Datum
1696 443936 : int4range_canonical(PG_FUNCTION_ARGS)
1697 : {
1698 443936 : RangeType *r = PG_GETARG_RANGE_P(0);
1699 443936 : Node *escontext = fcinfo->context;
1700 : TypeCacheEntry *typcache;
1701 : RangeBound lower;
1702 : RangeBound upper;
1703 : bool empty;
1704 :
1705 443936 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
1706 :
1707 443936 : range_deserialize(typcache, r, &lower, &upper, &empty);
1708 :
1709 443936 : if (empty)
1710 0 : PG_RETURN_RANGE_P(r);
1711 :
1712 443936 : if (!lower.infinite && !lower.inclusive)
1713 : {
1714 3248 : int32 bnd = DatumGetInt32(lower.val);
1715 :
1716 : /* Handle possible overflow manually */
1717 3248 : if (unlikely(bnd == PG_INT32_MAX))
1718 0 : ereturn(escontext, (Datum) 0,
1719 : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
1720 : errmsg("integer out of range")));
1721 3248 : lower.val = Int32GetDatum(bnd + 1);
1722 3248 : lower.inclusive = true;
1723 : }
1724 :
1725 443936 : if (!upper.infinite && upper.inclusive)
1726 : {
1727 3242 : int32 bnd = DatumGetInt32(upper.val);
1728 :
1729 : /* Handle possible overflow manually */
1730 3242 : if (unlikely(bnd == PG_INT32_MAX))
1731 12 : ereturn(escontext, (Datum) 0,
1732 : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
1733 : errmsg("integer out of range")));
1734 3230 : upper.val = Int32GetDatum(bnd + 1);
1735 3230 : upper.inclusive = false;
1736 : }
1737 :
1738 443924 : PG_RETURN_RANGE_P(range_serialize(typcache, &lower, &upper,
1739 : false, escontext));
1740 : }
1741 :
1742 : Datum
1743 98 : int8range_canonical(PG_FUNCTION_ARGS)
1744 : {
1745 98 : RangeType *r = PG_GETARG_RANGE_P(0);
1746 98 : Node *escontext = fcinfo->context;
1747 : TypeCacheEntry *typcache;
1748 : RangeBound lower;
1749 : RangeBound upper;
1750 : bool empty;
1751 :
1752 98 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
1753 :
1754 98 : range_deserialize(typcache, r, &lower, &upper, &empty);
1755 :
1756 98 : if (empty)
1757 0 : PG_RETURN_RANGE_P(r);
1758 :
1759 98 : if (!lower.infinite && !lower.inclusive)
1760 : {
1761 18 : int64 bnd = DatumGetInt64(lower.val);
1762 :
1763 : /* Handle possible overflow manually */
1764 18 : if (unlikely(bnd == PG_INT64_MAX))
1765 0 : ereturn(escontext, (Datum) 0,
1766 : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
1767 : errmsg("bigint out of range")));
1768 18 : lower.val = Int64GetDatum(bnd + 1);
1769 18 : lower.inclusive = true;
1770 : }
1771 :
1772 98 : if (!upper.infinite && upper.inclusive)
1773 : {
1774 24 : int64 bnd = DatumGetInt64(upper.val);
1775 :
1776 : /* Handle possible overflow manually */
1777 24 : if (unlikely(bnd == PG_INT64_MAX))
1778 0 : ereturn(escontext, (Datum) 0,
1779 : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
1780 : errmsg("bigint out of range")));
1781 24 : upper.val = Int64GetDatum(bnd + 1);
1782 24 : upper.inclusive = false;
1783 : }
1784 :
1785 98 : PG_RETURN_RANGE_P(range_serialize(typcache, &lower, &upper,
1786 : false, escontext));
1787 : }
1788 :
1789 : Datum
1790 3642 : daterange_canonical(PG_FUNCTION_ARGS)
1791 : {
1792 3642 : RangeType *r = PG_GETARG_RANGE_P(0);
1793 3642 : Node *escontext = fcinfo->context;
1794 : TypeCacheEntry *typcache;
1795 : RangeBound lower;
1796 : RangeBound upper;
1797 : bool empty;
1798 :
1799 3642 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
1800 :
1801 3642 : range_deserialize(typcache, r, &lower, &upper, &empty);
1802 :
1803 3642 : if (empty)
1804 0 : PG_RETURN_RANGE_P(r);
1805 :
1806 3642 : if (!lower.infinite && !DATE_NOT_FINITE(DatumGetDateADT(lower.val)) &&
1807 3594 : !lower.inclusive)
1808 : {
1809 36 : DateADT bnd = DatumGetDateADT(lower.val);
1810 :
1811 : /* Check for overflow -- note we already eliminated PG_INT32_MAX */
1812 36 : bnd++;
1813 36 : if (unlikely(!IS_VALID_DATE(bnd)))
1814 0 : ereturn(escontext, (Datum) 0,
1815 : (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1816 : errmsg("date out of range")));
1817 36 : lower.val = DateADTGetDatum(bnd);
1818 36 : lower.inclusive = true;
1819 : }
1820 :
1821 3642 : if (!upper.infinite && !DATE_NOT_FINITE(DatumGetDateADT(upper.val)) &&
1822 3468 : upper.inclusive)
1823 : {
1824 36 : DateADT bnd = DatumGetDateADT(upper.val);
1825 :
1826 : /* Check for overflow -- note we already eliminated PG_INT32_MAX */
1827 36 : bnd++;
1828 36 : if (unlikely(!IS_VALID_DATE(bnd)))
1829 12 : ereturn(escontext, (Datum) 0,
1830 : (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1831 : errmsg("date out of range")));
1832 24 : upper.val = DateADTGetDatum(bnd);
1833 24 : upper.inclusive = false;
1834 : }
1835 :
1836 3630 : PG_RETURN_RANGE_P(range_serialize(typcache, &lower, &upper,
1837 : false, escontext));
1838 : }
1839 :
1840 : /*
1841 : *----------------------------------------------------------
1842 : * SUBTYPE_DIFF FUNCTIONS
1843 : *
1844 : * Functions for specific built-in range types.
1845 : *
1846 : * Note that subtype_diff does return the difference, not the absolute value
1847 : * of the difference, and it must take care to avoid overflow.
1848 : * (numrange_subdiff is at some risk there ...)
1849 : *----------------------------------------------------------
1850 : */
1851 :
1852 : Datum
1853 821754 : int4range_subdiff(PG_FUNCTION_ARGS)
1854 : {
1855 821754 : int32 v1 = PG_GETARG_INT32(0);
1856 821754 : int32 v2 = PG_GETARG_INT32(1);
1857 :
1858 821754 : PG_RETURN_FLOAT8((float8) v1 - (float8) v2);
1859 : }
1860 :
1861 : Datum
1862 0 : int8range_subdiff(PG_FUNCTION_ARGS)
1863 : {
1864 0 : int64 v1 = PG_GETARG_INT64(0);
1865 0 : int64 v2 = PG_GETARG_INT64(1);
1866 :
1867 0 : PG_RETURN_FLOAT8((float8) v1 - (float8) v2);
1868 : }
1869 :
1870 : Datum
1871 246 : numrange_subdiff(PG_FUNCTION_ARGS)
1872 : {
1873 246 : Datum v1 = PG_GETARG_DATUM(0);
1874 246 : Datum v2 = PG_GETARG_DATUM(1);
1875 : Datum numresult;
1876 : float8 floatresult;
1877 :
1878 246 : numresult = DirectFunctionCall2(numeric_sub, v1, v2);
1879 :
1880 246 : floatresult = DatumGetFloat8(DirectFunctionCall1(numeric_float8,
1881 : numresult));
1882 :
1883 246 : PG_RETURN_FLOAT8(floatresult);
1884 : }
1885 :
1886 : Datum
1887 0 : daterange_subdiff(PG_FUNCTION_ARGS)
1888 : {
1889 0 : int32 v1 = PG_GETARG_INT32(0);
1890 0 : int32 v2 = PG_GETARG_INT32(1);
1891 :
1892 0 : PG_RETURN_FLOAT8((float8) v1 - (float8) v2);
1893 : }
1894 :
1895 : Datum
1896 0 : tsrange_subdiff(PG_FUNCTION_ARGS)
1897 : {
1898 0 : Timestamp v1 = PG_GETARG_TIMESTAMP(0);
1899 0 : Timestamp v2 = PG_GETARG_TIMESTAMP(1);
1900 : float8 result;
1901 :
1902 0 : result = ((float8) v1 - (float8) v2) / USECS_PER_SEC;
1903 0 : PG_RETURN_FLOAT8(result);
1904 : }
1905 :
1906 : Datum
1907 0 : tstzrange_subdiff(PG_FUNCTION_ARGS)
1908 : {
1909 0 : Timestamp v1 = PG_GETARG_TIMESTAMP(0);
1910 0 : Timestamp v2 = PG_GETARG_TIMESTAMP(1);
1911 : float8 result;
1912 :
1913 0 : result = ((float8) v1 - (float8) v2) / USECS_PER_SEC;
1914 0 : PG_RETURN_FLOAT8(result);
1915 : }
1916 :
1917 : /*
1918 : *----------------------------------------------------------
1919 : * SUPPORT FUNCTIONS
1920 : *
1921 : * These functions aren't in pg_proc, but are useful for
1922 : * defining new generic range functions in C.
1923 : *----------------------------------------------------------
1924 : */
1925 :
1926 : /*
1927 : * range_get_typcache: get cached information about a range type
1928 : *
1929 : * This is for use by range-related functions that follow the convention
1930 : * of using the fn_extra field as a pointer to the type cache entry for
1931 : * the range type. Functions that need to cache more information than
1932 : * that must fend for themselves.
1933 : */
1934 : TypeCacheEntry *
1935 4108644 : range_get_typcache(FunctionCallInfo fcinfo, Oid rngtypid)
1936 : {
1937 4108644 : TypeCacheEntry *typcache = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
1938 :
1939 4108644 : if (typcache == NULL ||
1940 4089776 : typcache->type_id != rngtypid)
1941 : {
1942 18868 : typcache = lookup_type_cache(rngtypid, TYPECACHE_RANGE_INFO);
1943 18868 : if (typcache->rngelemtype == NULL)
1944 0 : elog(ERROR, "type %u is not a range type", rngtypid);
1945 18868 : fcinfo->flinfo->fn_extra = typcache;
1946 : }
1947 :
1948 4108644 : return typcache;
1949 : }
1950 :
1951 : /*
1952 : * range_serialize: construct a range value from bounds and empty-flag
1953 : *
1954 : * This does not force canonicalization of the range value. In most cases,
1955 : * external callers should only be canonicalization functions. Note that
1956 : * we perform some datatype-independent canonicalization checks anyway.
1957 : */
1958 : RangeType *
1959 907636 : range_serialize(TypeCacheEntry *typcache, RangeBound *lower, RangeBound *upper,
1960 : bool empty, struct Node *escontext)
1961 : {
1962 : RangeType *range;
1963 : int cmp;
1964 : Size msize;
1965 : Pointer ptr;
1966 : int16 typlen;
1967 : bool typbyval;
1968 : char typalign;
1969 : char typstorage;
1970 907636 : char flags = 0;
1971 :
1972 : /*
1973 : * Verify range is not invalid on its face, and construct flags value,
1974 : * preventing any non-canonical combinations such as infinite+inclusive.
1975 : */
1976 : Assert(lower->lower);
1977 : Assert(!upper->lower);
1978 :
1979 907636 : if (empty)
1980 3798 : flags |= RANGE_EMPTY;
1981 : else
1982 : {
1983 903838 : cmp = range_cmp_bound_values(typcache, lower, upper);
1984 :
1985 : /* error check: if lower bound value is above upper, it's wrong */
1986 903838 : if (cmp > 0)
1987 66 : ereturn(escontext, NULL,
1988 : (errcode(ERRCODE_DATA_EXCEPTION),
1989 : errmsg("range lower bound must be less than or equal to range upper bound")));
1990 :
1991 : /* if bounds are equal, and not both inclusive, range is empty */
1992 903772 : if (cmp == 0 && !(lower->inclusive && upper->inclusive))
1993 384 : flags |= RANGE_EMPTY;
1994 : else
1995 : {
1996 : /* infinite boundaries are never inclusive */
1997 903388 : if (lower->infinite)
1998 11592 : flags |= RANGE_LB_INF;
1999 891796 : else if (lower->inclusive)
2000 888140 : flags |= RANGE_LB_INC;
2001 903388 : if (upper->infinite)
2002 7056 : flags |= RANGE_UB_INF;
2003 896332 : else if (upper->inclusive)
2004 4180 : flags |= RANGE_UB_INC;
2005 : }
2006 : }
2007 :
2008 : /* Fetch information about range's element type */
2009 907570 : typlen = typcache->rngelemtype->typlen;
2010 907570 : typbyval = typcache->rngelemtype->typbyval;
2011 907570 : typalign = typcache->rngelemtype->typalign;
2012 907570 : typstorage = typcache->rngelemtype->typstorage;
2013 :
2014 : /* Count space for varlena header and range type's OID */
2015 907570 : msize = sizeof(RangeType);
2016 : Assert(msize == MAXALIGN(msize));
2017 :
2018 : /* Count space for bounds */
2019 907570 : if (RANGE_HAS_LBOUND(flags))
2020 : {
2021 : /*
2022 : * Make sure item to be inserted is not toasted. It is essential that
2023 : * we not insert an out-of-line toast value pointer into a range
2024 : * object, for the same reasons that arrays and records can't contain
2025 : * them. It would work to store a compressed-in-line value, but we
2026 : * prefer to decompress and then let compression be applied to the
2027 : * whole range object if necessary. But, unlike arrays, we do allow
2028 : * short-header varlena objects to stay as-is.
2029 : */
2030 891796 : if (typlen == -1)
2031 5234 : lower->val = PointerGetDatum(PG_DETOAST_DATUM_PACKED(lower->val));
2032 :
2033 891796 : msize = datum_compute_size(msize, lower->val, typbyval, typalign,
2034 : typlen, typstorage);
2035 : }
2036 :
2037 907570 : if (RANGE_HAS_UBOUND(flags))
2038 : {
2039 : /* Make sure item to be inserted is not toasted */
2040 896332 : if (typlen == -1)
2041 5192 : upper->val = PointerGetDatum(PG_DETOAST_DATUM_PACKED(upper->val));
2042 :
2043 896332 : msize = datum_compute_size(msize, upper->val, typbyval, typalign,
2044 : typlen, typstorage);
2045 : }
2046 :
2047 : /* Add space for flag byte */
2048 907570 : msize += sizeof(char);
2049 :
2050 : /* Note: zero-fill is required here, just as in heap tuples */
2051 907570 : range = (RangeType *) palloc0(msize);
2052 907570 : SET_VARSIZE(range, msize);
2053 :
2054 : /* Now fill in the datum */
2055 907570 : range->rangetypid = typcache->type_id;
2056 :
2057 907570 : ptr = (char *) (range + 1);
2058 :
2059 907570 : if (RANGE_HAS_LBOUND(flags))
2060 : {
2061 : Assert(lower->lower);
2062 891796 : ptr = datum_write(ptr, lower->val, typbyval, typalign, typlen,
2063 : typstorage);
2064 : }
2065 :
2066 907570 : if (RANGE_HAS_UBOUND(flags))
2067 : {
2068 : Assert(!upper->lower);
2069 896332 : ptr = datum_write(ptr, upper->val, typbyval, typalign, typlen,
2070 : typstorage);
2071 : }
2072 :
2073 907570 : *((char *) ptr) = flags;
2074 :
2075 907570 : return range;
2076 : }
2077 :
2078 : /*
2079 : * range_deserialize: deconstruct a range value
2080 : *
2081 : * NB: the given range object must be fully detoasted; it cannot have a
2082 : * short varlena header.
2083 : *
2084 : * Note that if the element type is pass-by-reference, the datums in the
2085 : * RangeBound structs will be pointers into the given range object.
2086 : */
2087 : void
2088 9703116 : range_deserialize(TypeCacheEntry *typcache, const RangeType *range,
2089 : RangeBound *lower, RangeBound *upper, bool *empty)
2090 : {
2091 : char flags;
2092 : int16 typlen;
2093 : bool typbyval;
2094 : char typalign;
2095 : Pointer ptr;
2096 : Datum lbound;
2097 : Datum ubound;
2098 :
2099 : /* assert caller passed the right typcache entry */
2100 : Assert(RangeTypeGetOid(range) == typcache->type_id);
2101 :
2102 : /* fetch the flag byte from datum's last byte */
2103 9703116 : flags = *((const char *) range + VARSIZE(range) - 1);
2104 :
2105 : /* fetch information about range's element type */
2106 9703116 : typlen = typcache->rngelemtype->typlen;
2107 9703116 : typbyval = typcache->rngelemtype->typbyval;
2108 9703116 : typalign = typcache->rngelemtype->typalign;
2109 :
2110 : /* initialize data pointer just after the range OID */
2111 9703116 : ptr = (Pointer) (range + 1);
2112 :
2113 : /* fetch lower bound, if any */
2114 9703116 : if (RANGE_HAS_LBOUND(flags))
2115 : {
2116 : /* att_align_pointer cannot be necessary here */
2117 8556102 : lbound = fetch_att(ptr, typbyval, typlen);
2118 8556102 : ptr = (Pointer) att_addlength_pointer(ptr, typlen, ptr);
2119 : }
2120 : else
2121 1147014 : lbound = (Datum) 0;
2122 :
2123 : /* fetch upper bound, if any */
2124 9703116 : if (RANGE_HAS_UBOUND(flags))
2125 : {
2126 8581510 : ptr = (Pointer) att_align_pointer(ptr, typalign, typlen, ptr);
2127 8581510 : ubound = fetch_att(ptr, typbyval, typlen);
2128 : /* no need for att_addlength_pointer */
2129 : }
2130 : else
2131 1121606 : ubound = (Datum) 0;
2132 :
2133 : /* emit results */
2134 :
2135 9703116 : *empty = (flags & RANGE_EMPTY) != 0;
2136 :
2137 9703116 : lower->val = lbound;
2138 9703116 : lower->infinite = (flags & RANGE_LB_INF) != 0;
2139 9703116 : lower->inclusive = (flags & RANGE_LB_INC) != 0;
2140 9703116 : lower->lower = true;
2141 :
2142 9703116 : upper->val = ubound;
2143 9703116 : upper->infinite = (flags & RANGE_UB_INF) != 0;
2144 9703116 : upper->inclusive = (flags & RANGE_UB_INC) != 0;
2145 9703116 : upper->lower = false;
2146 9703116 : }
2147 :
2148 : /*
2149 : * range_get_flags: just get the flags from a RangeType value.
2150 : *
2151 : * This is frequently useful in places that only need the flags and not
2152 : * the full results of range_deserialize.
2153 : */
2154 : char
2155 2941304 : range_get_flags(const RangeType *range)
2156 : {
2157 : /* fetch the flag byte from datum's last byte */
2158 2941304 : return *((char *) range + VARSIZE(range) - 1);
2159 : }
2160 :
2161 : /*
2162 : * range_set_contain_empty: set the RANGE_CONTAIN_EMPTY bit in the value.
2163 : *
2164 : * This is only needed in GiST operations, so we don't include a provision
2165 : * for setting it in range_serialize; rather, this function must be applied
2166 : * afterwards.
2167 : */
2168 : void
2169 618 : range_set_contain_empty(RangeType *range)
2170 : {
2171 : char *flagsp;
2172 :
2173 : /* flag byte is datum's last byte */
2174 618 : flagsp = (char *) range + VARSIZE(range) - 1;
2175 :
2176 618 : *flagsp |= RANGE_CONTAIN_EMPTY;
2177 618 : }
2178 :
2179 : /*
2180 : * This both serializes and canonicalizes (if applicable) the range.
2181 : * This should be used by most callers.
2182 : */
2183 : RangeType *
2184 457620 : make_range(TypeCacheEntry *typcache, RangeBound *lower, RangeBound *upper,
2185 : bool empty, struct Node *escontext)
2186 : {
2187 : RangeType *range;
2188 :
2189 457620 : range = range_serialize(typcache, lower, upper, empty, escontext);
2190 :
2191 457566 : if (SOFT_ERROR_OCCURRED(escontext))
2192 12 : return NULL;
2193 :
2194 : /* no need to call canonical on empty ranges ... */
2195 457554 : if (OidIsValid(typcache->rng_canonical_finfo.fn_oid) &&
2196 451396 : !RangeIsEmpty(range))
2197 : {
2198 : /* Do this the hard way so that we can pass escontext */
2199 447676 : LOCAL_FCINFO(fcinfo, 1);
2200 : Datum result;
2201 :
2202 447676 : InitFunctionCallInfoData(*fcinfo, &typcache->rng_canonical_finfo, 1,
2203 : InvalidOid, escontext, NULL);
2204 :
2205 447676 : fcinfo->args[0].value = RangeTypePGetDatum(range);
2206 447676 : fcinfo->args[0].isnull = false;
2207 :
2208 447676 : result = FunctionCallInvoke(fcinfo);
2209 :
2210 447676 : if (SOFT_ERROR_OCCURRED(escontext))
2211 24 : return NULL;
2212 :
2213 : /* Should not get a null result if there was no error */
2214 447652 : if (fcinfo->isnull)
2215 0 : elog(ERROR, "function %u returned NULL",
2216 : typcache->rng_canonical_finfo.fn_oid);
2217 :
2218 447652 : range = DatumGetRangeTypeP(result);
2219 : }
2220 :
2221 457530 : return range;
2222 : }
2223 :
2224 : /*
2225 : * Compare two range boundary points, returning <0, 0, or >0 according to
2226 : * whether b1 is less than, equal to, or greater than b2.
2227 : *
2228 : * The boundaries can be any combination of upper and lower; so it's useful
2229 : * for a variety of operators.
2230 : *
2231 : * The simple case is when b1 and b2 are both finite and inclusive, in which
2232 : * case the result is just a comparison of the values held in b1 and b2.
2233 : *
2234 : * If a bound is exclusive, then we need to know whether it's a lower bound,
2235 : * in which case we treat the boundary point as "just greater than" the held
2236 : * value; or an upper bound, in which case we treat the boundary point as
2237 : * "just less than" the held value.
2238 : *
2239 : * If a bound is infinite, it represents minus infinity (less than every other
2240 : * point) if it's a lower bound; or plus infinity (greater than every other
2241 : * point) if it's an upper bound.
2242 : *
2243 : * There is only one case where two boundaries compare equal but are not
2244 : * identical: when both bounds are inclusive and hold the same finite value,
2245 : * but one is an upper bound and the other a lower bound.
2246 : */
2247 : int
2248 11422194 : range_cmp_bounds(TypeCacheEntry *typcache, const RangeBound *b1, const RangeBound *b2)
2249 : {
2250 : int32 result;
2251 :
2252 : /*
2253 : * First, handle cases involving infinity, which don't require invoking
2254 : * the comparison proc.
2255 : */
2256 11422194 : if (b1->infinite && b2->infinite)
2257 : {
2258 : /*
2259 : * Both are infinity, so they are equal unless one is lower and the
2260 : * other not.
2261 : */
2262 19234 : if (b1->lower == b2->lower)
2263 19144 : return 0;
2264 : else
2265 90 : return b1->lower ? -1 : 1;
2266 : }
2267 11402960 : else if (b1->infinite)
2268 91016 : return b1->lower ? -1 : 1;
2269 11311944 : else if (b2->infinite)
2270 31168 : return b2->lower ? 1 : -1;
2271 :
2272 : /*
2273 : * Both boundaries are finite, so compare the held values.
2274 : */
2275 11280776 : result = DatumGetInt32(FunctionCall2Coll(&typcache->rng_cmp_proc_finfo,
2276 : typcache->rng_collation,
2277 11280776 : b1->val, b2->val));
2278 :
2279 : /*
2280 : * If the comparison is anything other than equal, we're done. If they
2281 : * compare equal though, we still have to consider whether the boundaries
2282 : * are inclusive or exclusive.
2283 : */
2284 11280776 : if (result == 0)
2285 : {
2286 814744 : if (!b1->inclusive && !b2->inclusive)
2287 : {
2288 : /* both are exclusive */
2289 363456 : if (b1->lower == b2->lower)
2290 363450 : return 0;
2291 : else
2292 6 : return b1->lower ? 1 : -1;
2293 : }
2294 451288 : else if (!b1->inclusive)
2295 792 : return b1->lower ? 1 : -1;
2296 450496 : else if (!b2->inclusive)
2297 1242 : return b2->lower ? -1 : 1;
2298 : else
2299 : {
2300 : /*
2301 : * Both are inclusive and the values held are equal, so they are
2302 : * equal regardless of whether they are upper or lower boundaries,
2303 : * or a mix.
2304 : */
2305 449254 : return 0;
2306 : }
2307 : }
2308 :
2309 10466032 : return result;
2310 : }
2311 :
2312 : /*
2313 : * Compare two range boundary point values, returning <0, 0, or >0 according
2314 : * to whether b1 is less than, equal to, or greater than b2.
2315 : *
2316 : * This is similar to but simpler than range_cmp_bounds(). We just compare
2317 : * the values held in b1 and b2, ignoring inclusive/exclusive flags. The
2318 : * lower/upper flags only matter for infinities, where they tell us if the
2319 : * infinity is plus or minus.
2320 : */
2321 : int
2322 1373080 : range_cmp_bound_values(TypeCacheEntry *typcache, const RangeBound *b1,
2323 : const RangeBound *b2)
2324 : {
2325 : /*
2326 : * First, handle cases involving infinity, which don't require invoking
2327 : * the comparison proc.
2328 : */
2329 1373080 : if (b1->infinite && b2->infinite)
2330 : {
2331 : /*
2332 : * Both are infinity, so they are equal unless one is lower and the
2333 : * other not.
2334 : */
2335 322 : if (b1->lower == b2->lower)
2336 0 : return 0;
2337 : else
2338 322 : return b1->lower ? -1 : 1;
2339 : }
2340 1372758 : else if (b1->infinite)
2341 17924 : return b1->lower ? -1 : 1;
2342 1354834 : else if (b2->infinite)
2343 14102 : return b2->lower ? 1 : -1;
2344 :
2345 : /*
2346 : * Both boundaries are finite, so compare the held values.
2347 : */
2348 1340732 : return DatumGetInt32(FunctionCall2Coll(&typcache->rng_cmp_proc_finfo,
2349 : typcache->rng_collation,
2350 1340732 : b1->val, b2->val));
2351 : }
2352 :
2353 : /*
2354 : * qsort callback for sorting ranges.
2355 : *
2356 : * Two empty ranges compare equal; an empty range sorts to the left of any
2357 : * non-empty range. Two non-empty ranges are sorted by lower bound first
2358 : * and by upper bound next.
2359 : */
2360 : int
2361 27038 : range_compare(const void *key1, const void *key2, void *arg)
2362 : {
2363 27038 : RangeType *r1 = *(RangeType **) key1;
2364 27038 : RangeType *r2 = *(RangeType **) key2;
2365 27038 : TypeCacheEntry *typcache = (TypeCacheEntry *) arg;
2366 : RangeBound lower1;
2367 : RangeBound upper1;
2368 : RangeBound lower2;
2369 : RangeBound upper2;
2370 : bool empty1;
2371 : bool empty2;
2372 : int cmp;
2373 :
2374 27038 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
2375 27038 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
2376 :
2377 27038 : if (empty1 && empty2)
2378 54 : cmp = 0;
2379 26984 : else if (empty1)
2380 42 : cmp = -1;
2381 26942 : else if (empty2)
2382 24 : cmp = 1;
2383 : else
2384 : {
2385 26918 : cmp = range_cmp_bounds(typcache, &lower1, &lower2);
2386 26918 : if (cmp == 0)
2387 48 : cmp = range_cmp_bounds(typcache, &upper1, &upper2);
2388 : }
2389 :
2390 27038 : return cmp;
2391 : }
2392 :
2393 : /*
2394 : * Build an empty range value of the type indicated by the typcache entry.
2395 : */
2396 : RangeType *
2397 3198 : make_empty_range(TypeCacheEntry *typcache)
2398 : {
2399 : RangeBound lower;
2400 : RangeBound upper;
2401 :
2402 3198 : lower.val = (Datum) 0;
2403 3198 : lower.infinite = false;
2404 3198 : lower.inclusive = false;
2405 3198 : lower.lower = true;
2406 :
2407 3198 : upper.val = (Datum) 0;
2408 3198 : upper.infinite = false;
2409 3198 : upper.inclusive = false;
2410 3198 : upper.lower = false;
2411 :
2412 3198 : return make_range(typcache, &lower, &upper, true, NULL);
2413 : }
2414 :
2415 : /*
2416 : * Planner support function for elem_contained_by_range (<@ operator).
2417 : */
2418 : Datum
2419 126 : elem_contained_by_range_support(PG_FUNCTION_ARGS)
2420 : {
2421 126 : Node *rawreq = (Node *) PG_GETARG_POINTER(0);
2422 126 : Node *ret = NULL;
2423 :
2424 126 : if (IsA(rawreq, SupportRequestSimplify))
2425 : {
2426 96 : SupportRequestSimplify *req = (SupportRequestSimplify *) rawreq;
2427 96 : FuncExpr *fexpr = req->fcall;
2428 : Expr *leftop,
2429 : *rightop;
2430 :
2431 : Assert(list_length(fexpr->args) == 2);
2432 96 : leftop = linitial(fexpr->args);
2433 96 : rightop = lsecond(fexpr->args);
2434 :
2435 96 : ret = find_simplified_clause(req->root, rightop, leftop);
2436 : }
2437 :
2438 126 : PG_RETURN_POINTER(ret);
2439 : }
2440 :
2441 : /*
2442 : * Planner support function for range_contains_elem (@> operator).
2443 : */
2444 : Datum
2445 306 : range_contains_elem_support(PG_FUNCTION_ARGS)
2446 : {
2447 306 : Node *rawreq = (Node *) PG_GETARG_POINTER(0);
2448 306 : Node *ret = NULL;
2449 :
2450 306 : if (IsA(rawreq, SupportRequestSimplify))
2451 : {
2452 156 : SupportRequestSimplify *req = (SupportRequestSimplify *) rawreq;
2453 156 : FuncExpr *fexpr = req->fcall;
2454 : Expr *leftop,
2455 : *rightop;
2456 :
2457 : Assert(list_length(fexpr->args) == 2);
2458 156 : leftop = linitial(fexpr->args);
2459 156 : rightop = lsecond(fexpr->args);
2460 :
2461 156 : ret = find_simplified_clause(req->root, leftop, rightop);
2462 : }
2463 :
2464 306 : PG_RETURN_POINTER(ret);
2465 : }
2466 :
2467 :
2468 : /*
2469 : *----------------------------------------------------------
2470 : * STATIC FUNCTIONS
2471 : *----------------------------------------------------------
2472 : */
2473 :
2474 : /*
2475 : * Given a string representing the flags for the range type, return the flags
2476 : * represented as a char.
2477 : */
2478 : static char
2479 5208 : range_parse_flags(const char *flags_str)
2480 : {
2481 5208 : char flags = 0;
2482 :
2483 5208 : if (flags_str[0] == '\0' ||
2484 5208 : flags_str[1] == '\0' ||
2485 5208 : flags_str[2] != '\0')
2486 0 : ereport(ERROR,
2487 : (errcode(ERRCODE_SYNTAX_ERROR),
2488 : errmsg("invalid range bound flags"),
2489 : errhint("Valid values are \"[]\", \"[)\", \"(]\", and \"()\".")));
2490 :
2491 5208 : switch (flags_str[0])
2492 : {
2493 264 : case '[':
2494 264 : flags |= RANGE_LB_INC;
2495 264 : break;
2496 4944 : case '(':
2497 4944 : break;
2498 0 : default:
2499 0 : ereport(ERROR,
2500 : (errcode(ERRCODE_SYNTAX_ERROR),
2501 : errmsg("invalid range bound flags"),
2502 : errhint("Valid values are \"[]\", \"[)\", \"(]\", and \"()\".")));
2503 : }
2504 :
2505 5208 : switch (flags_str[1])
2506 : {
2507 5094 : case ']':
2508 5094 : flags |= RANGE_UB_INC;
2509 5094 : break;
2510 114 : case ')':
2511 114 : break;
2512 0 : default:
2513 0 : ereport(ERROR,
2514 : (errcode(ERRCODE_SYNTAX_ERROR),
2515 : errmsg("invalid range bound flags"),
2516 : errhint("Valid values are \"[]\", \"[)\", \"(]\", and \"()\".")));
2517 : }
2518 :
2519 5208 : return flags;
2520 : }
2521 :
2522 : /*
2523 : * Parse range input.
2524 : *
2525 : * Input parameters:
2526 : * string: input string to be parsed
2527 : * Output parameters:
2528 : * *flags: receives flags bitmask
2529 : * *lbound_str: receives palloc'd lower bound string, or NULL if none
2530 : * *ubound_str: receives palloc'd upper bound string, or NULL if none
2531 : *
2532 : * This is modeled somewhat after record_in in rowtypes.c.
2533 : * The input syntax is:
2534 : * <range> := EMPTY
2535 : * | <lb-inc> <string>, <string> <ub-inc>
2536 : * <lb-inc> := '[' | '('
2537 : * <ub-inc> := ']' | ')'
2538 : *
2539 : * Whitespace before or after <range> is ignored. Whitespace within a <string>
2540 : * is taken literally and becomes part of the input string for that bound.
2541 : *
2542 : * A <string> of length zero is taken as "infinite" (i.e. no bound), unless it
2543 : * is surrounded by double-quotes, in which case it is the literal empty
2544 : * string.
2545 : *
2546 : * Within a <string>, special characters (such as comma, parenthesis, or
2547 : * brackets) can be enclosed in double-quotes or escaped with backslash. Within
2548 : * double-quotes, a double-quote can be escaped with double-quote or backslash.
2549 : *
2550 : * Returns true on success, false on failure (but failures will return only if
2551 : * escontext is an ErrorSaveContext).
2552 : */
2553 : static bool
2554 7126 : range_parse(const char *string, char *flags, char **lbound_str,
2555 : char **ubound_str, Node *escontext)
2556 : {
2557 7126 : const char *ptr = string;
2558 : bool infinite;
2559 :
2560 7126 : *flags = 0;
2561 :
2562 : /* consume whitespace */
2563 7150 : while (*ptr != '\0' && isspace((unsigned char) *ptr))
2564 24 : ptr++;
2565 :
2566 : /* check for empty range */
2567 7126 : if (pg_strncasecmp(ptr, RANGE_EMPTY_LITERAL,
2568 : strlen(RANGE_EMPTY_LITERAL)) == 0)
2569 : {
2570 600 : *flags = RANGE_EMPTY;
2571 600 : *lbound_str = NULL;
2572 600 : *ubound_str = NULL;
2573 :
2574 600 : ptr += strlen(RANGE_EMPTY_LITERAL);
2575 :
2576 : /* the rest should be whitespace */
2577 612 : while (*ptr != '\0' && isspace((unsigned char) *ptr))
2578 12 : ptr++;
2579 :
2580 : /* should have consumed everything */
2581 600 : if (*ptr != '\0')
2582 0 : ereturn(escontext, false,
2583 : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
2584 : errmsg("malformed range literal: \"%s\"",
2585 : string),
2586 : errdetail("Junk after \"empty\" key word.")));
2587 :
2588 600 : return true;
2589 : }
2590 :
2591 6526 : if (*ptr == '[')
2592 : {
2593 5826 : *flags |= RANGE_LB_INC;
2594 5826 : ptr++;
2595 : }
2596 700 : else if (*ptr == '(')
2597 676 : ptr++;
2598 : else
2599 24 : ereturn(escontext, false,
2600 : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
2601 : errmsg("malformed range literal: \"%s\"",
2602 : string),
2603 : errdetail("Missing left parenthesis or bracket.")));
2604 :
2605 6502 : ptr = range_parse_bound(string, ptr, lbound_str, &infinite, escontext);
2606 6496 : if (ptr == NULL)
2607 0 : return false;
2608 6496 : if (infinite)
2609 176 : *flags |= RANGE_LB_INF;
2610 :
2611 6496 : if (*ptr == ',')
2612 6472 : ptr++;
2613 : else
2614 24 : ereturn(escontext, false,
2615 : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
2616 : errmsg("malformed range literal: \"%s\"",
2617 : string),
2618 : errdetail("Missing comma after lower bound.")));
2619 :
2620 6472 : ptr = range_parse_bound(string, ptr, ubound_str, &infinite, escontext);
2621 6472 : if (ptr == NULL)
2622 12 : return false;
2623 6460 : if (infinite)
2624 260 : *flags |= RANGE_UB_INF;
2625 :
2626 6460 : if (*ptr == ']')
2627 : {
2628 652 : *flags |= RANGE_UB_INC;
2629 652 : ptr++;
2630 : }
2631 5808 : else if (*ptr == ')')
2632 5796 : ptr++;
2633 : else /* must be a comma */
2634 12 : ereturn(escontext, false,
2635 : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
2636 : errmsg("malformed range literal: \"%s\"",
2637 : string),
2638 : errdetail("Too many commas.")));
2639 :
2640 : /* consume whitespace */
2641 6478 : while (*ptr != '\0' && isspace((unsigned char) *ptr))
2642 30 : ptr++;
2643 :
2644 6448 : if (*ptr != '\0')
2645 18 : ereturn(escontext, false,
2646 : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
2647 : errmsg("malformed range literal: \"%s\"",
2648 : string),
2649 : errdetail("Junk after right parenthesis or bracket.")));
2650 :
2651 6430 : return true;
2652 : }
2653 :
2654 : /*
2655 : * Helper for range_parse: parse and de-quote one bound string.
2656 : *
2657 : * We scan until finding comma, right parenthesis, or right bracket.
2658 : *
2659 : * Input parameters:
2660 : * string: entire input string (used only for error reports)
2661 : * ptr: where to start parsing bound
2662 : * Output parameters:
2663 : * *bound_str: receives palloc'd bound string, or NULL if none
2664 : * *infinite: set true if no bound, else false
2665 : *
2666 : * The return value is the scan ptr, advanced past the bound string.
2667 : * However, if escontext is an ErrorSaveContext, we return NULL on failure.
2668 : */
2669 : static const char *
2670 12974 : range_parse_bound(const char *string, const char *ptr,
2671 : char **bound_str, bool *infinite, Node *escontext)
2672 : {
2673 : StringInfoData buf;
2674 :
2675 : /* Check for null: completely empty input means null */
2676 12974 : if (*ptr == ',' || *ptr == ')' || *ptr == ']')
2677 : {
2678 436 : *bound_str = NULL;
2679 436 : *infinite = true;
2680 : }
2681 : else
2682 : {
2683 : /* Extract string for this bound */
2684 12538 : bool inquote = false;
2685 :
2686 12538 : initStringInfo(&buf);
2687 41138 : while (inquote || !(*ptr == ',' || *ptr == ')' || *ptr == ']'))
2688 : {
2689 28618 : char ch = *ptr++;
2690 :
2691 28618 : if (ch == '\0')
2692 18 : ereturn(escontext, NULL,
2693 : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
2694 : errmsg("malformed range literal: \"%s\"",
2695 : string),
2696 : errdetail("Unexpected end of input.")));
2697 28600 : if (ch == '\\')
2698 : {
2699 42 : if (*ptr == '\0')
2700 0 : ereturn(escontext, NULL,
2701 : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
2702 : errmsg("malformed range literal: \"%s\"",
2703 : string),
2704 : errdetail("Unexpected end of input.")));
2705 42 : appendStringInfoChar(&buf, *ptr++);
2706 : }
2707 28558 : else if (ch == '"')
2708 : {
2709 400 : if (!inquote)
2710 200 : inquote = true;
2711 200 : else if (*ptr == '"')
2712 : {
2713 : /* doubled quote within quote sequence */
2714 6 : appendStringInfoChar(&buf, *ptr++);
2715 : }
2716 : else
2717 194 : inquote = false;
2718 : }
2719 : else
2720 28158 : appendStringInfoChar(&buf, ch);
2721 : }
2722 :
2723 12520 : *bound_str = buf.data;
2724 12520 : *infinite = false;
2725 : }
2726 :
2727 12956 : return ptr;
2728 : }
2729 :
2730 : /*
2731 : * Convert a deserialized range value to text form
2732 : *
2733 : * Inputs are the flags byte, and the two bound values already converted to
2734 : * text (but not yet quoted). If no bound value, pass NULL.
2735 : *
2736 : * Result is a palloc'd string
2737 : */
2738 : static char *
2739 108246 : range_deparse(char flags, const char *lbound_str, const char *ubound_str)
2740 : {
2741 : StringInfoData buf;
2742 :
2743 108246 : if (flags & RANGE_EMPTY)
2744 16904 : return pstrdup(RANGE_EMPTY_LITERAL);
2745 :
2746 91342 : initStringInfo(&buf);
2747 :
2748 91342 : appendStringInfoChar(&buf, (flags & RANGE_LB_INC) ? '[' : '(');
2749 :
2750 91342 : if (RANGE_HAS_LBOUND(flags))
2751 88830 : appendStringInfoString(&buf, range_bound_escape(lbound_str));
2752 :
2753 91342 : appendStringInfoChar(&buf, ',');
2754 :
2755 91342 : if (RANGE_HAS_UBOUND(flags))
2756 88692 : appendStringInfoString(&buf, range_bound_escape(ubound_str));
2757 :
2758 91342 : appendStringInfoChar(&buf, (flags & RANGE_UB_INC) ? ']' : ')');
2759 :
2760 91342 : return buf.data;
2761 : }
2762 :
2763 : /*
2764 : * Helper for range_deparse: quote a bound value as needed
2765 : *
2766 : * Result is a palloc'd string
2767 : */
2768 : static char *
2769 177522 : range_bound_escape(const char *value)
2770 : {
2771 : bool nq;
2772 : const char *ptr;
2773 : StringInfoData buf;
2774 :
2775 177522 : initStringInfo(&buf);
2776 :
2777 : /* Detect whether we need double quotes for this value */
2778 177522 : nq = (value[0] == '\0'); /* force quotes for empty string */
2779 812912 : for (ptr = value; *ptr; ptr++)
2780 : {
2781 635900 : char ch = *ptr;
2782 :
2783 635900 : if (ch == '"' || ch == '\\' ||
2784 635762 : ch == '(' || ch == ')' ||
2785 635738 : ch == '[' || ch == ']' ||
2786 635690 : ch == ',' ||
2787 635690 : isspace((unsigned char) ch))
2788 : {
2789 510 : nq = true;
2790 510 : break;
2791 : }
2792 : }
2793 :
2794 : /* And emit the string */
2795 177522 : if (nq)
2796 534 : appendStringInfoChar(&buf, '"');
2797 817106 : for (ptr = value; *ptr; ptr++)
2798 : {
2799 639584 : char ch = *ptr;
2800 :
2801 639584 : if (ch == '"' || ch == '\\')
2802 120 : appendStringInfoChar(&buf, ch);
2803 639584 : appendStringInfoChar(&buf, ch);
2804 : }
2805 177522 : if (nq)
2806 534 : appendStringInfoChar(&buf, '"');
2807 :
2808 177522 : return buf.data;
2809 : }
2810 :
2811 : /*
2812 : * Test whether range r1 contains range r2.
2813 : *
2814 : * Caller has already checked that they are the same range type, and looked up
2815 : * the necessary typcache entry.
2816 : */
2817 : bool
2818 481614 : range_contains_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
2819 : {
2820 : RangeBound lower1;
2821 : RangeBound upper1;
2822 : bool empty1;
2823 : RangeBound lower2;
2824 : RangeBound upper2;
2825 : bool empty2;
2826 :
2827 : /* Different types should be prevented by ANYRANGE matching rules */
2828 481614 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
2829 0 : elog(ERROR, "range types do not match");
2830 :
2831 481614 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
2832 481614 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
2833 :
2834 : /* If either range is empty, the answer is easy */
2835 481614 : if (empty2)
2836 314712 : return true;
2837 166902 : else if (empty1)
2838 13566 : return false;
2839 :
2840 : /* Else we must have lower1 <= lower2 and upper1 >= upper2 */
2841 153336 : if (range_cmp_bounds(typcache, &lower1, &lower2) > 0)
2842 73522 : return false;
2843 79814 : if (range_cmp_bounds(typcache, &upper1, &upper2) < 0)
2844 71556 : return false;
2845 :
2846 8258 : return true;
2847 : }
2848 :
2849 : bool
2850 120960 : range_contained_by_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
2851 : {
2852 120960 : return range_contains_internal(typcache, r2, r1);
2853 : }
2854 :
2855 : /*
2856 : * Test whether range r contains a specific element value.
2857 : */
2858 : bool
2859 88380 : range_contains_elem_internal(TypeCacheEntry *typcache, const RangeType *r, Datum val)
2860 : {
2861 : RangeBound lower;
2862 : RangeBound upper;
2863 : bool empty;
2864 : int32 cmp;
2865 :
2866 88380 : range_deserialize(typcache, r, &lower, &upper, &empty);
2867 :
2868 88380 : if (empty)
2869 12864 : return false;
2870 :
2871 75516 : if (!lower.infinite)
2872 : {
2873 71262 : cmp = DatumGetInt32(FunctionCall2Coll(&typcache->rng_cmp_proc_finfo,
2874 : typcache->rng_collation,
2875 : lower.val, val));
2876 71262 : if (cmp > 0)
2877 68914 : return false;
2878 2348 : if (cmp == 0 && !lower.inclusive)
2879 0 : return false;
2880 : }
2881 :
2882 6602 : if (!upper.infinite)
2883 : {
2884 6526 : cmp = DatumGetInt32(FunctionCall2Coll(&typcache->rng_cmp_proc_finfo,
2885 : typcache->rng_collation,
2886 : upper.val, val));
2887 6526 : if (cmp < 0)
2888 480 : return false;
2889 6046 : if (cmp == 0 && !upper.inclusive)
2890 0 : return false;
2891 : }
2892 :
2893 6122 : return true;
2894 : }
2895 :
2896 :
2897 : /*
2898 : * datum_compute_size() and datum_write() are used to insert the bound
2899 : * values into a range object. They are modeled after heaptuple.c's
2900 : * heap_compute_data_size() and heap_fill_tuple(), but we need not handle
2901 : * null values here. TYPE_IS_PACKABLE must test the same conditions as
2902 : * heaptuple.c's ATT_IS_PACKABLE macro. See the comments there for more
2903 : * details.
2904 : */
2905 :
2906 : /* Does datatype allow packing into the 1-byte-header varlena format? */
2907 : #define TYPE_IS_PACKABLE(typlen, typstorage) \
2908 : ((typlen) == -1 && (typstorage) != TYPSTORAGE_PLAIN)
2909 :
2910 : /*
2911 : * Increment data_length by the space needed by the datum, including any
2912 : * preceding alignment padding.
2913 : */
2914 : static Size
2915 1788128 : datum_compute_size(Size data_length, Datum val, bool typbyval, char typalign,
2916 : int16 typlen, char typstorage)
2917 : {
2918 1798554 : if (TYPE_IS_PACKABLE(typlen, typstorage) &&
2919 10426 : VARATT_CAN_MAKE_SHORT(DatumGetPointer(val)))
2920 : {
2921 : /*
2922 : * we're anticipating converting to a short varlena header, so adjust
2923 : * length and don't count any alignment
2924 : */
2925 9304 : data_length += VARATT_CONVERTED_SHORT_SIZE(DatumGetPointer(val));
2926 : }
2927 : else
2928 : {
2929 1778824 : data_length = att_align_datum(data_length, typalign, typlen, val);
2930 1778824 : data_length = att_addlength_datum(data_length, typlen, val);
2931 : }
2932 :
2933 1788128 : return data_length;
2934 : }
2935 :
2936 : /*
2937 : * Write the given datum beginning at ptr (after advancing to correct
2938 : * alignment, if needed). Return the pointer incremented by space used.
2939 : */
2940 : static Pointer
2941 1788128 : datum_write(Pointer ptr, Datum datum, bool typbyval, char typalign,
2942 : int16 typlen, char typstorage)
2943 : {
2944 : Size data_length;
2945 :
2946 1788128 : if (typbyval)
2947 : {
2948 : /* pass-by-value */
2949 1777702 : ptr = (char *) att_align_nominal(ptr, typalign);
2950 1777702 : store_att_byval(ptr, datum, typlen);
2951 1777702 : data_length = typlen;
2952 : }
2953 10426 : else if (typlen == -1)
2954 : {
2955 : /* varlena */
2956 10426 : Pointer val = DatumGetPointer(datum);
2957 :
2958 10426 : if (VARATT_IS_EXTERNAL(val))
2959 : {
2960 : /*
2961 : * Throw error, because we must never put a toast pointer inside a
2962 : * range object. Caller should have detoasted it.
2963 : */
2964 0 : elog(ERROR, "cannot store a toast pointer inside a range");
2965 : data_length = 0; /* keep compiler quiet */
2966 : }
2967 10426 : else if (VARATT_IS_SHORT(val))
2968 : {
2969 : /* no alignment for short varlenas */
2970 1086 : data_length = VARSIZE_SHORT(val);
2971 1086 : memcpy(ptr, val, data_length);
2972 : }
2973 18680 : else if (TYPE_IS_PACKABLE(typlen, typstorage) &&
2974 9340 : VARATT_CAN_MAKE_SHORT(val))
2975 : {
2976 : /* convert to short varlena -- no alignment */
2977 9304 : data_length = VARATT_CONVERTED_SHORT_SIZE(val);
2978 9304 : SET_VARSIZE_SHORT(ptr, data_length);
2979 9304 : memcpy(ptr + 1, VARDATA(val), data_length - 1);
2980 : }
2981 : else
2982 : {
2983 : /* full 4-byte header varlena */
2984 36 : ptr = (char *) att_align_nominal(ptr, typalign);
2985 36 : data_length = VARSIZE(val);
2986 36 : memcpy(ptr, val, data_length);
2987 : }
2988 : }
2989 0 : else if (typlen == -2)
2990 : {
2991 : /* cstring ... never needs alignment */
2992 : Assert(typalign == TYPALIGN_CHAR);
2993 0 : data_length = strlen(DatumGetCString(datum)) + 1;
2994 0 : memcpy(ptr, DatumGetPointer(datum), data_length);
2995 : }
2996 : else
2997 : {
2998 : /* fixed-length pass-by-reference */
2999 0 : ptr = (char *) att_align_nominal(ptr, typalign);
3000 : Assert(typlen > 0);
3001 0 : data_length = typlen;
3002 0 : memcpy(ptr, DatumGetPointer(datum), data_length);
3003 : }
3004 :
3005 1788128 : ptr += data_length;
3006 :
3007 1788128 : return ptr;
3008 : }
3009 :
3010 : /*
3011 : * Common code for the elem_contained_by_range and range_contains_elem
3012 : * support functions. The caller has extracted the function argument
3013 : * expressions, and swapped them if necessary to pass the range first.
3014 : *
3015 : * Returns a simplified replacement expression, or NULL if we can't simplify.
3016 : */
3017 : static Node *
3018 252 : find_simplified_clause(PlannerInfo *root, Expr *rangeExpr, Expr *elemExpr)
3019 : {
3020 : RangeType *range;
3021 : TypeCacheEntry *rangetypcache;
3022 : RangeBound lower;
3023 : RangeBound upper;
3024 : bool empty;
3025 :
3026 : /* can't do anything unless the range is a non-null constant */
3027 252 : if (!IsA(rangeExpr, Const) || ((Const *) rangeExpr)->constisnull)
3028 156 : return NULL;
3029 96 : range = DatumGetRangeTypeP(((Const *) rangeExpr)->constvalue);
3030 :
3031 96 : rangetypcache = lookup_type_cache(RangeTypeGetOid(range),
3032 : TYPECACHE_RANGE_INFO);
3033 96 : if (rangetypcache->rngelemtype == NULL)
3034 0 : elog(ERROR, "type %u is not a range type", RangeTypeGetOid(range));
3035 :
3036 96 : range_deserialize(rangetypcache, range, &lower, &upper, &empty);
3037 :
3038 96 : if (empty)
3039 : {
3040 : /* if the range is empty, then there can be no matches */
3041 6 : return makeBoolConst(false, false);
3042 : }
3043 90 : else if (lower.infinite && upper.infinite)
3044 : {
3045 : /* the range has infinite bounds, so it matches everything */
3046 6 : return makeBoolConst(true, false);
3047 : }
3048 : else
3049 : {
3050 : /* at least one bound is available, we have something to work with */
3051 84 : TypeCacheEntry *elemTypcache = rangetypcache->rngelemtype;
3052 84 : Oid opfamily = rangetypcache->rng_opfamily;
3053 84 : Oid rng_collation = rangetypcache->rng_collation;
3054 84 : Expr *lowerExpr = NULL;
3055 84 : Expr *upperExpr = NULL;
3056 :
3057 84 : if (!lower.infinite && !upper.infinite)
3058 : {
3059 : /*
3060 : * When both bounds are present, we have a problem: the
3061 : * "simplified" clause would need to evaluate the elemExpr twice.
3062 : * That's definitely not okay if the elemExpr is volatile, and
3063 : * it's also unattractive if the elemExpr is expensive.
3064 : */
3065 : QualCost eval_cost;
3066 :
3067 66 : if (contain_volatile_functions((Node *) elemExpr))
3068 6 : return NULL;
3069 :
3070 : /*
3071 : * We define "expensive" as "contains any subplan or more than 10
3072 : * operators". Note that the subplan search has to be done
3073 : * explicitly, since cost_qual_eval() will barf on unplanned
3074 : * subselects.
3075 : */
3076 60 : if (contain_subplans((Node *) elemExpr))
3077 0 : return NULL;
3078 60 : cost_qual_eval_node(&eval_cost, (Node *) elemExpr, root);
3079 60 : if (eval_cost.startup + eval_cost.per_tuple >
3080 60 : 10 * cpu_operator_cost)
3081 0 : return NULL;
3082 : }
3083 :
3084 : /* Okay, try to build boundary comparison expressions */
3085 78 : if (!lower.infinite)
3086 : {
3087 72 : lowerExpr = build_bound_expr(elemExpr,
3088 : lower.val,
3089 : true,
3090 72 : lower.inclusive,
3091 : elemTypcache,
3092 : opfamily,
3093 : rng_collation);
3094 72 : if (lowerExpr == NULL)
3095 0 : return NULL;
3096 : }
3097 :
3098 78 : if (!upper.infinite)
3099 : {
3100 : /* Copy the elemExpr if we need two copies */
3101 66 : if (!lower.infinite)
3102 60 : elemExpr = copyObject(elemExpr);
3103 66 : upperExpr = build_bound_expr(elemExpr,
3104 : upper.val,
3105 : false,
3106 66 : upper.inclusive,
3107 : elemTypcache,
3108 : opfamily,
3109 : rng_collation);
3110 66 : if (upperExpr == NULL)
3111 0 : return NULL;
3112 : }
3113 :
3114 78 : if (lowerExpr != NULL && upperExpr != NULL)
3115 60 : return (Node *) make_andclause(list_make2(lowerExpr, upperExpr));
3116 18 : else if (lowerExpr != NULL)
3117 12 : return (Node *) lowerExpr;
3118 6 : else if (upperExpr != NULL)
3119 6 : return (Node *) upperExpr;
3120 : else
3121 : {
3122 : Assert(false);
3123 0 : return NULL;
3124 : }
3125 : }
3126 : }
3127 :
3128 : /*
3129 : * Helper function for find_simplified_clause().
3130 : *
3131 : * Build the expression (elemExpr Operator val), where the operator is
3132 : * the appropriate member of the given opfamily depending on
3133 : * isLowerBound and isInclusive. typeCache is the typcache entry for
3134 : * the "val" value (presently, this will be the same type as elemExpr).
3135 : * rng_collation is the collation to use in the comparison.
3136 : *
3137 : * Return NULL on failure (if, for some reason, we can't find the operator).
3138 : */
3139 : static Expr *
3140 138 : build_bound_expr(Expr *elemExpr, Datum val,
3141 : bool isLowerBound, bool isInclusive,
3142 : TypeCacheEntry *typeCache,
3143 : Oid opfamily, Oid rng_collation)
3144 : {
3145 138 : Oid elemType = typeCache->type_id;
3146 138 : int16 elemTypeLen = typeCache->typlen;
3147 138 : bool elemByValue = typeCache->typbyval;
3148 138 : Oid elemCollation = typeCache->typcollation;
3149 : int16 strategy;
3150 : Oid oproid;
3151 : Expr *constExpr;
3152 :
3153 : /* Identify the comparison operator to use */
3154 138 : if (isLowerBound)
3155 72 : strategy = isInclusive ? BTGreaterEqualStrategyNumber : BTGreaterStrategyNumber;
3156 : else
3157 66 : strategy = isInclusive ? BTLessEqualStrategyNumber : BTLessStrategyNumber;
3158 :
3159 : /*
3160 : * We could use exprType(elemExpr) here, if it ever becomes possible that
3161 : * elemExpr is not the exact same type as the range elements.
3162 : */
3163 138 : oproid = get_opfamily_member(opfamily, elemType, elemType, strategy);
3164 :
3165 : /* We don't really expect failure here, but just in case ... */
3166 138 : if (!OidIsValid(oproid))
3167 0 : return NULL;
3168 :
3169 : /* OK, convert "val" to a full-fledged Const node, and make the OpExpr */
3170 138 : constExpr = (Expr *) makeConst(elemType,
3171 : -1,
3172 : elemCollation,
3173 : elemTypeLen,
3174 : val,
3175 : false,
3176 : elemByValue);
3177 :
3178 138 : return make_opclause(oproid,
3179 : BOOLOID,
3180 : false,
3181 : elemExpr,
3182 : constExpr,
3183 : InvalidOid,
3184 : rng_collation);
3185 : }
|