Branch data 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-2026, 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 char *datum_write(char *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 : 1008 : range_in(PG_FUNCTION_ARGS)
93 : : {
94 : 1008 : char *input_str = PG_GETARG_CSTRING(0);
95 : 1008 : Oid rngtypoid = PG_GETARG_OID(1);
96 : 1008 : Oid typmod = PG_GETARG_INT32(2);
97 : 1008 : Node *escontext = fcinfo->context;
98 : 1008 : RangeType *range;
99 : 1008 : RangeIOData *cache;
100 : 1008 : char flags;
101 : 1008 : char *lbound_str;
102 : 1008 : char *ubound_str;
103 : 1008 : RangeBound lower;
104 : 1008 : RangeBound upper;
105 : :
106 : 1008 : check_stack_depth(); /* recurses when subtype is a range type */
107 : :
108 : 1008 : cache = get_range_io_data(fcinfo, rngtypoid, IOFunc_input);
109 : :
110 : : /* parse */
111 [ + + ]: 1008 : if (!range_parse(input_str, &flags, &lbound_str, &ubound_str, escontext))
112 : 3 : PG_RETURN_NULL();
113 : :
114 : : /* call element type's input function */
115 [ + + ]: 1005 : if (RANGE_HAS_LBOUND(flags))
116 [ + - + - ]: 1768 : if (!InputFunctionCallSafe(&cache->typioproc, lbound_str,
117 : 884 : cache->typioparam, typmod,
118 : 884 : escontext, &lower.val))
119 : 0 : PG_RETURN_NULL();
120 [ + + ]: 1005 : if (RANGE_HAS_UBOUND(flags))
121 [ + + + + ]: 1736 : if (!InputFunctionCallSafe(&cache->typioproc, ubound_str,
122 : 868 : cache->typioparam, typmod,
123 : 868 : escontext, &upper.val))
124 : 4 : PG_RETURN_NULL();
125 : :
126 : 1001 : lower.infinite = (flags & RANGE_LB_INF) != 0;
127 : 1001 : lower.inclusive = (flags & RANGE_LB_INC) != 0;
128 : 1001 : lower.lower = true;
129 : 1001 : upper.infinite = (flags & RANGE_UB_INF) != 0;
130 : 1001 : upper.inclusive = (flags & RANGE_UB_INC) != 0;
131 : 1001 : upper.lower = false;
132 : :
133 : : /* serialize and canonicalize */
134 : 2002 : range = make_range(cache->typcache, &lower, &upper,
135 : 1001 : flags & RANGE_EMPTY, escontext);
136 : :
137 : 1001 : PG_RETURN_RANGE_P(range);
138 : 1008 : }
139 : :
140 : : Datum
141 : 951 : range_out(PG_FUNCTION_ARGS)
142 : : {
143 : 951 : RangeType *range = PG_GETARG_RANGE_P(0);
144 : 951 : char *output_str;
145 : 951 : RangeIOData *cache;
146 : 951 : char flags;
147 : 951 : char *lbound_str = NULL;
148 : 951 : char *ubound_str = NULL;
149 : 951 : RangeBound lower;
150 : 951 : RangeBound upper;
151 : 951 : bool empty;
152 : :
153 : 951 : check_stack_depth(); /* recurses when subtype is a range type */
154 : :
155 : 951 : cache = get_range_io_data(fcinfo, RangeTypeGetOid(range), IOFunc_output);
156 : :
157 : : /* deserialize */
158 : 951 : range_deserialize(cache->typcache, range, &lower, &upper, &empty);
159 : 951 : flags = range_get_flags(range);
160 : :
161 : : /* call element type's output function */
162 [ + + ]: 951 : if (RANGE_HAS_LBOUND(flags))
163 : 774 : lbound_str = OutputFunctionCall(&cache->typioproc, lower.val);
164 [ + + ]: 951 : if (RANGE_HAS_UBOUND(flags))
165 : 751 : ubound_str = OutputFunctionCall(&cache->typioproc, upper.val);
166 : :
167 : : /* construct result string */
168 : 951 : output_str = range_deparse(flags, lbound_str, ubound_str);
169 : :
170 : 1902 : PG_RETURN_CSTRING(output_str);
171 : 951 : }
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 : 0 : RangeType *range;
187 : 0 : RangeIOData *cache;
188 : 0 : char flags;
189 : 0 : RangeBound lower;
190 : 0 : 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 : 0 : 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 : 0 : cache->typioparam,
223 : 0 : typmod);
224 : 0 : pfree(bound_buf.data);
225 : 0 : }
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 : 0 : 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 : 0 : cache->typioparam,
241 : 0 : typmod);
242 : 0 : pfree(bound_buf.data);
243 : 0 : }
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 : 0 : }
263 : :
264 : : Datum
265 : 0 : range_send(PG_FUNCTION_ARGS)
266 : : {
267 : 0 : RangeType *range = PG_GETARG_RANGE_P(0);
268 : 0 : StringInfoData buf;
269 : 0 : RangeIOData *cache;
270 : 0 : char flags;
271 : 0 : RangeBound lower;
272 : 0 : RangeBound upper;
273 : 0 : 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 : 0 : }
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 : 0 : }
309 : :
310 : 0 : PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
311 : 0 : }
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 : 1972 : get_range_io_data(FunctionCallInfo fcinfo, Oid rngtypid, IOFuncSelector func)
322 : : {
323 : 1972 : RangeIOData *cache = (RangeIOData *) fcinfo->flinfo->fn_extra;
324 : :
325 [ + + + - ]: 1972 : if (cache == NULL || cache->typcache->type_id != rngtypid)
326 : : {
327 : 1483 : int16 typlen;
328 : 1483 : bool typbyval;
329 : 1483 : char typalign;
330 : 1483 : char typdelim;
331 : 1483 : Oid typiofunc;
332 : :
333 : 1483 : cache = (RangeIOData *) MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
334 : : sizeof(RangeIOData));
335 : 1483 : cache->typcache = lookup_type_cache(rngtypid, TYPECACHE_RANGE_INFO);
336 [ + - ]: 1483 : 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 : 2966 : get_type_io_data(cache->typcache->rngelemtype->type_id,
341 : 1483 : func,
342 : : &typlen,
343 : : &typbyval,
344 : : &typalign,
345 : : &typdelim,
346 : 1483 : &cache->typioparam,
347 : : &typiofunc);
348 : :
349 [ + - ]: 1483 : 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 : 0 : }
363 : 2966 : fmgr_info_cxt(typiofunc, &cache->typioproc,
364 : 1483 : fcinfo->flinfo->fn_mcxt);
365 : :
366 : 1483 : fcinfo->flinfo->fn_extra = cache;
367 : 1483 : }
368 : :
369 : 3944 : return cache;
370 : 1972 : }
371 : :
372 : :
373 : : /*
374 : : *----------------------------------------------------------
375 : : * GENERIC FUNCTIONS
376 : : *----------------------------------------------------------
377 : : */
378 : :
379 : : /* Construct standard-form range value from two arguments */
380 : : Datum
381 : 18309 : range_constructor2(PG_FUNCTION_ARGS)
382 : : {
383 : 18309 : Datum arg1 = PG_GETARG_DATUM(0);
384 : 18309 : Datum arg2 = PG_GETARG_DATUM(1);
385 : 18309 : Oid rngtypid = get_fn_expr_rettype(fcinfo->flinfo);
386 : 18309 : RangeType *range;
387 : 18309 : TypeCacheEntry *typcache;
388 : 18309 : RangeBound lower;
389 : 18309 : RangeBound upper;
390 : :
391 : 18309 : typcache = range_get_typcache(fcinfo, rngtypid);
392 : :
393 [ + + ]: 18309 : lower.val = PG_ARGISNULL(0) ? (Datum) 0 : arg1;
394 : 18309 : lower.infinite = PG_ARGISNULL(0);
395 : 18309 : lower.inclusive = true;
396 : 18309 : lower.lower = true;
397 : :
398 [ + + ]: 18309 : upper.val = PG_ARGISNULL(1) ? (Datum) 0 : arg2;
399 : 18309 : upper.infinite = PG_ARGISNULL(1);
400 : 18309 : upper.inclusive = false;
401 : 18309 : upper.lower = false;
402 : :
403 : 18309 : range = make_range(typcache, &lower, &upper, false, NULL);
404 : :
405 : 36618 : PG_RETURN_RANGE_P(range);
406 : 18309 : }
407 : :
408 : : /* Construct general range value from three arguments */
409 : : Datum
410 : 868 : range_constructor3(PG_FUNCTION_ARGS)
411 : : {
412 : 868 : Datum arg1 = PG_GETARG_DATUM(0);
413 : 868 : Datum arg2 = PG_GETARG_DATUM(1);
414 : 868 : Oid rngtypid = get_fn_expr_rettype(fcinfo->flinfo);
415 : 868 : RangeType *range;
416 : 868 : TypeCacheEntry *typcache;
417 : 868 : RangeBound lower;
418 : 868 : RangeBound upper;
419 : 868 : char flags;
420 : :
421 : 868 : typcache = range_get_typcache(fcinfo, rngtypid);
422 : :
423 [ + - ]: 868 : 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 : 868 : flags = range_parse_flags(text_to_cstring(PG_GETARG_TEXT_PP(2)));
429 : :
430 [ + + ]: 868 : lower.val = PG_ARGISNULL(0) ? (Datum) 0 : arg1;
431 : 868 : lower.infinite = PG_ARGISNULL(0);
432 : 868 : lower.inclusive = (flags & RANGE_LB_INC) != 0;
433 : 868 : lower.lower = true;
434 : :
435 [ + + ]: 868 : upper.val = PG_ARGISNULL(1) ? (Datum) 0 : arg2;
436 : 868 : upper.infinite = PG_ARGISNULL(1);
437 : 868 : upper.inclusive = (flags & RANGE_UB_INC) != 0;
438 : 868 : upper.lower = false;
439 : :
440 : 868 : range = make_range(typcache, &lower, &upper, false, NULL);
441 : :
442 : 1736 : PG_RETURN_RANGE_P(range);
443 : 868 : }
444 : :
445 : :
446 : : /* range -> subtype functions */
447 : :
448 : : /* extract lower bound value */
449 : : Datum
450 : 51 : range_lower(PG_FUNCTION_ARGS)
451 : : {
452 : 51 : RangeType *r1 = PG_GETARG_RANGE_P(0);
453 : 51 : TypeCacheEntry *typcache;
454 : 51 : RangeBound lower;
455 : 51 : RangeBound upper;
456 : 51 : bool empty;
457 : :
458 : 51 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
459 : :
460 : 51 : range_deserialize(typcache, r1, &lower, &upper, &empty);
461 : :
462 : : /* Return NULL if there's no finite lower bound */
463 [ + + + + ]: 51 : if (empty || lower.infinite)
464 : 6 : PG_RETURN_NULL();
465 : :
466 : 45 : PG_RETURN_DATUM(lower.val);
467 : 51 : }
468 : :
469 : : /* extract upper bound value */
470 : : Datum
471 : 38 : range_upper(PG_FUNCTION_ARGS)
472 : : {
473 : 38 : RangeType *r1 = PG_GETARG_RANGE_P(0);
474 : 38 : TypeCacheEntry *typcache;
475 : 38 : RangeBound lower;
476 : 38 : RangeBound upper;
477 : 38 : bool empty;
478 : :
479 : 38 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
480 : :
481 : 38 : range_deserialize(typcache, r1, &lower, &upper, &empty);
482 : :
483 : : /* Return NULL if there's no finite upper bound */
484 [ + + + + ]: 38 : if (empty || upper.infinite)
485 : 6 : PG_RETURN_NULL();
486 : :
487 : 32 : PG_RETURN_DATUM(upper.val);
488 : 38 : }
489 : :
490 : :
491 : : /* range -> bool functions */
492 : :
493 : : /* is range empty? */
494 : : Datum
495 : 366 : range_empty(PG_FUNCTION_ARGS)
496 : : {
497 : 366 : RangeType *r1 = PG_GETARG_RANGE_P(0);
498 : 366 : char flags = range_get_flags(r1);
499 : :
500 : 732 : PG_RETURN_BOOL(flags & RANGE_EMPTY);
501 : 366 : }
502 : :
503 : : /* is lower bound inclusive? */
504 : : Datum
505 : 12 : range_lower_inc(PG_FUNCTION_ARGS)
506 : : {
507 : 12 : RangeType *r1 = PG_GETARG_RANGE_P(0);
508 : 12 : char flags = range_get_flags(r1);
509 : :
510 : 24 : PG_RETURN_BOOL(flags & RANGE_LB_INC);
511 : 12 : }
512 : :
513 : : /* is upper bound inclusive? */
514 : : Datum
515 : 12 : range_upper_inc(PG_FUNCTION_ARGS)
516 : : {
517 : 12 : RangeType *r1 = PG_GETARG_RANGE_P(0);
518 : 12 : char flags = range_get_flags(r1);
519 : :
520 : 24 : PG_RETURN_BOOL(flags & RANGE_UB_INC);
521 : 12 : }
522 : :
523 : : /* is lower bound infinite? */
524 : : Datum
525 : 12 : range_lower_inf(PG_FUNCTION_ARGS)
526 : : {
527 : 12 : RangeType *r1 = PG_GETARG_RANGE_P(0);
528 : 12 : char flags = range_get_flags(r1);
529 : :
530 : 24 : PG_RETURN_BOOL(flags & RANGE_LB_INF);
531 : 12 : }
532 : :
533 : : /* is upper bound infinite? */
534 : : Datum
535 : 12 : range_upper_inf(PG_FUNCTION_ARGS)
536 : : {
537 : 12 : RangeType *r1 = PG_GETARG_RANGE_P(0);
538 : 12 : char flags = range_get_flags(r1);
539 : :
540 : 24 : PG_RETURN_BOOL(flags & RANGE_UB_INF);
541 : 12 : }
542 : :
543 : :
544 : : /* range, element -> bool functions */
545 : :
546 : : /* contains? */
547 : : Datum
548 : 12700 : range_contains_elem(PG_FUNCTION_ARGS)
549 : : {
550 : 12700 : RangeType *r = PG_GETARG_RANGE_P(0);
551 : 12700 : Datum val = PG_GETARG_DATUM(1);
552 : 12700 : TypeCacheEntry *typcache;
553 : :
554 : 12700 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
555 : :
556 : 25400 : PG_RETURN_BOOL(range_contains_elem_internal(typcache, r, val));
557 : 12700 : }
558 : :
559 : : /* contained by? */
560 : : Datum
561 : 14 : elem_contained_by_range(PG_FUNCTION_ARGS)
562 : : {
563 : 14 : Datum val = PG_GETARG_DATUM(0);
564 : 14 : RangeType *r = PG_GETARG_RANGE_P(1);
565 : 14 : TypeCacheEntry *typcache;
566 : :
567 : 14 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
568 : :
569 : 28 : PG_RETURN_BOOL(range_contains_elem_internal(typcache, r, val));
570 : 14 : }
571 : :
572 : :
573 : : /* range, range -> bool functions */
574 : :
575 : : /* equality (internal version) */
576 : : bool
577 : 26369 : range_eq_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
578 : : {
579 : 26369 : RangeBound lower1,
580 : : lower2;
581 : 26369 : RangeBound upper1,
582 : : upper2;
583 : 26369 : bool empty1,
584 : : empty2;
585 : :
586 : : /* Different types should be prevented by ANYRANGE matching rules */
587 [ + - ]: 26369 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
588 [ # # # # ]: 0 : elog(ERROR, "range types do not match");
589 : :
590 : 26369 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
591 : 26369 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
592 : :
593 [ + + + + ]: 26369 : if (empty1 && empty2)
594 : 1261 : return true;
595 [ + + ]: 25108 : if (empty1 != empty2)
596 : 2252 : return false;
597 : :
598 [ + + ]: 22856 : if (range_cmp_bounds(typcache, &lower1, &lower2) != 0)
599 : 13407 : return false;
600 : :
601 [ + + ]: 9449 : if (range_cmp_bounds(typcache, &upper1, &upper2) != 0)
602 : 5598 : return false;
603 : :
604 : 3851 : return true;
605 : 26369 : }
606 : :
607 : : /* equality */
608 : : Datum
609 : 13196 : range_eq(PG_FUNCTION_ARGS)
610 : : {
611 : 13196 : RangeType *r1 = PG_GETARG_RANGE_P(0);
612 : 13196 : RangeType *r2 = PG_GETARG_RANGE_P(1);
613 : 13196 : TypeCacheEntry *typcache;
614 : :
615 : 13196 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
616 : :
617 : 26392 : PG_RETURN_BOOL(range_eq_internal(typcache, r1, r2));
618 : 13196 : }
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 : 0 : 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 : 0 : }
639 : :
640 : : /* contains? */
641 : : Datum
642 : 25745 : range_contains(PG_FUNCTION_ARGS)
643 : : {
644 : 25745 : RangeType *r1 = PG_GETARG_RANGE_P(0);
645 : 25745 : RangeType *r2 = PG_GETARG_RANGE_P(1);
646 : 25745 : TypeCacheEntry *typcache;
647 : :
648 : 25745 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
649 : :
650 : 51490 : PG_RETURN_BOOL(range_contains_internal(typcache, r1, r2));
651 : 25745 : }
652 : :
653 : : /* contained by? */
654 : : Datum
655 : 12822 : range_contained_by(PG_FUNCTION_ARGS)
656 : : {
657 : 12822 : RangeType *r1 = PG_GETARG_RANGE_P(0);
658 : 12822 : RangeType *r2 = PG_GETARG_RANGE_P(1);
659 : 12822 : TypeCacheEntry *typcache;
660 : :
661 : 12822 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
662 : :
663 : 25644 : PG_RETURN_BOOL(range_contained_by_internal(typcache, r1, r2));
664 : 12822 : }
665 : :
666 : : /* strictly left of? (internal version) */
667 : : bool
668 : 20381 : range_before_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
669 : : {
670 : 20381 : RangeBound lower1,
671 : : lower2;
672 : 20381 : RangeBound upper1,
673 : : upper2;
674 : 20381 : bool empty1,
675 : : empty2;
676 : :
677 : : /* Different types should be prevented by ANYRANGE matching rules */
678 [ + - ]: 20381 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
679 [ # # # # ]: 0 : elog(ERROR, "range types do not match");
680 : :
681 : 20381 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
682 : 20381 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
683 : :
684 : : /* An empty range is neither before nor after any other range */
685 [ + + + + ]: 20381 : if (empty1 || empty2)
686 : 2485 : return false;
687 : :
688 : 17896 : return (range_cmp_bounds(typcache, &upper1, &lower2) < 0);
689 : 20381 : }
690 : :
691 : : /* strictly left of? */
692 : : Datum
693 : 13153 : range_before(PG_FUNCTION_ARGS)
694 : : {
695 : 13153 : RangeType *r1 = PG_GETARG_RANGE_P(0);
696 : 13153 : RangeType *r2 = PG_GETARG_RANGE_P(1);
697 : 13153 : TypeCacheEntry *typcache;
698 : :
699 : 13153 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
700 : :
701 : 26306 : PG_RETURN_BOOL(range_before_internal(typcache, r1, r2));
702 : 13153 : }
703 : :
704 : : /* strictly right of? (internal version) */
705 : : bool
706 : 32943 : range_after_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
707 : : {
708 : 32943 : RangeBound lower1,
709 : : lower2;
710 : 32943 : RangeBound upper1,
711 : : upper2;
712 : 32943 : bool empty1,
713 : : empty2;
714 : :
715 : : /* Different types should be prevented by ANYRANGE matching rules */
716 [ + - ]: 32943 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
717 [ # # # # ]: 0 : elog(ERROR, "range types do not match");
718 : :
719 : 32943 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
720 : 32943 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
721 : :
722 : : /* An empty range is neither before nor after any other range */
723 [ + + + + ]: 32943 : if (empty1 || empty2)
724 : 2385 : return false;
725 : :
726 : 30558 : return (range_cmp_bounds(typcache, &lower1, &upper2) > 0);
727 : 32943 : }
728 : :
729 : : /* strictly right of? */
730 : : Datum
731 : 13051 : range_after(PG_FUNCTION_ARGS)
732 : : {
733 : 13051 : RangeType *r1 = PG_GETARG_RANGE_P(0);
734 : 13051 : RangeType *r2 = PG_GETARG_RANGE_P(1);
735 : 13051 : TypeCacheEntry *typcache;
736 : :
737 : 13051 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
738 : :
739 : 26102 : PG_RETURN_BOOL(range_after_internal(typcache, r1, r2));
740 : 13051 : }
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 : 78872 : bounds_adjacent(TypeCacheEntry *typcache, RangeBound boundA, RangeBound boundB)
762 : : {
763 : 78872 : int cmp;
764 : :
765 [ + - ]: 78872 : Assert(!boundA.lower && boundB.lower);
766 : :
767 : 78872 : cmp = range_cmp_bound_values(typcache, &boundA, &boundB);
768 [ + + ]: 78872 : if (cmp < 0)
769 : : {
770 : 24216 : 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 [ + + ]: 24216 : if (!OidIsValid(typcache->rng_canonical_finfo.fn_oid))
778 : 154 : 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 : 24062 : boundA.inclusive = !boundA.inclusive;
787 : 24062 : boundB.inclusive = !boundB.inclusive;
788 : : /* change upper/lower labels to avoid Assert failures */
789 : 24062 : boundA.lower = true;
790 : 24062 : boundB.lower = false;
791 : 24062 : r = make_range(typcache, &boundA, &boundB, false, NULL);
792 : 24062 : return RangeIsEmpty(r);
793 : 24216 : }
794 [ + + ]: 54656 : else if (cmp == 0)
795 : 315 : return boundA.inclusive != boundB.inclusive;
796 : : else
797 : 54341 : return false; /* bounds overlap */
798 : 78872 : }
799 : :
800 : : /* adjacent to (but not overlapping)? (internal version) */
801 : : bool
802 : 23856 : range_adjacent_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
803 : : {
804 : 23856 : RangeBound lower1,
805 : : lower2;
806 : 23856 : RangeBound upper1,
807 : : upper2;
808 : 23856 : bool empty1,
809 : : empty2;
810 : :
811 : : /* Different types should be prevented by ANYRANGE matching rules */
812 [ + - ]: 23856 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
813 [ # # # # ]: 0 : elog(ERROR, "range types do not match");
814 : :
815 : 23856 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
816 : 23856 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
817 : :
818 : : /* An empty range is not adjacent to any other range */
819 [ + + - + ]: 23856 : if (empty1 || empty2)
820 : 2000 : 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 [ + + ]: 21856 : return (bounds_adjacent(typcache, upper1, lower2) ||
827 : 21605 : bounds_adjacent(typcache, upper2, lower1));
828 : 23856 : }
829 : :
830 : : /* adjacent to (but not overlapping)? */
831 : : Datum
832 : 12406 : range_adjacent(PG_FUNCTION_ARGS)
833 : : {
834 : 12406 : RangeType *r1 = PG_GETARG_RANGE_P(0);
835 : 12406 : RangeType *r2 = PG_GETARG_RANGE_P(1);
836 : 12406 : TypeCacheEntry *typcache;
837 : :
838 : 12406 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
839 : :
840 : 24812 : PG_RETURN_BOOL(range_adjacent_internal(typcache, r1, r2));
841 : 12406 : }
842 : :
843 : : /* overlaps? (internal version) */
844 : : bool
845 : 16111 : range_overlaps_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
846 : : {
847 : 16111 : RangeBound lower1,
848 : : lower2;
849 : 16111 : RangeBound upper1,
850 : : upper2;
851 : 16111 : bool empty1,
852 : : empty2;
853 : :
854 : : /* Different types should be prevented by ANYRANGE matching rules */
855 [ + - ]: 16111 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
856 [ # # # # ]: 0 : elog(ERROR, "range types do not match");
857 : :
858 : 16111 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
859 : 16111 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
860 : :
861 : : /* An empty range does not overlap any other range */
862 [ + + + + ]: 16111 : if (empty1 || empty2)
863 : 2350 : return false;
864 : :
865 [ + + + + ]: 13761 : if (range_cmp_bounds(typcache, &lower1, &lower2) >= 0 &&
866 : 12661 : range_cmp_bounds(typcache, &lower1, &upper2) <= 0)
867 : 808 : return true;
868 : :
869 [ + + + + ]: 12953 : if (range_cmp_bounds(typcache, &lower2, &lower1) >= 0 &&
870 : 1100 : range_cmp_bounds(typcache, &lower2, &upper1) <= 0)
871 : 999 : return true;
872 : :
873 : 11954 : return false;
874 : 16111 : }
875 : :
876 : : /* overlaps? */
877 : : Datum
878 : 12899 : range_overlaps(PG_FUNCTION_ARGS)
879 : : {
880 : 12899 : RangeType *r1 = PG_GETARG_RANGE_P(0);
881 : 12899 : RangeType *r2 = PG_GETARG_RANGE_P(1);
882 : 12899 : TypeCacheEntry *typcache;
883 : :
884 : 12899 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
885 : :
886 : 25798 : PG_RETURN_BOOL(range_overlaps_internal(typcache, r1, r2));
887 : 12899 : }
888 : :
889 : : /* does not extend to right of? (internal version) */
890 : : bool
891 : 21929 : range_overleft_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
892 : : {
893 : 21929 : RangeBound lower1,
894 : : lower2;
895 : 21929 : RangeBound upper1,
896 : : upper2;
897 : 21929 : bool empty1,
898 : : empty2;
899 : :
900 : : /* Different types should be prevented by ANYRANGE matching rules */
901 [ + - ]: 21929 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
902 [ # # # # ]: 0 : elog(ERROR, "range types do not match");
903 : :
904 : 21929 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
905 : 21929 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
906 : :
907 : : /* An empty range is neither before nor after any other range */
908 [ + + - + ]: 21929 : if (empty1 || empty2)
909 : 2191 : return false;
910 : :
911 [ + + ]: 19738 : if (range_cmp_bounds(typcache, &upper1, &upper2) <= 0)
912 : 6772 : return true;
913 : :
914 : 12966 : return false;
915 : 21929 : }
916 : :
917 : : /* does not extend to right of? */
918 : : Datum
919 : 12751 : range_overleft(PG_FUNCTION_ARGS)
920 : : {
921 : 12751 : RangeType *r1 = PG_GETARG_RANGE_P(0);
922 : 12751 : RangeType *r2 = PG_GETARG_RANGE_P(1);
923 : 12751 : TypeCacheEntry *typcache;
924 : :
925 : 12751 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
926 : :
927 : 25502 : PG_RETURN_BOOL(range_overleft_internal(typcache, r1, r2));
928 : 12751 : }
929 : :
930 : : /* does not extend to left of? (internal version) */
931 : : bool
932 : 36327 : range_overright_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
933 : : {
934 : 36327 : RangeBound lower1,
935 : : lower2;
936 : 36327 : RangeBound upper1,
937 : : upper2;
938 : 36327 : bool empty1,
939 : : empty2;
940 : :
941 : : /* Different types should be prevented by ANYRANGE matching rules */
942 [ + - ]: 36327 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
943 [ # # # # ]: 0 : elog(ERROR, "range types do not match");
944 : :
945 : 36327 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
946 : 36327 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
947 : :
948 : : /* An empty range is neither before nor after any other range */
949 [ + + - + ]: 36327 : if (empty1 || empty2)
950 : 2191 : return false;
951 : :
952 [ + + ]: 34136 : if (range_cmp_bounds(typcache, &lower1, &lower2) >= 0)
953 : 31826 : return true;
954 : :
955 : 2310 : return false;
956 : 36327 : }
957 : :
958 : : /* does not extend to left of? */
959 : : Datum
960 : 12750 : range_overright(PG_FUNCTION_ARGS)
961 : : {
962 : 12750 : RangeType *r1 = PG_GETARG_RANGE_P(0);
963 : 12750 : RangeType *r2 = PG_GETARG_RANGE_P(1);
964 : 12750 : TypeCacheEntry *typcache;
965 : :
966 : 12750 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
967 : :
968 : 25500 : PG_RETURN_BOOL(range_overright_internal(typcache, r1, r2));
969 : 12750 : }
970 : :
971 : :
972 : : /* range, range -> range functions */
973 : :
974 : : /* set difference */
975 : : Datum
976 : 5 : range_minus(PG_FUNCTION_ARGS)
977 : : {
978 : 5 : RangeType *r1 = PG_GETARG_RANGE_P(0);
979 : 5 : RangeType *r2 = PG_GETARG_RANGE_P(1);
980 : 5 : RangeType *ret;
981 : 5 : TypeCacheEntry *typcache;
982 : :
983 : : /* Different types should be prevented by ANYRANGE matching rules */
984 [ + - ]: 5 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
985 [ # # # # ]: 0 : elog(ERROR, "range types do not match");
986 : :
987 : 5 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
988 : :
989 : 5 : ret = range_minus_internal(typcache, r1, r2);
990 [ + - ]: 5 : if (ret)
991 : 5 : PG_RETURN_RANGE_P(ret);
992 : : else
993 : 0 : PG_RETURN_NULL();
994 [ - + ]: 5 : }
995 : :
996 : : RangeType *
997 : 27 : range_minus_internal(TypeCacheEntry *typcache, RangeType *r1, RangeType *r2)
998 : : {
999 : 27 : RangeBound lower1,
1000 : : lower2;
1001 : 27 : RangeBound upper1,
1002 : : upper2;
1003 : 27 : bool empty1,
1004 : : empty2;
1005 : 27 : int cmp_l1l2,
1006 : : cmp_l1u2,
1007 : : cmp_u1l2,
1008 : : cmp_u1u2;
1009 : :
1010 : 27 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
1011 : 27 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
1012 : :
1013 : : /* if either is empty, r1 is the correct answer */
1014 [ + - - + ]: 27 : if (empty1 || empty2)
1015 : 0 : return r1;
1016 : :
1017 : 27 : cmp_l1l2 = range_cmp_bounds(typcache, &lower1, &lower2);
1018 : 27 : cmp_l1u2 = range_cmp_bounds(typcache, &lower1, &upper2);
1019 : 27 : cmp_u1l2 = range_cmp_bounds(typcache, &upper1, &lower2);
1020 : 27 : cmp_u1u2 = range_cmp_bounds(typcache, &upper1, &upper2);
1021 : :
1022 [ + + + - ]: 27 : 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 [ + - + + ]: 27 : if (cmp_l1u2 > 0 || cmp_u1l2 < 0)
1028 : 2 : return r1;
1029 : :
1030 [ + + + + ]: 25 : if (cmp_l1l2 >= 0 && cmp_u1u2 <= 0)
1031 : 13 : return make_empty_range(typcache);
1032 : :
1033 [ + + + - : 12 : if (cmp_l1l2 <= 0 && cmp_u1l2 >= 0 && cmp_u1u2 <= 0)
+ + ]
1034 : : {
1035 : 6 : lower2.inclusive = !lower2.inclusive;
1036 : 6 : lower2.lower = false; /* it will become the upper bound */
1037 : 6 : return make_range(typcache, &lower1, &lower2, false, NULL);
1038 : : }
1039 : :
1040 [ + - ]: 6 : if (cmp_l1l2 >= 0 && cmp_u1u2 >= 0 && cmp_l1u2 <= 0)
1041 : : {
1042 : 6 : upper2.inclusive = !upper2.inclusive;
1043 : 6 : upper2.lower = true; /* it will become the lower bound */
1044 : 6 : return make_range(typcache, &upper2, &upper1, false, NULL);
1045 : : }
1046 : :
1047 [ # # # # ]: 0 : elog(ERROR, "unexpected case in range_minus");
1048 : 0 : return NULL;
1049 : 27 : }
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 : 262 : range_union_internal(TypeCacheEntry *typcache, RangeType *r1, RangeType *r2,
1057 : : bool strict)
1058 : : {
1059 : 262 : RangeBound lower1,
1060 : : lower2;
1061 : 262 : RangeBound upper1,
1062 : : upper2;
1063 : 262 : bool empty1,
1064 : : empty2;
1065 : 262 : RangeBound *result_lower;
1066 : 262 : RangeBound *result_upper;
1067 : :
1068 : : /* Different types should be prevented by ANYRANGE matching rules */
1069 [ + - ]: 262 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
1070 [ # # # # ]: 0 : elog(ERROR, "range types do not match");
1071 : :
1072 : 262 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
1073 : 262 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
1074 : :
1075 : : /* if either is empty, the other is the correct answer */
1076 [ + + ]: 262 : if (empty1)
1077 : 1 : return r2;
1078 [ - + ]: 261 : if (empty2)
1079 : 0 : return r1;
1080 : :
1081 [ + + ]: 261 : if (strict &&
1082 [ + + + + ]: 23 : !range_overlaps_internal(typcache, r1, r2) &&
1083 : 2 : !range_adjacent_internal(typcache, r1, r2))
1084 [ + - + - ]: 1 : ereport(ERROR,
1085 : : (errcode(ERRCODE_DATA_EXCEPTION),
1086 : : errmsg("result of range union would not be contiguous")));
1087 : :
1088 [ + + ]: 260 : if (range_cmp_bounds(typcache, &lower1, &lower2) < 0)
1089 : 254 : result_lower = &lower1;
1090 : : else
1091 : 6 : result_lower = &lower2;
1092 : :
1093 [ + + ]: 260 : if (range_cmp_bounds(typcache, &upper1, &upper2) > 0)
1094 : 8 : result_upper = &upper1;
1095 : : else
1096 : 252 : result_upper = &upper2;
1097 : :
1098 : 260 : return make_range(typcache, result_lower, result_upper, false, NULL);
1099 : 261 : }
1100 : :
1101 : : Datum
1102 : 3 : range_union(PG_FUNCTION_ARGS)
1103 : : {
1104 : 3 : RangeType *r1 = PG_GETARG_RANGE_P(0);
1105 : 3 : RangeType *r2 = PG_GETARG_RANGE_P(1);
1106 : 3 : TypeCacheEntry *typcache;
1107 : :
1108 : 3 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
1109 : :
1110 : 6 : PG_RETURN_RANGE_P(range_union_internal(typcache, r1, r2, true));
1111 : 3 : }
1112 : :
1113 : : /*
1114 : : * range merge: like set union, except also allow and account for non-adjacent
1115 : : * input ranges.
1116 : : */
1117 : : Datum
1118 : 5 : range_merge(PG_FUNCTION_ARGS)
1119 : : {
1120 : 5 : RangeType *r1 = PG_GETARG_RANGE_P(0);
1121 : 5 : RangeType *r2 = PG_GETARG_RANGE_P(1);
1122 : 5 : TypeCacheEntry *typcache;
1123 : :
1124 : 5 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
1125 : :
1126 : 10 : PG_RETURN_RANGE_P(range_union_internal(typcache, r1, r2, false));
1127 : 5 : }
1128 : :
1129 : : /* set intersection */
1130 : : Datum
1131 : 20 : range_intersect(PG_FUNCTION_ARGS)
1132 : : {
1133 : 20 : RangeType *r1 = PG_GETARG_RANGE_P(0);
1134 : 20 : RangeType *r2 = PG_GETARG_RANGE_P(1);
1135 : 20 : TypeCacheEntry *typcache;
1136 : :
1137 : : /* Different types should be prevented by ANYRANGE matching rules */
1138 [ + - ]: 20 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
1139 [ # # # # ]: 0 : elog(ERROR, "range types do not match");
1140 : :
1141 : 20 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
1142 : :
1143 : 40 : PG_RETURN_RANGE_P(range_intersect_internal(typcache, r1, r2));
1144 : 20 : }
1145 : :
1146 : : RangeType *
1147 : 70 : range_intersect_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
1148 : : {
1149 : 70 : RangeBound lower1,
1150 : : lower2;
1151 : 70 : RangeBound upper1,
1152 : : upper2;
1153 : 70 : bool empty1,
1154 : : empty2;
1155 : 70 : RangeBound *result_lower;
1156 : 70 : RangeBound *result_upper;
1157 : :
1158 : 70 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
1159 : 70 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
1160 : :
1161 [ + + + - : 70 : if (empty1 || empty2 || !range_overlaps_internal(typcache, r1, r2))
+ + ]
1162 : 5 : return make_empty_range(typcache);
1163 : :
1164 [ + + ]: 65 : if (range_cmp_bounds(typcache, &lower1, &lower2) >= 0)
1165 : 47 : result_lower = &lower1;
1166 : : else
1167 : 18 : result_lower = &lower2;
1168 : :
1169 [ + + ]: 65 : if (range_cmp_bounds(typcache, &upper1, &upper2) <= 0)
1170 : 49 : result_upper = &upper1;
1171 : : else
1172 : 16 : result_upper = &upper2;
1173 : :
1174 : 65 : return make_range(typcache, result_lower, result_upper, false, NULL);
1175 : 70 : }
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 : 44 : range_split_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2,
1187 : : RangeType **output1, RangeType **output2)
1188 : : {
1189 : 44 : RangeBound lower1,
1190 : : lower2;
1191 : 44 : RangeBound upper1,
1192 : : upper2;
1193 : 44 : bool empty1,
1194 : : empty2;
1195 : :
1196 : 44 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
1197 : 44 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
1198 : :
1199 [ + + + + ]: 44 : if (range_cmp_bounds(typcache, &lower1, &lower2) < 0 &&
1200 : 26 : 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 : 6 : lower2.inclusive = !lower2.inclusive;
1208 : 6 : lower2.lower = false;
1209 : 6 : upper2.inclusive = !upper2.inclusive;
1210 : 6 : upper2.lower = true;
1211 : :
1212 : 6 : *output1 = make_range(typcache, &lower1, &lower2, false, NULL);
1213 : 6 : *output2 = make_range(typcache, &upper2, &upper1, false, NULL);
1214 : 6 : return true;
1215 : : }
1216 : :
1217 : 38 : return false;
1218 : 44 : }
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 : 18 : range_minus_multi(PG_FUNCTION_ARGS)
1226 : : {
1227 : : struct range_minus_multi_fctx
1228 : : {
1229 : : RangeType *rs[2];
1230 : : int n;
1231 : : };
1232 : :
1233 : 18 : FuncCallContext *funcctx;
1234 : 18 : struct range_minus_multi_fctx *fctx;
1235 : 18 : MemoryContext oldcontext;
1236 : :
1237 : : /* stuff done only on the first call of the function */
1238 [ + + ]: 18 : if (SRF_IS_FIRSTCALL())
1239 : : {
1240 : 9 : RangeType *r1;
1241 : 9 : RangeType *r2;
1242 : 9 : Oid rngtypid;
1243 : 9 : TypeCacheEntry *typcache;
1244 : :
1245 : : /* create a function context for cross-call persistence */
1246 : 9 : funcctx = SRF_FIRSTCALL_INIT();
1247 : :
1248 : : /*
1249 : : * switch to memory context appropriate for multiple function calls
1250 : : */
1251 : 9 : oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1252 : :
1253 : 9 : r1 = PG_GETARG_RANGE_P(0);
1254 : 9 : r2 = PG_GETARG_RANGE_P(1);
1255 : :
1256 : : /* Different types should be prevented by ANYRANGE matching rules */
1257 [ + - ]: 9 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
1258 [ # # # # ]: 0 : elog(ERROR, "range types do not match");
1259 : :
1260 : : /* allocate memory for user context */
1261 : 9 : fctx = palloc_object(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 : 9 : rngtypid = RangeTypeGetOid(r1);
1268 : 9 : typcache = lookup_type_cache(rngtypid, TYPECACHE_RANGE_INFO);
1269 [ + - ]: 9 : if (typcache->rngelemtype == NULL)
1270 [ # # # # ]: 0 : elog(ERROR, "type %u is not a range type", rngtypid);
1271 : 9 : range_minus_multi_internal(typcache, r1, r2, fctx->rs, &fctx->n);
1272 : :
1273 : 9 : funcctx->user_fctx = fctx;
1274 : 9 : MemoryContextSwitchTo(oldcontext);
1275 : 9 : }
1276 : :
1277 : : /* stuff done on every call of the function */
1278 : 18 : funcctx = SRF_PERCALL_SETUP();
1279 : 18 : fctx = funcctx->user_fctx;
1280 : :
1281 [ + + ]: 18 : 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 : 9 : RangeType *ret = fctx->rs[funcctx->call_cntr];
1288 : :
1289 : 9 : SRF_RETURN_NEXT(funcctx, RangeTypePGetDatum(ret));
1290 [ + - ]: 9 : }
1291 : : else
1292 : : /* do when there is no more left */
1293 [ + - ]: 9 : SRF_RETURN_DONE(funcctx);
1294 [ - + ]: 18 : }
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 : 9 : range_minus_multi_internal(TypeCacheEntry *typcache, RangeType *r1,
1307 : : RangeType *r2, RangeType **outputs, int *outputn)
1308 : : {
1309 : 9 : int cmp_l1l2,
1310 : : cmp_l1u2,
1311 : : cmp_u1l2,
1312 : : cmp_u1u2;
1313 : 9 : RangeBound lower1,
1314 : : lower2;
1315 : 9 : RangeBound upper1,
1316 : : upper2;
1317 : 9 : bool empty1,
1318 : : empty2;
1319 : :
1320 : 9 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
1321 : 9 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
1322 : :
1323 [ + + ]: 9 : if (empty1)
1324 : : {
1325 : : /* if r1 is empty then r1 - r2 is empty, so return zero results */
1326 : 1 : *outputn = 0;
1327 : 1 : return;
1328 : : }
1329 [ + + ]: 8 : else if (empty2)
1330 : : {
1331 : : /* r2 is empty so the result is just r1 (which we know is not empty) */
1332 : 1 : outputs[0] = r1;
1333 : 1 : *outputn = 1;
1334 : 1 : return;
1335 : : }
1336 : :
1337 : : /*
1338 : : * Use the same logic as range_minus_internal, but support the split case
1339 : : */
1340 : 7 : cmp_l1l2 = range_cmp_bounds(typcache, &lower1, &lower2);
1341 : 7 : cmp_l1u2 = range_cmp_bounds(typcache, &lower1, &upper2);
1342 : 7 : cmp_u1l2 = range_cmp_bounds(typcache, &upper1, &lower2);
1343 : 7 : cmp_u1u2 = range_cmp_bounds(typcache, &upper1, &upper2);
1344 : :
1345 [ + + + + ]: 7 : if (cmp_l1l2 < 0 && cmp_u1u2 > 0)
1346 : : {
1347 : 2 : lower2.inclusive = !lower2.inclusive;
1348 : 2 : lower2.lower = false; /* it will become the upper bound */
1349 : 2 : outputs[0] = make_range(typcache, &lower1, &lower2, false, NULL);
1350 : :
1351 : 2 : upper2.inclusive = !upper2.inclusive;
1352 : 2 : upper2.lower = true; /* it will become the lower bound */
1353 : 2 : outputs[1] = make_range(typcache, &upper2, &upper1, false, NULL);
1354 : :
1355 : 2 : *outputn = 2;
1356 : 2 : }
1357 [ + - + + ]: 5 : else if (cmp_l1u2 > 0 || cmp_u1l2 < 0)
1358 : : {
1359 : 2 : outputs[0] = r1;
1360 : 2 : *outputn = 1;
1361 : 2 : }
1362 [ + + - + ]: 3 : else if (cmp_l1l2 >= 0 && cmp_u1u2 <= 0)
1363 : : {
1364 : 1 : *outputn = 0;
1365 : 1 : }
1366 [ + - + - : 2 : else if (cmp_l1l2 <= 0 && cmp_u1l2 >= 0 && cmp_u1u2 <= 0)
- + ]
1367 : : {
1368 : 2 : lower2.inclusive = !lower2.inclusive;
1369 : 2 : lower2.lower = false; /* it will become the upper bound */
1370 : 2 : outputs[0] = make_range(typcache, &lower1, &lower2, false, NULL);
1371 : 2 : *outputn = 1;
1372 : 2 : }
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 : 0 : }
1380 : : else
1381 : : {
1382 [ # # # # ]: 0 : elog(ERROR, "unexpected case in range_minus_multi");
1383 : : }
1384 [ - + ]: 9 : }
1385 : :
1386 : : /* range -> range aggregate functions */
1387 : :
1388 : : Datum
1389 : 7 : range_intersect_agg_transfn(PG_FUNCTION_ARGS)
1390 : : {
1391 : 7 : MemoryContext aggContext;
1392 : 7 : Oid rngtypoid;
1393 : 7 : TypeCacheEntry *typcache;
1394 : 7 : RangeType *result;
1395 : 7 : RangeType *current;
1396 : :
1397 [ + - ]: 7 : if (!AggCheckCallContext(fcinfo, &aggContext))
1398 [ # # # # ]: 0 : elog(ERROR, "range_intersect_agg_transfn called in non-aggregate context");
1399 : :
1400 : 7 : rngtypoid = get_fn_expr_argtype(fcinfo->flinfo, 1);
1401 [ + - ]: 7 : if (!type_is_range(rngtypoid))
1402 [ # # # # ]: 0 : elog(ERROR, "range_intersect_agg must be called with a range");
1403 : :
1404 : 7 : typcache = range_get_typcache(fcinfo, rngtypoid);
1405 : :
1406 : : /* strictness ensures these are non-null */
1407 : 7 : result = PG_GETARG_RANGE_P(0);
1408 : 7 : current = PG_GETARG_RANGE_P(1);
1409 : :
1410 : 7 : result = range_intersect_internal(typcache, result, current);
1411 : 14 : PG_RETURN_RANGE_P(result);
1412 : 7 : }
1413 : :
1414 : :
1415 : : /* Btree support */
1416 : :
1417 : : /* btree comparator */
1418 : : Datum
1419 : 3118 : range_cmp(PG_FUNCTION_ARGS)
1420 : : {
1421 : 3118 : RangeType *r1 = PG_GETARG_RANGE_P(0);
1422 : 3118 : RangeType *r2 = PG_GETARG_RANGE_P(1);
1423 : 3118 : TypeCacheEntry *typcache;
1424 : 3118 : RangeBound lower1,
1425 : : lower2;
1426 : 3118 : RangeBound upper1,
1427 : : upper2;
1428 : 3118 : bool empty1,
1429 : : empty2;
1430 : 3118 : int cmp;
1431 : :
1432 : 3118 : check_stack_depth(); /* recurses when subtype is a range type */
1433 : :
1434 : : /* Different types should be prevented by ANYRANGE matching rules */
1435 [ + - ]: 3118 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
1436 [ # # # # ]: 0 : elog(ERROR, "range types do not match");
1437 : :
1438 : 3118 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r1));
1439 : :
1440 : 3118 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
1441 : 3118 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
1442 : :
1443 : : /* For b-tree use, empty ranges sort before all else */
1444 [ + + + + ]: 3118 : if (empty1 && empty2)
1445 : 439 : cmp = 0;
1446 [ + + ]: 2679 : else if (empty1)
1447 : 579 : cmp = -1;
1448 [ + + ]: 2100 : else if (empty2)
1449 : 340 : cmp = 1;
1450 : : else
1451 : : {
1452 : 1760 : cmp = range_cmp_bounds(typcache, &lower1, &lower2);
1453 [ + + ]: 1760 : if (cmp == 0)
1454 : 90 : cmp = range_cmp_bounds(typcache, &upper1, &upper2);
1455 : : }
1456 : :
1457 [ + + ]: 3118 : PG_FREE_IF_COPY(r1, 0);
1458 [ + + ]: 3118 : PG_FREE_IF_COPY(r2, 1);
1459 : :
1460 : 6236 : PG_RETURN_INT32(cmp);
1461 : 3118 : }
1462 : :
1463 : : /* Sort support strategy routine */
1464 : : Datum
1465 : 245 : range_sortsupport(PG_FUNCTION_ARGS)
1466 : : {
1467 : 245 : SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
1468 : :
1469 : 245 : ssup->comparator = range_fast_cmp;
1470 : 245 : ssup->ssup_extra = NULL;
1471 : :
1472 : 245 : PG_RETURN_VOID();
1473 : 245 : }
1474 : :
1475 : : /* like range_cmp, but uses the new sortsupport interface */
1476 : : static int
1477 : 90105 : range_fast_cmp(Datum a, Datum b, SortSupport ssup)
1478 : : {
1479 : 90105 : RangeType *range_a = DatumGetRangeTypeP(a);
1480 : 90105 : RangeType *range_b = DatumGetRangeTypeP(b);
1481 : 90105 : TypeCacheEntry *typcache;
1482 : 90105 : RangeBound lower1,
1483 : : lower2;
1484 : 90105 : RangeBound upper1,
1485 : : upper2;
1486 : 90105 : bool empty1,
1487 : : empty2;
1488 : 90105 : int cmp;
1489 : :
1490 : : /* cache the range info between calls */
1491 [ + + ]: 90105 : if (ssup->ssup_extra == NULL)
1492 : : {
1493 [ + - ]: 58 : Assert(RangeTypeGetOid(range_a) == RangeTypeGetOid(range_b));
1494 : 58 : ssup->ssup_extra =
1495 : 58 : lookup_type_cache(RangeTypeGetOid(range_a), TYPECACHE_RANGE_INFO);
1496 : 58 : }
1497 : 90105 : typcache = ssup->ssup_extra;
1498 : :
1499 : 90105 : range_deserialize(typcache, range_a, &lower1, &upper1, &empty1);
1500 : 90105 : range_deserialize(typcache, range_b, &lower2, &upper2, &empty2);
1501 : :
1502 : : /* For b-tree use, empty ranges sort before all else */
1503 [ + + + + ]: 90105 : if (empty1 && empty2)
1504 : 12680 : cmp = 0;
1505 [ + + ]: 77425 : else if (empty1)
1506 : 3054 : cmp = -1;
1507 [ + + ]: 74371 : else if (empty2)
1508 : 244 : cmp = 1;
1509 : : else
1510 : : {
1511 : 74127 : cmp = range_cmp_bounds(typcache, &lower1, &lower2);
1512 [ + + ]: 74127 : if (cmp == 0)
1513 : 5385 : cmp = range_cmp_bounds(typcache, &upper1, &upper2);
1514 : : }
1515 : :
1516 [ - + ]: 90105 : if (range_a != DatumGetPointer(a))
1517 : 90105 : pfree(range_a);
1518 [ - + ]: 90105 : if (range_b != DatumGetPointer(b))
1519 : 90105 : pfree(range_b);
1520 : :
1521 : 180210 : return cmp;
1522 : 90105 : }
1523 : :
1524 : :
1525 : : /* inequality operators using the range_cmp function */
1526 : : Datum
1527 : 223 : range_lt(PG_FUNCTION_ARGS)
1528 : : {
1529 : 223 : int cmp = DatumGetInt32(range_cmp(fcinfo));
1530 : :
1531 : 446 : PG_RETURN_BOOL(cmp < 0);
1532 : 223 : }
1533 : :
1534 : : Datum
1535 : 502 : range_le(PG_FUNCTION_ARGS)
1536 : : {
1537 : 502 : int cmp = DatumGetInt32(range_cmp(fcinfo));
1538 : :
1539 : 1004 : PG_RETURN_BOOL(cmp <= 0);
1540 : 502 : }
1541 : :
1542 : : Datum
1543 : 506 : range_ge(PG_FUNCTION_ARGS)
1544 : : {
1545 : 506 : int cmp = DatumGetInt32(range_cmp(fcinfo));
1546 : :
1547 : 1012 : PG_RETURN_BOOL(cmp >= 0);
1548 : 506 : }
1549 : :
1550 : : Datum
1551 : 512 : range_gt(PG_FUNCTION_ARGS)
1552 : : {
1553 : 512 : int cmp = DatumGetInt32(range_cmp(fcinfo));
1554 : :
1555 : 1024 : PG_RETURN_BOOL(cmp > 0);
1556 : 512 : }
1557 : :
1558 : : /* Hash support */
1559 : :
1560 : : /* hash a range value */
1561 : : Datum
1562 : 35 : hash_range(PG_FUNCTION_ARGS)
1563 : : {
1564 : 35 : RangeType *r = PG_GETARG_RANGE_P(0);
1565 : 35 : uint32 result;
1566 : 35 : TypeCacheEntry *typcache;
1567 : 35 : TypeCacheEntry *scache;
1568 : 35 : RangeBound lower;
1569 : 35 : RangeBound upper;
1570 : 35 : bool empty;
1571 : 35 : char flags;
1572 : 35 : uint32 lower_hash;
1573 : 35 : uint32 upper_hash;
1574 : :
1575 : 35 : check_stack_depth(); /* recurses when subtype is a range type */
1576 : :
1577 : 35 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
1578 : :
1579 : : /* deserialize */
1580 : 35 : range_deserialize(typcache, r, &lower, &upper, &empty);
1581 : 35 : flags = range_get_flags(r);
1582 : :
1583 : : /*
1584 : : * Look up the element type's hash function, if not done already.
1585 : : */
1586 : 35 : scache = typcache->rngelemtype;
1587 [ + + ]: 35 : if (!OidIsValid(scache->hash_proc_finfo.fn_oid))
1588 : : {
1589 : 1 : scache = lookup_type_cache(scache->type_id, TYPECACHE_HASH_PROC_FINFO);
1590 [ + - ]: 1 : 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 : 1 : }
1596 : :
1597 : : /*
1598 : : * Apply the hash function to each bound.
1599 : : */
1600 [ + + ]: 35 : if (RANGE_HAS_LBOUND(flags))
1601 : 48 : lower_hash = DatumGetUInt32(FunctionCall1Coll(&scache->hash_proc_finfo,
1602 : 24 : typcache->rng_collation,
1603 : 24 : lower.val));
1604 : : else
1605 : 11 : lower_hash = 0;
1606 : :
1607 [ + + ]: 35 : if (RANGE_HAS_UBOUND(flags))
1608 : 52 : upper_hash = DatumGetUInt32(FunctionCall1Coll(&scache->hash_proc_finfo,
1609 : 26 : typcache->rng_collation,
1610 : 26 : upper.val));
1611 : : else
1612 : 9 : upper_hash = 0;
1613 : :
1614 : : /* Merge hashes of flags and bounds */
1615 : 35 : result = hash_bytes_uint32((uint32) flags);
1616 : 35 : result ^= lower_hash;
1617 : 35 : result = pg_rotate_left32(result, 1);
1618 : 35 : result ^= upper_hash;
1619 : :
1620 : 70 : PG_RETURN_INT32(result);
1621 : 35 : }
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 : 0 : hash_range_extended(PG_FUNCTION_ARGS)
1629 : : {
1630 : 0 : RangeType *r = PG_GETARG_RANGE_P(0);
1631 : 0 : Datum seed = PG_GETARG_DATUM(1);
1632 : 0 : uint64 result;
1633 : 0 : TypeCacheEntry *typcache;
1634 : 0 : TypeCacheEntry *scache;
1635 : 0 : RangeBound lower;
1636 : 0 : RangeBound upper;
1637 : 0 : bool empty;
1638 : 0 : char flags;
1639 : 0 : uint64 lower_hash;
1640 : 0 : uint64 upper_hash;
1641 : :
1642 : 0 : check_stack_depth();
1643 : :
1644 : 0 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
1645 : :
1646 : 0 : range_deserialize(typcache, r, &lower, &upper, &empty);
1647 : 0 : flags = range_get_flags(r);
1648 : :
1649 : 0 : scache = typcache->rngelemtype;
1650 [ # # ]: 0 : 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 : 0 : }
1660 : :
1661 [ # # ]: 0 : if (RANGE_HAS_LBOUND(flags))
1662 : 0 : lower_hash = DatumGetUInt64(FunctionCall2Coll(&scache->hash_extended_proc_finfo,
1663 : 0 : typcache->rng_collation,
1664 : 0 : lower.val,
1665 : 0 : seed));
1666 : : else
1667 : 0 : lower_hash = 0;
1668 : :
1669 [ # # ]: 0 : if (RANGE_HAS_UBOUND(flags))
1670 : 0 : upper_hash = DatumGetUInt64(FunctionCall2Coll(&scache->hash_extended_proc_finfo,
1671 : 0 : typcache->rng_collation,
1672 : 0 : upper.val,
1673 : 0 : seed));
1674 : : else
1675 : 0 : upper_hash = 0;
1676 : :
1677 : : /* Merge hashes of flags and bounds */
1678 : 0 : result = DatumGetUInt64(hash_uint32_extended((uint32) flags,
1679 : 0 : DatumGetInt64(seed)));
1680 : 0 : result ^= lower_hash;
1681 : 0 : result = ROTATE_HIGH_AND_LOW_32BITS(result);
1682 : 0 : result ^= upper_hash;
1683 : :
1684 : 0 : PG_RETURN_UINT64(result);
1685 : 0 : }
1686 : :
1687 : : /*
1688 : : *----------------------------------------------------------
1689 : : * CANONICAL FUNCTIONS
1690 : : *
1691 : : * Functions for specific built-in range types.
1692 : : *----------------------------------------------------------
1693 : : */
1694 : :
1695 : : Datum
1696 : 0 : int4range_canonical(PG_FUNCTION_ARGS)
1697 : : {
1698 : 0 : RangeType *r = PG_GETARG_RANGE_P(0);
1699 : 0 : Node *escontext = fcinfo->context;
1700 : 0 : TypeCacheEntry *typcache;
1701 : 0 : RangeBound lower;
1702 : 0 : RangeBound upper;
1703 : 0 : bool empty;
1704 : :
1705 : 0 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
1706 : :
1707 : 0 : range_deserialize(typcache, r, &lower, &upper, &empty);
1708 : :
1709 [ # # ]: 0 : if (empty)
1710 : 0 : PG_RETURN_RANGE_P(r);
1711 : :
1712 [ # # # # ]: 0 : if (!lower.infinite && !lower.inclusive)
1713 : : {
1714 : 0 : int32 bnd = DatumGetInt32(lower.val);
1715 : :
1716 : : /* Handle possible overflow manually */
1717 [ # # ]: 0 : 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 : 0 : lower.val = Int32GetDatum(bnd + 1);
1722 : 0 : lower.inclusive = true;
1723 [ # # ]: 0 : }
1724 : :
1725 [ # # # # ]: 0 : if (!upper.infinite && upper.inclusive)
1726 : : {
1727 : 0 : int32 bnd = DatumGetInt32(upper.val);
1728 : :
1729 : : /* Handle possible overflow manually */
1730 [ # # ]: 0 : if (unlikely(bnd == PG_INT32_MAX))
1731 [ # # ]: 0 : ereturn(escontext, (Datum) 0,
1732 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
1733 : : errmsg("integer out of range")));
1734 : 0 : upper.val = Int32GetDatum(bnd + 1);
1735 : 0 : upper.inclusive = false;
1736 [ # # ]: 0 : }
1737 : :
1738 : 0 : PG_RETURN_RANGE_P(range_serialize(typcache, &lower, &upper,
1739 : : false, escontext));
1740 : 0 : }
1741 : :
1742 : : Datum
1743 : 0 : int8range_canonical(PG_FUNCTION_ARGS)
1744 : : {
1745 : 0 : RangeType *r = PG_GETARG_RANGE_P(0);
1746 : 0 : Node *escontext = fcinfo->context;
1747 : 0 : TypeCacheEntry *typcache;
1748 : 0 : RangeBound lower;
1749 : 0 : RangeBound upper;
1750 : 0 : bool empty;
1751 : :
1752 : 0 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
1753 : :
1754 : 0 : range_deserialize(typcache, r, &lower, &upper, &empty);
1755 : :
1756 [ # # ]: 0 : if (empty)
1757 : 0 : PG_RETURN_RANGE_P(r);
1758 : :
1759 [ # # # # ]: 0 : if (!lower.infinite && !lower.inclusive)
1760 : : {
1761 : 0 : int64 bnd = DatumGetInt64(lower.val);
1762 : :
1763 : : /* Handle possible overflow manually */
1764 [ # # ]: 0 : 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 : 0 : lower.val = Int64GetDatum(bnd + 1);
1769 : 0 : lower.inclusive = true;
1770 [ # # ]: 0 : }
1771 : :
1772 [ # # # # ]: 0 : if (!upper.infinite && upper.inclusive)
1773 : : {
1774 : 0 : int64 bnd = DatumGetInt64(upper.val);
1775 : :
1776 : : /* Handle possible overflow manually */
1777 [ # # ]: 0 : 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 : 0 : upper.val = Int64GetDatum(bnd + 1);
1782 : 0 : upper.inclusive = false;
1783 [ # # ]: 0 : }
1784 : :
1785 : 0 : PG_RETURN_RANGE_P(range_serialize(typcache, &lower, &upper,
1786 : : false, escontext));
1787 : 0 : }
1788 : :
1789 : : Datum
1790 : 0 : daterange_canonical(PG_FUNCTION_ARGS)
1791 : : {
1792 : 0 : RangeType *r = PG_GETARG_RANGE_P(0);
1793 : 0 : Node *escontext = fcinfo->context;
1794 : 0 : TypeCacheEntry *typcache;
1795 : 0 : RangeBound lower;
1796 : 0 : RangeBound upper;
1797 : 0 : bool empty;
1798 : :
1799 : 0 : typcache = range_get_typcache(fcinfo, RangeTypeGetOid(r));
1800 : :
1801 : 0 : range_deserialize(typcache, r, &lower, &upper, &empty);
1802 : :
1803 [ # # ]: 0 : if (empty)
1804 : 0 : PG_RETURN_RANGE_P(r);
1805 : :
1806 [ # # # # : 0 : if (!lower.infinite && !DATE_NOT_FINITE(DatumGetDateADT(lower.val)) &&
# # # # ]
1807 : 0 : !lower.inclusive)
1808 : : {
1809 : 0 : DateADT bnd = DatumGetDateADT(lower.val);
1810 : :
1811 : : /* Check for overflow -- note we already eliminated PG_INT32_MAX */
1812 : 0 : bnd++;
1813 [ # # # # ]: 0 : 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 : 0 : lower.val = DateADTGetDatum(bnd);
1818 : 0 : lower.inclusive = true;
1819 [ # # ]: 0 : }
1820 : :
1821 [ # # # # : 0 : if (!upper.infinite && !DATE_NOT_FINITE(DatumGetDateADT(upper.val)) &&
# # # # ]
1822 : 0 : upper.inclusive)
1823 : : {
1824 : 0 : DateADT bnd = DatumGetDateADT(upper.val);
1825 : :
1826 : : /* Check for overflow -- note we already eliminated PG_INT32_MAX */
1827 : 0 : bnd++;
1828 [ # # # # ]: 0 : if (unlikely(!IS_VALID_DATE(bnd)))
1829 [ # # ]: 0 : ereturn(escontext, (Datum) 0,
1830 : : (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1831 : : errmsg("date out of range")));
1832 : 0 : upper.val = DateADTGetDatum(bnd);
1833 : 0 : upper.inclusive = false;
1834 [ # # ]: 0 : }
1835 : :
1836 : 0 : PG_RETURN_RANGE_P(range_serialize(typcache, &lower, &upper,
1837 : : false, escontext));
1838 : 0 : }
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 : 0 : int4range_subdiff(PG_FUNCTION_ARGS)
1854 : : {
1855 : 0 : int32 v1 = PG_GETARG_INT32(0);
1856 : 0 : int32 v2 = PG_GETARG_INT32(1);
1857 : :
1858 : 0 : PG_RETURN_FLOAT8((float8) v1 - (float8) v2);
1859 : 0 : }
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 : 0 : }
1869 : :
1870 : : Datum
1871 : 0 : numrange_subdiff(PG_FUNCTION_ARGS)
1872 : : {
1873 : 0 : Datum v1 = PG_GETARG_DATUM(0);
1874 : 0 : Datum v2 = PG_GETARG_DATUM(1);
1875 : 0 : Datum numresult;
1876 : 0 : float8 floatresult;
1877 : :
1878 : 0 : numresult = DirectFunctionCall2(numeric_sub, v1, v2);
1879 : :
1880 : 0 : floatresult = DatumGetFloat8(DirectFunctionCall1(numeric_float8,
1881 : : numresult));
1882 : :
1883 : 0 : PG_RETURN_FLOAT8(floatresult);
1884 : 0 : }
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 : 0 : }
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 : 0 : float8 result;
1901 : :
1902 : 0 : result = ((float8) v1 - (float8) v2) / USECS_PER_SEC;
1903 : 0 : PG_RETURN_FLOAT8(result);
1904 : 0 : }
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 : 0 : float8 result;
1912 : :
1913 : 0 : result = ((float8) v1 - (float8) v2) / USECS_PER_SEC;
1914 : 0 : PG_RETURN_FLOAT8(result);
1915 : 0 : }
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 : 684948 : range_get_typcache(FunctionCallInfo fcinfo, Oid rngtypid)
1936 : : {
1937 : 684948 : TypeCacheEntry *typcache = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
1938 : :
1939 [ + + + - ]: 684948 : if (typcache == NULL ||
1940 : 681995 : typcache->type_id != rngtypid)
1941 : : {
1942 : 2953 : typcache = lookup_type_cache(rngtypid, TYPECACHE_RANGE_INFO);
1943 [ + - ]: 2953 : if (typcache->rngelemtype == NULL)
1944 [ # # # # ]: 0 : elog(ERROR, "type %u is not a range type", rngtypid);
1945 : 2953 : fcinfo->flinfo->fn_extra = typcache;
1946 : 2953 : }
1947 : :
1948 : 1369896 : return typcache;
1949 : 684948 : }
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 : 0 : range_serialize(TypeCacheEntry *typcache, RangeBound *lower, RangeBound *upper,
1960 : : bool empty, struct Node *escontext)
1961 : : {
1962 : 0 : RangeType *range;
1963 : 0 : int cmp;
1964 : 0 : Size msize;
1965 : 0 : Pointer ptr;
1966 : 0 : int16 typlen;
1967 : 0 : bool typbyval;
1968 : 0 : char typalign;
1969 : 0 : char typstorage;
1970 : 0 : 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 [ # # ]: 0 : Assert(lower->lower);
1977 [ # # ]: 0 : Assert(!upper->lower);
1978 : :
1979 [ # # ]: 0 : if (empty)
1980 : 0 : flags |= RANGE_EMPTY;
1981 : : else
1982 : : {
1983 : 0 : cmp = range_cmp_bound_values(typcache, lower, upper);
1984 : :
1985 : : /* error check: if lower bound value is above upper, it's wrong */
1986 [ # # ]: 0 : if (cmp > 0)
1987 [ # # ]: 0 : 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 [ # # # # : 0 : if (cmp == 0 && !(lower->inclusive && upper->inclusive))
# # ]
1993 : 0 : flags |= RANGE_EMPTY;
1994 : : else
1995 : : {
1996 : : /* infinite boundaries are never inclusive */
1997 [ # # ]: 0 : if (lower->infinite)
1998 : 0 : flags |= RANGE_LB_INF;
1999 [ # # ]: 0 : else if (lower->inclusive)
2000 : 0 : flags |= RANGE_LB_INC;
2001 [ # # ]: 0 : if (upper->infinite)
2002 : 0 : flags |= RANGE_UB_INF;
2003 [ # # ]: 0 : else if (upper->inclusive)
2004 : 0 : flags |= RANGE_UB_INC;
2005 : : }
2006 : : }
2007 : :
2008 : : /* Fetch information about range's element type */
2009 : 0 : typlen = typcache->rngelemtype->typlen;
2010 : 0 : typbyval = typcache->rngelemtype->typbyval;
2011 : 0 : typalign = typcache->rngelemtype->typalign;
2012 : 0 : typstorage = typcache->rngelemtype->typstorage;
2013 : :
2014 : : /* Count space for varlena header and range type's OID */
2015 : 0 : msize = sizeof(RangeType);
2016 [ # # ]: 0 : Assert(msize == MAXALIGN(msize));
2017 : :
2018 : : /* Count space for bounds */
2019 [ # # ]: 0 : 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 [ # # ]: 0 : if (typlen == -1)
2031 : 0 : lower->val = PointerGetDatum(PG_DETOAST_DATUM_PACKED(lower->val));
2032 : :
2033 : 0 : msize = datum_compute_size(msize, lower->val, typbyval, typalign,
2034 : 0 : typlen, typstorage);
2035 : 0 : }
2036 : :
2037 [ # # ]: 0 : if (RANGE_HAS_UBOUND(flags))
2038 : : {
2039 : : /* Make sure item to be inserted is not toasted */
2040 [ # # ]: 0 : if (typlen == -1)
2041 : 0 : upper->val = PointerGetDatum(PG_DETOAST_DATUM_PACKED(upper->val));
2042 : :
2043 : 0 : msize = datum_compute_size(msize, upper->val, typbyval, typalign,
2044 : 0 : typlen, typstorage);
2045 : 0 : }
2046 : :
2047 : : /* Add space for flag byte */
2048 : 0 : msize += sizeof(char);
2049 : :
2050 : : /* Note: zero-fill is required here, just as in heap tuples */
2051 : 0 : range = (RangeType *) palloc0(msize);
2052 : 0 : SET_VARSIZE(range, msize);
2053 : :
2054 : : /* Now fill in the datum */
2055 : 0 : range->rangetypid = typcache->type_id;
2056 : :
2057 : 0 : ptr = (char *) (range + 1);
2058 : :
2059 [ # # ]: 0 : if (RANGE_HAS_LBOUND(flags))
2060 : : {
2061 [ # # ]: 0 : Assert(lower->lower);
2062 : 0 : ptr = datum_write(ptr, lower->val, typbyval, typalign, typlen,
2063 : 0 : typstorage);
2064 : 0 : }
2065 : :
2066 [ # # ]: 0 : if (RANGE_HAS_UBOUND(flags))
2067 : : {
2068 [ # # ]: 0 : Assert(!upper->lower);
2069 : 0 : ptr = datum_write(ptr, upper->val, typbyval, typalign, typlen,
2070 : 0 : typstorage);
2071 : 0 : }
2072 : :
2073 : 0 : *((char *) ptr) = flags;
2074 : :
2075 : 0 : return range;
2076 : 0 : }
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 : 1595629 : range_deserialize(TypeCacheEntry *typcache, const RangeType *range,
2089 : : RangeBound *lower, RangeBound *upper, bool *empty)
2090 : : {
2091 : 1595629 : char flags;
2092 : 1595629 : int16 typlen;
2093 : 1595629 : bool typbyval;
2094 : 1595629 : char typalign;
2095 : 1595629 : const char *ptr;
2096 : 1595629 : Datum lbound;
2097 : 1595629 : Datum ubound;
2098 : :
2099 : : /* assert caller passed the right typcache entry */
2100 [ + - ]: 1595629 : Assert(RangeTypeGetOid(range) == typcache->type_id);
2101 : :
2102 : : /* fetch the flag byte from datum's last byte */
2103 : 1595629 : flags = *((const char *) range + VARSIZE(range) - 1);
2104 : :
2105 : : /* fetch information about range's element type */
2106 : 1595629 : typlen = typcache->rngelemtype->typlen;
2107 : 1595629 : typbyval = typcache->rngelemtype->typbyval;
2108 : 1595629 : typalign = typcache->rngelemtype->typalign;
2109 : :
2110 : : /* initialize data pointer just after the range OID */
2111 : 1595629 : ptr = (char *) (range + 1);
2112 : :
2113 : : /* fetch lower bound, if any */
2114 [ + + ]: 1595629 : if (RANGE_HAS_LBOUND(flags))
2115 : : {
2116 : : /* att_align_pointer cannot be necessary here */
2117 : 1408596 : lbound = fetch_att(ptr, typbyval, typlen);
2118 [ + + - + : 1408596 : ptr = (char *) att_addlength_pointer(ptr, typlen, ptr);
# # ]
2119 : 1408596 : }
2120 : : else
2121 : 187033 : lbound = (Datum) 0;
2122 : :
2123 : : /* fetch upper bound, if any */
2124 [ + + ]: 1595629 : if (RANGE_HAS_UBOUND(flags))
2125 : : {
2126 [ + + + + : 1412843 : ptr = (char *) att_align_pointer(ptr, typalign, typlen, ptr);
+ + - + +
- # # ]
2127 : 1412843 : ubound = fetch_att(ptr, typbyval, typlen);
2128 : : /* no need for att_addlength_pointer */
2129 : 1412843 : }
2130 : : else
2131 : 182786 : ubound = (Datum) 0;
2132 : :
2133 : : /* emit results */
2134 : :
2135 : 1595629 : *empty = (flags & RANGE_EMPTY) != 0;
2136 : :
2137 : 1595629 : lower->val = lbound;
2138 : 1595629 : lower->infinite = (flags & RANGE_LB_INF) != 0;
2139 : 1595629 : lower->inclusive = (flags & RANGE_LB_INC) != 0;
2140 : 1595629 : lower->lower = true;
2141 : :
2142 : 1595629 : upper->val = ubound;
2143 : 1595629 : upper->infinite = (flags & RANGE_UB_INF) != 0;
2144 : 1595629 : upper->inclusive = (flags & RANGE_UB_INC) != 0;
2145 : 1595629 : upper->lower = false;
2146 : 1595629 : }
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 : 473851 : range_get_flags(const RangeType *range)
2156 : : {
2157 : : /* fetch the flag byte from datum's last byte */
2158 : 473851 : 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 : 0 : range_set_contain_empty(RangeType *range)
2170 : : {
2171 : 0 : char *flagsp;
2172 : :
2173 : : /* flag byte is datum's last byte */
2174 : 0 : flagsp = (char *) range + VARSIZE(range) - 1;
2175 : :
2176 : 0 : *flagsp |= RANGE_CONTAIN_EMPTY;
2177 : 0 : }
2178 : :
2179 : : /*
2180 : : * This both serializes and canonicalizes (if applicable) the range.
2181 : : * This should be used by most callers.
2182 : : */
2183 : : RangeType *
2184 : 76316 : make_range(TypeCacheEntry *typcache, RangeBound *lower, RangeBound *upper,
2185 : : bool empty, struct Node *escontext)
2186 : : {
2187 : 76316 : RangeType *range;
2188 : :
2189 : 76316 : range = range_serialize(typcache, lower, upper, empty, escontext);
2190 : :
2191 [ + + + - : 76316 : if (SOFT_ERROR_OCCURRED(escontext))
+ + ]
2192 : 2 : return NULL;
2193 : :
2194 : : /* no need to call canonical on empty ranges ... */
2195 [ + + + + ]: 76314 : if (OidIsValid(typcache->rng_canonical_finfo.fn_oid) &&
2196 : 75297 : !RangeIsEmpty(range))
2197 : : {
2198 : : /* Do this the hard way so that we can pass escontext */
2199 : 74677 : LOCAL_FCINFO(fcinfo, 1);
2200 : 74677 : Datum result;
2201 : :
2202 : 74677 : InitFunctionCallInfoData(*fcinfo, &typcache->rng_canonical_finfo, 1,
2203 : : InvalidOid, escontext, NULL);
2204 : :
2205 : 74677 : fcinfo->args[0].value = RangeTypePGetDatum(range);
2206 : 74677 : fcinfo->args[0].isnull = false;
2207 : :
2208 : 74677 : result = FunctionCallInvoke(fcinfo);
2209 : :
2210 [ + + + - : 74677 : if (SOFT_ERROR_OCCURRED(escontext))
+ + ]
2211 : 4 : return NULL;
2212 : :
2213 : : /* Should not get a null result if there was no error */
2214 [ + - ]: 74673 : if (fcinfo->isnull)
2215 [ # # # # ]: 0 : elog(ERROR, "function %u returned NULL",
2216 : : typcache->rng_canonical_finfo.fn_oid);
2217 : :
2218 : 74673 : range = DatumGetRangeTypeP(result);
2219 [ + + ]: 74677 : }
2220 : :
2221 : 76310 : return range;
2222 : 76316 : }
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 : 1827708 : range_cmp_bounds(TypeCacheEntry *typcache, const RangeBound *b1, const RangeBound *b2)
2249 : : {
2250 : 1827708 : int32 result;
2251 : :
2252 : : /*
2253 : : * First, handle cases involving infinity, which don't require invoking
2254 : : * the comparison proc.
2255 : : */
2256 [ + + + + ]: 1827708 : 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 [ + + ]: 3078 : if (b1->lower == b2->lower)
2263 : 3063 : return 0;
2264 : : else
2265 : 15 : return b1->lower ? -1 : 1;
2266 : : }
2267 [ + + ]: 1824630 : else if (b1->infinite)
2268 : 14543 : return b1->lower ? -1 : 1;
2269 [ + + ]: 1810087 : else if (b2->infinite)
2270 : 5175 : return b2->lower ? 1 : -1;
2271 : :
2272 : : /*
2273 : : * Both boundaries are finite, so compare the held values.
2274 : : */
2275 : 3609824 : result = DatumGetInt32(FunctionCall2Coll(&typcache->rng_cmp_proc_finfo,
2276 : 1804912 : typcache->rng_collation,
2277 : 1804912 : 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 [ + + ]: 1804912 : if (result == 0)
2285 : : {
2286 [ + + + + ]: 131269 : if (!b1->inclusive && !b2->inclusive)
2287 : : {
2288 : : /* both are exclusive */
2289 [ + + ]: 58716 : if (b1->lower == b2->lower)
2290 : 58715 : return 0;
2291 : : else
2292 : 1 : return b1->lower ? 1 : -1;
2293 : : }
2294 [ + + ]: 72553 : else if (!b1->inclusive)
2295 : 132 : return b1->lower ? 1 : -1;
2296 [ + + ]: 72421 : else if (!b2->inclusive)
2297 : 204 : 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 : 72217 : return 0;
2306 : : }
2307 : : }
2308 : :
2309 : 1673643 : return result;
2310 : 1827708 : }
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 : 229564 : 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 [ + + + + ]: 229564 : 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 [ - + ]: 55 : if (b1->lower == b2->lower)
2336 : 0 : return 0;
2337 : : else
2338 : 55 : return b1->lower ? -1 : 1;
2339 : : }
2340 [ + + ]: 229509 : else if (b1->infinite)
2341 : 3049 : return b1->lower ? -1 : 1;
2342 [ + + ]: 226460 : else if (b2->infinite)
2343 : 2346 : return b2->lower ? 1 : -1;
2344 : :
2345 : : /*
2346 : : * Both boundaries are finite, so compare the held values.
2347 : : */
2348 : 448228 : return DatumGetInt32(FunctionCall2Coll(&typcache->rng_cmp_proc_finfo,
2349 : 224114 : typcache->rng_collation,
2350 : 224114 : b1->val, b2->val));
2351 : 229564 : }
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 : 0 : range_compare(const void *key1, const void *key2, void *arg)
2362 : : {
2363 : 0 : RangeType *r1 = *(RangeType **) key1;
2364 : 0 : RangeType *r2 = *(RangeType **) key2;
2365 : 0 : TypeCacheEntry *typcache = (TypeCacheEntry *) arg;
2366 : 0 : RangeBound lower1;
2367 : 0 : RangeBound upper1;
2368 : 0 : RangeBound lower2;
2369 : 0 : RangeBound upper2;
2370 : 0 : bool empty1;
2371 : 0 : bool empty2;
2372 : 0 : int cmp;
2373 : :
2374 : 0 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
2375 : 0 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
2376 : :
2377 [ # # # # ]: 0 : if (empty1 && empty2)
2378 : 0 : cmp = 0;
2379 [ # # ]: 0 : else if (empty1)
2380 : 0 : cmp = -1;
2381 [ # # ]: 0 : else if (empty2)
2382 : 0 : cmp = 1;
2383 : : else
2384 : : {
2385 : 0 : cmp = range_cmp_bounds(typcache, &lower1, &lower2);
2386 [ # # ]: 0 : if (cmp == 0)
2387 : 0 : cmp = range_cmp_bounds(typcache, &upper1, &upper2);
2388 : : }
2389 : :
2390 : 0 : return cmp;
2391 : 0 : }
2392 : :
2393 : : /*
2394 : : * Build an empty range value of the type indicated by the typcache entry.
2395 : : */
2396 : : RangeType *
2397 : 533 : make_empty_range(TypeCacheEntry *typcache)
2398 : : {
2399 : 533 : RangeBound lower;
2400 : 533 : RangeBound upper;
2401 : :
2402 : 533 : lower.val = (Datum) 0;
2403 : 533 : lower.infinite = false;
2404 : 533 : lower.inclusive = false;
2405 : 533 : lower.lower = true;
2406 : :
2407 : 533 : upper.val = (Datum) 0;
2408 : 533 : upper.infinite = false;
2409 : 533 : upper.inclusive = false;
2410 : 533 : upper.lower = false;
2411 : :
2412 : 1066 : return make_range(typcache, &lower, &upper, true, NULL);
2413 : 533 : }
2414 : :
2415 : : /*
2416 : : * Planner support function for elem_contained_by_range (<@ operator).
2417 : : */
2418 : : Datum
2419 : 0 : elem_contained_by_range_support(PG_FUNCTION_ARGS)
2420 : : {
2421 : 0 : Node *rawreq = (Node *) PG_GETARG_POINTER(0);
2422 : 0 : Node *ret = NULL;
2423 : :
2424 [ # # ]: 0 : if (IsA(rawreq, SupportRequestSimplify))
2425 : : {
2426 : 0 : SupportRequestSimplify *req = (SupportRequestSimplify *) rawreq;
2427 : 0 : FuncExpr *fexpr = req->fcall;
2428 : 0 : Expr *leftop,
2429 : : *rightop;
2430 : :
2431 [ # # ]: 0 : Assert(list_length(fexpr->args) == 2);
2432 : 0 : leftop = linitial(fexpr->args);
2433 : 0 : rightop = lsecond(fexpr->args);
2434 : :
2435 : 0 : ret = find_simplified_clause(req->root, rightop, leftop);
2436 : 0 : }
2437 : :
2438 : 0 : PG_RETURN_POINTER(ret);
2439 : 0 : }
2440 : :
2441 : : /*
2442 : : * Planner support function for range_contains_elem (@> operator).
2443 : : */
2444 : : Datum
2445 : 0 : range_contains_elem_support(PG_FUNCTION_ARGS)
2446 : : {
2447 : 0 : Node *rawreq = (Node *) PG_GETARG_POINTER(0);
2448 : 0 : Node *ret = NULL;
2449 : :
2450 [ # # ]: 0 : if (IsA(rawreq, SupportRequestSimplify))
2451 : : {
2452 : 0 : SupportRequestSimplify *req = (SupportRequestSimplify *) rawreq;
2453 : 0 : FuncExpr *fexpr = req->fcall;
2454 : 0 : Expr *leftop,
2455 : : *rightop;
2456 : :
2457 [ # # ]: 0 : Assert(list_length(fexpr->args) == 2);
2458 : 0 : leftop = linitial(fexpr->args);
2459 : 0 : rightop = lsecond(fexpr->args);
2460 : :
2461 : 0 : ret = find_simplified_clause(req->root, leftop, rightop);
2462 : 0 : }
2463 : :
2464 : 0 : PG_RETURN_POINTER(ret);
2465 : 0 : }
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 : 868 : range_parse_flags(const char *flags_str)
2480 : : {
2481 : 868 : char flags = 0;
2482 : :
2483 [ + - ]: 868 : if (flags_str[0] == '\0' ||
2484 : 868 : flags_str[1] == '\0' ||
2485 : 868 : 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 [ + + - ]: 868 : switch (flags_str[0])
2492 : : {
2493 : : case '[':
2494 : 44 : flags |= RANGE_LB_INC;
2495 : 44 : break;
2496 : : case '(':
2497 : : break;
2498 : : default:
2499 [ # # # # ]: 0 : ereport(ERROR,
2500 : : (errcode(ERRCODE_SYNTAX_ERROR),
2501 : : errmsg("invalid range bound flags"),
2502 : : errhint("Valid values are \"[]\", \"[)\", \"(]\", and \"()\".")));
2503 : 0 : }
2504 : :
2505 [ + + - ]: 868 : switch (flags_str[1])
2506 : : {
2507 : : case ']':
2508 : 849 : flags |= RANGE_UB_INC;
2509 : 849 : break;
2510 : : case ')':
2511 : : break;
2512 : : default:
2513 [ # # # # ]: 0 : ereport(ERROR,
2514 : : (errcode(ERRCODE_SYNTAX_ERROR),
2515 : : errmsg("invalid range bound flags"),
2516 : : errhint("Valid values are \"[]\", \"[)\", \"(]\", and \"()\".")));
2517 : 0 : }
2518 : :
2519 : 1736 : return flags;
2520 : 868 : }
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 : 1030 : range_parse(const char *string, char *flags, char **lbound_str,
2555 : : char **ubound_str, Node *escontext)
2556 : : {
2557 : 1030 : const char *ptr = string;
2558 : 1030 : bool infinite;
2559 : :
2560 : 1030 : *flags = 0;
2561 : :
2562 : : /* consume whitespace */
2563 [ + + + + ]: 1034 : while (*ptr != '\0' && isspace((unsigned char) *ptr))
2564 : 4 : ptr++;
2565 : :
2566 : : /* check for empty range */
2567 : 1030 : if (pg_strncasecmp(ptr, RANGE_EMPTY_LITERAL,
2568 [ + + ]: 1030 : strlen(RANGE_EMPTY_LITERAL)) == 0)
2569 : : {
2570 : 100 : *flags = RANGE_EMPTY;
2571 : 100 : *lbound_str = NULL;
2572 : 100 : *ubound_str = NULL;
2573 : :
2574 : 100 : ptr += strlen(RANGE_EMPTY_LITERAL);
2575 : :
2576 : : /* the rest should be whitespace */
2577 [ + + + + ]: 102 : while (*ptr != '\0' && isspace((unsigned char) *ptr))
2578 : 2 : ptr++;
2579 : :
2580 : : /* should have consumed everything */
2581 [ + - ]: 100 : 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 : 100 : return true;
2589 : : }
2590 : :
2591 [ + + ]: 930 : if (*ptr == '[')
2592 : : {
2593 : 815 : *flags |= RANGE_LB_INC;
2594 : 815 : ptr++;
2595 : 815 : }
2596 [ + + ]: 115 : else if (*ptr == '(')
2597 : 110 : ptr++;
2598 : : else
2599 [ + + ]: 5 : 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 : 925 : ptr = range_parse_bound(string, ptr, lbound_str, &infinite, escontext);
2606 [ + - ]: 925 : if (ptr == NULL)
2607 : 0 : return false;
2608 [ + + ]: 925 : if (infinite)
2609 : 27 : *flags |= RANGE_LB_INF;
2610 : :
2611 [ + + ]: 925 : if (*ptr == ',')
2612 : 917 : ptr++;
2613 : : else
2614 [ + + ]: 8 : 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 : 917 : ptr = range_parse_bound(string, ptr, ubound_str, &infinite, escontext);
2621 [ + + ]: 917 : if (ptr == NULL)
2622 : 2 : return false;
2623 [ + + ]: 915 : if (infinite)
2624 : 41 : *flags |= RANGE_UB_INF;
2625 : :
2626 [ + + ]: 915 : if (*ptr == ']')
2627 : : {
2628 : 106 : *flags |= RANGE_UB_INC;
2629 : 106 : ptr++;
2630 : 106 : }
2631 [ + + ]: 809 : else if (*ptr == ')')
2632 : 805 : ptr++;
2633 : : else /* must be a comma */
2634 [ + + ]: 4 : 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 [ + + + + ]: 916 : while (*ptr != '\0' && isspace((unsigned char) *ptr))
2642 : 5 : ptr++;
2643 : :
2644 [ + + ]: 911 : if (*ptr != '\0')
2645 [ + + ]: 6 : 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 : 905 : return true;
2652 : 1008 : }
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 : 0 : range_parse_bound(const char *string, const char *ptr,
2671 : : char **bound_str, bool *infinite, Node *escontext)
2672 : : {
2673 : 0 : StringInfoData buf;
2674 : :
2675 : : /* Check for null: completely empty input means null */
2676 [ # # # # : 0 : if (*ptr == ',' || *ptr == ')' || *ptr == ']')
# # ]
2677 : : {
2678 : 0 : *bound_str = NULL;
2679 : 0 : *infinite = true;
2680 : 0 : }
2681 : : else
2682 : : {
2683 : : /* Extract string for this bound */
2684 : 0 : bool inquote = false;
2685 : :
2686 : 0 : initStringInfo(&buf);
2687 [ # # # # : 0 : while (inquote || !(*ptr == ',' || *ptr == ')' || *ptr == ']'))
# # # # ]
2688 : : {
2689 : 0 : char ch = *ptr++;
2690 : :
2691 [ # # ]: 0 : if (ch == '\0')
2692 [ # # ]: 0 : ereturn(escontext, NULL,
2693 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
2694 : : errmsg("malformed range literal: \"%s\"",
2695 : : string),
2696 : : errdetail("Unexpected end of input.")));
2697 [ # # ]: 0 : if (ch == '\\')
2698 : : {
2699 [ # # ]: 0 : 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 : 0 : appendStringInfoChar(&buf, *ptr++);
2706 : 0 : }
2707 [ # # ]: 0 : else if (ch == '"')
2708 : : {
2709 [ # # ]: 0 : if (!inquote)
2710 : 0 : inquote = true;
2711 [ # # ]: 0 : else if (*ptr == '"')
2712 : : {
2713 : : /* doubled quote within quote sequence */
2714 : 0 : appendStringInfoChar(&buf, *ptr++);
2715 : 0 : }
2716 : : else
2717 : 0 : inquote = false;
2718 : 0 : }
2719 : : else
2720 : 0 : appendStringInfoChar(&buf, ch);
2721 [ # # ]: 0 : }
2722 : :
2723 : 0 : *bound_str = buf.data;
2724 : 0 : *infinite = false;
2725 [ # # ]: 0 : }
2726 : :
2727 : 0 : return ptr;
2728 : 0 : }
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 : 951 : range_deparse(char flags, const char *lbound_str, const char *ubound_str)
2740 : : {
2741 : 951 : StringInfoData buf;
2742 : :
2743 [ + + ]: 951 : if (flags & RANGE_EMPTY)
2744 : 44 : return pstrdup(RANGE_EMPTY_LITERAL);
2745 : :
2746 : 907 : initStringInfo(&buf);
2747 : :
2748 : 907 : appendStringInfoChar(&buf, (flags & RANGE_LB_INC) ? '[' : '(');
2749 : :
2750 [ + + ]: 907 : if (RANGE_HAS_LBOUND(flags))
2751 : 774 : appendStringInfoString(&buf, range_bound_escape(lbound_str));
2752 : :
2753 : 907 : appendStringInfoChar(&buf, ',');
2754 : :
2755 [ + + ]: 907 : if (RANGE_HAS_UBOUND(flags))
2756 : 751 : appendStringInfoString(&buf, range_bound_escape(ubound_str));
2757 : :
2758 : 907 : appendStringInfoChar(&buf, (flags & RANGE_UB_INC) ? ']' : ')');
2759 : :
2760 : 907 : return buf.data;
2761 : 951 : }
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 : 0 : range_bound_escape(const char *value)
2770 : : {
2771 : 0 : bool nq;
2772 : 0 : const char *ptr;
2773 : 0 : StringInfoData buf;
2774 : :
2775 : 0 : initStringInfo(&buf);
2776 : :
2777 : : /* Detect whether we need double quotes for this value */
2778 : 0 : nq = (value[0] == '\0'); /* force quotes for empty string */
2779 [ # # ]: 0 : for (ptr = value; *ptr; ptr++)
2780 : : {
2781 : 0 : char ch = *ptr;
2782 : :
2783 [ # # # # ]: 0 : if (ch == '"' || ch == '\\' ||
2784 [ # # # # ]: 0 : ch == '(' || ch == ')' ||
2785 [ # # # # ]: 0 : ch == '[' || ch == ']' ||
2786 [ # # # # ]: 0 : ch == ',' ||
2787 : 0 : isspace((unsigned char) ch))
2788 : : {
2789 : 0 : nq = true;
2790 : 0 : break;
2791 : : }
2792 [ # # # ]: 0 : }
2793 : :
2794 : : /* And emit the string */
2795 [ # # ]: 0 : if (nq)
2796 : 0 : appendStringInfoChar(&buf, '"');
2797 [ # # ]: 0 : for (ptr = value; *ptr; ptr++)
2798 : : {
2799 : 0 : char ch = *ptr;
2800 : :
2801 [ # # # # ]: 0 : if (ch == '"' || ch == '\\')
2802 : 0 : appendStringInfoChar(&buf, ch);
2803 : 0 : appendStringInfoChar(&buf, ch);
2804 : 0 : }
2805 [ # # ]: 0 : if (nq)
2806 : 0 : appendStringInfoChar(&buf, '"');
2807 : :
2808 : 0 : return buf.data;
2809 : 0 : }
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 : 80292 : range_contains_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
2819 : : {
2820 : 80292 : RangeBound lower1;
2821 : 80292 : RangeBound upper1;
2822 : 80292 : bool empty1;
2823 : 80292 : RangeBound lower2;
2824 : 80292 : RangeBound upper2;
2825 : 80292 : bool empty2;
2826 : :
2827 : : /* Different types should be prevented by ANYRANGE matching rules */
2828 [ + - ]: 80292 : if (RangeTypeGetOid(r1) != RangeTypeGetOid(r2))
2829 [ # # # # ]: 0 : elog(ERROR, "range types do not match");
2830 : :
2831 : 80292 : range_deserialize(typcache, r1, &lower1, &upper1, &empty1);
2832 : 80292 : range_deserialize(typcache, r2, &lower2, &upper2, &empty2);
2833 : :
2834 : : /* If either range is empty, the answer is easy */
2835 [ + + ]: 80292 : if (empty2)
2836 : 52452 : return true;
2837 [ + + ]: 27840 : else if (empty1)
2838 : 2261 : return false;
2839 : :
2840 : : /* Else we must have lower1 <= lower2 and upper1 >= upper2 */
2841 [ + + ]: 25579 : if (range_cmp_bounds(typcache, &lower1, &lower2) > 0)
2842 : 12362 : return false;
2843 [ + + ]: 13217 : if (range_cmp_bounds(typcache, &upper1, &upper2) < 0)
2844 : 11840 : return false;
2845 : :
2846 : 1377 : return true;
2847 : 80292 : }
2848 : :
2849 : : bool
2850 : 20074 : range_contained_by_internal(TypeCacheEntry *typcache, const RangeType *r1, const RangeType *r2)
2851 : : {
2852 : 20074 : return range_contains_internal(typcache, r2, r1);
2853 : : }
2854 : :
2855 : : /*
2856 : : * Test whether range r contains a specific element value.
2857 : : */
2858 : : bool
2859 : 14839 : range_contains_elem_internal(TypeCacheEntry *typcache, const RangeType *r, Datum val)
2860 : : {
2861 : 14839 : RangeBound lower;
2862 : 14839 : RangeBound upper;
2863 : 14839 : bool empty;
2864 : 14839 : int32 cmp;
2865 : :
2866 : 14839 : range_deserialize(typcache, r, &lower, &upper, &empty);
2867 : :
2868 [ + + ]: 14839 : if (empty)
2869 : 2144 : return false;
2870 : :
2871 [ + + ]: 12695 : if (!lower.infinite)
2872 : : {
2873 : 23972 : cmp = DatumGetInt32(FunctionCall2Coll(&typcache->rng_cmp_proc_finfo,
2874 : 11986 : typcache->rng_collation,
2875 : 11986 : lower.val, val));
2876 [ + + ]: 11986 : if (cmp > 0)
2877 : 11594 : return false;
2878 [ + + + - ]: 392 : if (cmp == 0 && !lower.inclusive)
2879 : 0 : return false;
2880 : 392 : }
2881 : :
2882 [ + + ]: 1101 : if (!upper.infinite)
2883 : : {
2884 : 2176 : cmp = DatumGetInt32(FunctionCall2Coll(&typcache->rng_cmp_proc_finfo,
2885 : 1088 : typcache->rng_collation,
2886 : 1088 : upper.val, val));
2887 [ + + ]: 1088 : if (cmp < 0)
2888 : 80 : return false;
2889 [ - + # # ]: 1008 : if (cmp == 0 && !upper.inclusive)
2890 : 0 : return false;
2891 : 1008 : }
2892 : :
2893 : 1021 : return true;
2894 : 14839 : }
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 : 0 : datum_compute_size(Size data_length, Datum val, bool typbyval, char typalign,
2916 : : int16 typlen, char typstorage)
2917 : : {
2918 [ # # # # : 0 : if (TYPE_IS_PACKABLE(typlen, typstorage) &&
# # ]
2919 : 0 : 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 : 0 : data_length += VARATT_CONVERTED_SHORT_SIZE(DatumGetPointer(val));
2926 : 0 : }
2927 : : else
2928 : : {
2929 [ # # # # : 0 : data_length = att_align_datum(data_length, typalign, typlen, val);
# # # # #
# # # ]
2930 [ # # # # : 0 : data_length = att_addlength_datum(data_length, typlen, val);
# # ]
2931 : : }
2932 : :
2933 : 0 : 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 char *
2941 : 0 : datum_write(char *ptr, Datum datum, bool typbyval, char typalign,
2942 : : int16 typlen, char typstorage)
2943 : : {
2944 : 0 : Size data_length;
2945 : :
2946 [ # # ]: 0 : if (typbyval)
2947 : : {
2948 : : /* pass-by-value */
2949 [ # # # # : 0 : ptr = (char *) att_align_nominal(ptr, typalign);
# # # # ]
2950 : 0 : store_att_byval(ptr, datum, typlen);
2951 : 0 : data_length = typlen;
2952 : 0 : }
2953 [ # # ]: 0 : else if (typlen == -1)
2954 : : {
2955 : : /* varlena */
2956 : 0 : Pointer val = DatumGetPointer(datum);
2957 : :
2958 [ # # ]: 0 : 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 : 0 : data_length = 0; /* keep compiler quiet */
2966 : 0 : }
2967 [ # # ]: 0 : else if (VARATT_IS_SHORT(val))
2968 : : {
2969 : : /* no alignment for short varlenas */
2970 : 0 : data_length = VARSIZE_SHORT(val);
2971 : 0 : memcpy(ptr, val, data_length);
2972 : 0 : }
2973 [ # # # # : 0 : else if (TYPE_IS_PACKABLE(typlen, typstorage) &&
# # ]
2974 : 0 : VARATT_CAN_MAKE_SHORT(val))
2975 : : {
2976 : : /* convert to short varlena -- no alignment */
2977 : 0 : data_length = VARATT_CONVERTED_SHORT_SIZE(val);
2978 : 0 : SET_VARSIZE_SHORT(ptr, data_length);
2979 : 0 : memcpy(ptr + 1, VARDATA(val), data_length - 1);
2980 : 0 : }
2981 : : else
2982 : : {
2983 : : /* full 4-byte header varlena */
2984 [ # # # # : 0 : ptr = (char *) att_align_nominal(ptr, typalign);
# # # # ]
2985 : 0 : data_length = VARSIZE(val);
2986 : 0 : memcpy(ptr, val, data_length);
2987 : : }
2988 : 0 : }
2989 [ # # ]: 0 : else if (typlen == -2)
2990 : : {
2991 : : /* cstring ... never needs alignment */
2992 [ # # ]: 0 : Assert(typalign == TYPALIGN_CHAR);
2993 : 0 : data_length = strlen(DatumGetCString(datum)) + 1;
2994 : 0 : memcpy(ptr, DatumGetPointer(datum), data_length);
2995 : 0 : }
2996 : : else
2997 : : {
2998 : : /* fixed-length pass-by-reference */
2999 [ # # # # : 0 : ptr = (char *) att_align_nominal(ptr, typalign);
# # # # ]
3000 [ # # ]: 0 : Assert(typlen > 0);
3001 : 0 : data_length = typlen;
3002 : 0 : memcpy(ptr, DatumGetPointer(datum), data_length);
3003 : : }
3004 : :
3005 : 0 : ptr += data_length;
3006 : :
3007 : 0 : return ptr;
3008 : 0 : }
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 : 0 : find_simplified_clause(PlannerInfo *root, Expr *rangeExpr, Expr *elemExpr)
3019 : : {
3020 : 0 : RangeType *range;
3021 : 0 : TypeCacheEntry *rangetypcache;
3022 : 0 : RangeBound lower;
3023 : 0 : RangeBound upper;
3024 : 0 : bool empty;
3025 : :
3026 : : /* can't do anything unless the range is a non-null constant */
3027 [ # # # # ]: 0 : if (!IsA(rangeExpr, Const) || ((Const *) rangeExpr)->constisnull)
3028 : 0 : return NULL;
3029 : 0 : range = DatumGetRangeTypeP(((Const *) rangeExpr)->constvalue);
3030 : :
3031 : 0 : rangetypcache = lookup_type_cache(RangeTypeGetOid(range),
3032 : : TYPECACHE_RANGE_INFO);
3033 [ # # ]: 0 : if (rangetypcache->rngelemtype == NULL)
3034 [ # # # # ]: 0 : elog(ERROR, "type %u is not a range type", RangeTypeGetOid(range));
3035 : :
3036 : 0 : range_deserialize(rangetypcache, range, &lower, &upper, &empty);
3037 : :
3038 [ # # ]: 0 : if (empty)
3039 : : {
3040 : : /* if the range is empty, then there can be no matches */
3041 : 0 : return makeBoolConst(false, false);
3042 : : }
3043 [ # # # # ]: 0 : else if (lower.infinite && upper.infinite)
3044 : : {
3045 : : /* the range has infinite bounds, so it matches everything */
3046 : 0 : return makeBoolConst(true, false);
3047 : : }
3048 : : else
3049 : : {
3050 : : /* at least one bound is available, we have something to work with */
3051 : 0 : TypeCacheEntry *elemTypcache = rangetypcache->rngelemtype;
3052 : 0 : Oid opfamily = rangetypcache->rng_opfamily;
3053 : 0 : Oid rng_collation = rangetypcache->rng_collation;
3054 : 0 : Expr *lowerExpr = NULL;
3055 : 0 : Expr *upperExpr = NULL;
3056 : :
3057 [ # # # # ]: 0 : 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 : 0 : QualCost eval_cost;
3066 : :
3067 [ # # ]: 0 : if (contain_volatile_functions((Node *) elemExpr))
3068 : 0 : 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 [ # # ]: 0 : if (contain_subplans((Node *) elemExpr))
3077 : 0 : return NULL;
3078 : 0 : cost_qual_eval_node(&eval_cost, (Node *) elemExpr, root);
3079 [ # # # # ]: 0 : if (eval_cost.startup + eval_cost.per_tuple >
3080 : 0 : 10 * cpu_operator_cost)
3081 : 0 : return NULL;
3082 [ # # ]: 0 : }
3083 : :
3084 : : /* Okay, try to build boundary comparison expressions */
3085 [ # # ]: 0 : if (!lower.infinite)
3086 : : {
3087 : 0 : lowerExpr = build_bound_expr(elemExpr,
3088 : 0 : lower.val,
3089 : : true,
3090 : 0 : lower.inclusive,
3091 : 0 : elemTypcache,
3092 : 0 : opfamily,
3093 : 0 : rng_collation);
3094 [ # # ]: 0 : if (lowerExpr == NULL)
3095 : 0 : return NULL;
3096 : 0 : }
3097 : :
3098 [ # # ]: 0 : if (!upper.infinite)
3099 : : {
3100 : : /* Copy the elemExpr if we need two copies */
3101 [ # # ]: 0 : if (!lower.infinite)
3102 : 0 : elemExpr = copyObject(elemExpr);
3103 : 0 : upperExpr = build_bound_expr(elemExpr,
3104 : 0 : upper.val,
3105 : : false,
3106 : 0 : upper.inclusive,
3107 : 0 : elemTypcache,
3108 : 0 : opfamily,
3109 : 0 : rng_collation);
3110 [ # # ]: 0 : if (upperExpr == NULL)
3111 : 0 : return NULL;
3112 : 0 : }
3113 : :
3114 [ # # # # ]: 0 : if (lowerExpr != NULL && upperExpr != NULL)
3115 : 0 : return (Node *) make_andclause(list_make2(lowerExpr, upperExpr));
3116 [ # # ]: 0 : else if (lowerExpr != NULL)
3117 : 0 : return (Node *) lowerExpr;
3118 [ # # ]: 0 : else if (upperExpr != NULL)
3119 : 0 : return (Node *) upperExpr;
3120 : : else
3121 : : {
3122 : 0 : Assert(false);
3123 : 0 : return NULL;
3124 : : }
3125 : 0 : }
3126 : 0 : }
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 : 0 : build_bound_expr(Expr *elemExpr, Datum val,
3141 : : bool isLowerBound, bool isInclusive,
3142 : : TypeCacheEntry *typeCache,
3143 : : Oid opfamily, Oid rng_collation)
3144 : : {
3145 : 0 : Oid elemType = typeCache->type_id;
3146 : 0 : int16 elemTypeLen = typeCache->typlen;
3147 : 0 : bool elemByValue = typeCache->typbyval;
3148 : 0 : Oid elemCollation = typeCache->typcollation;
3149 : 0 : int16 strategy;
3150 : 0 : Oid oproid;
3151 : 0 : Expr *constExpr;
3152 : :
3153 : : /* Identify the comparison operator to use */
3154 [ # # ]: 0 : if (isLowerBound)
3155 : 0 : strategy = isInclusive ? BTGreaterEqualStrategyNumber : BTGreaterStrategyNumber;
3156 : : else
3157 : 0 : 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 : 0 : oproid = get_opfamily_member(opfamily, elemType, elemType, strategy);
3164 : :
3165 : : /* We don't really expect failure here, but just in case ... */
3166 [ # # ]: 0 : if (!OidIsValid(oproid))
3167 : 0 : return NULL;
3168 : :
3169 : : /* OK, convert "val" to a full-fledged Const node, and make the OpExpr */
3170 : 0 : constExpr = (Expr *) makeConst(elemType,
3171 : : -1,
3172 : 0 : elemCollation,
3173 : 0 : elemTypeLen,
3174 : 0 : val,
3175 : : false,
3176 : 0 : elemByValue);
3177 : :
3178 : 0 : return make_opclause(oproid,
3179 : : BOOLOID,
3180 : : false,
3181 : 0 : elemExpr,
3182 : 0 : constExpr,
3183 : : InvalidOid,
3184 : 0 : rng_collation);
3185 : 0 : }
|