forked from postgres/postgres
/
multirangetypes.c
2791 lines (2335 loc) · 72.6 KB
/
multirangetypes.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-------------------------------------------------------------------------
*
* multirangetypes.c
* I/O functions, operators, and support functions for multirange types.
*
* The stored (serialized) format of a multirange value is:
*
* 12 bytes: MultirangeType struct including varlena header, multirange
* type's OID and the number of ranges in the multirange.
* 4 * (rangesCount - 1) bytes: 32-bit items pointing to the each range
* in the multirange starting from
* the second one.
* 1 * rangesCount bytes : 8-bit flags for each range in the multirange
* The rest of the multirange are range bound values pointed by multirange
* items.
*
* Majority of items contain lengths of corresponding range bound values.
* Thanks to that items are typically low numbers. This makes multiranges
* compression-friendly. Every MULTIRANGE_ITEM_OFFSET_STRIDE item contains
* an offset of the corresponding range bound values. That allows fast lookups
* for a particular range index. Offsets are counted starting from the end of
* flags aligned to the bound type.
*
* Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/utils/adt/multirangetypes.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/tupmacs.h"
#include "common/hashfn.h"
#include "lib/stringinfo.h"
#include "libpq/pqformat.h"
#include "miscadmin.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/rangetypes.h"
#include "utils/multirangetypes.h"
#include "utils/array.h"
#include "utils/memutils.h"
/* fn_extra cache entry for one of the range I/O functions */
typedef struct MultirangeIOData
{
TypeCacheEntry *typcache; /* multirange type's typcache entry */
FmgrInfo typioproc; /* range type's I/O proc */
Oid typioparam; /* range type's I/O parameter */
} MultirangeIOData;
typedef enum
{
MULTIRANGE_BEFORE_RANGE,
MULTIRANGE_IN_RANGE,
MULTIRANGE_IN_RANGE_ESCAPED,
MULTIRANGE_IN_RANGE_QUOTED,
MULTIRANGE_IN_RANGE_QUOTED_ESCAPED,
MULTIRANGE_AFTER_RANGE,
MULTIRANGE_FINISHED,
} MultirangeParseState;
/*
* Macros for accessing past MultirangeType parts of multirange: items, flags
* and boundaries.
*/
#define MultirangeGetItemsPtr(mr) ((uint32 *) ((Pointer) (mr) + \
sizeof(MultirangeType)))
#define MultirangeGetFlagsPtr(mr) ((uint8 *) ((Pointer) (mr) + \
sizeof(MultirangeType) + ((mr)->rangeCount - 1) * sizeof(uint32)))
#define MultirangeGetBoundariesPtr(mr, align) ((Pointer) (mr) + \
att_align_nominal(sizeof(MultirangeType) + \
((mr)->rangeCount - 1) * sizeof(uint32) + \
(mr)->rangeCount * sizeof(uint8), (align)))
#define MULTIRANGE_ITEM_OFF_BIT 0x80000000
#define MULTIRANGE_ITEM_GET_OFFLEN(item) ((item) & 0x7FFFFFFF)
#define MULTIRANGE_ITEM_HAS_OFF(item) ((item) & MULTIRANGE_ITEM_OFF_BIT)
#define MULTIRANGE_ITEM_OFFSET_STRIDE 4
typedef int (*multirange_bsearch_comparison) (TypeCacheEntry *typcache,
RangeBound *lower,
RangeBound *upper,
void *key,
bool *match);
static MultirangeIOData *get_multirange_io_data(FunctionCallInfo fcinfo,
Oid mltrngtypid,
IOFuncSelector func);
static int32 multirange_canonicalize(TypeCacheEntry *rangetyp,
int32 input_range_count,
RangeType **ranges);
/*
*----------------------------------------------------------
* I/O FUNCTIONS
*----------------------------------------------------------
*/
/*
* Converts string to multirange.
*
* We expect curly brackets to bound the list, with zero or more ranges
* separated by commas. We accept whitespace anywhere: before/after our
* brackets and around the commas. Ranges can be the empty literal or some
* stuff inside parens/brackets. Mostly we delegate parsing the individual
* range contents to range_in, but we have to detect quoting and
* backslash-escaping which can happen for range bounds. Backslashes can
* escape something inside or outside a quoted string, and a quoted string
* can escape quote marks with either backslashes or double double-quotes.
*/
Datum
multirange_in(PG_FUNCTION_ARGS)
{
char *input_str = PG_GETARG_CSTRING(0);
Oid mltrngtypoid = PG_GETARG_OID(1);
Oid typmod = PG_GETARG_INT32(2);
TypeCacheEntry *rangetyp;
int32 ranges_seen = 0;
int32 range_count = 0;
int32 range_capacity = 8;
RangeType *range;
RangeType **ranges = palloc(range_capacity * sizeof(RangeType *));
MultirangeIOData *cache;
MultirangeType *ret;
MultirangeParseState parse_state;
const char *ptr = input_str;
const char *range_str_begin = NULL;
int32 range_str_len;
char *range_str;
cache = get_multirange_io_data(fcinfo, mltrngtypoid, IOFunc_input);
rangetyp = cache->typcache->rngtype;
/* consume whitespace */
while (*ptr != '\0' && isspace((unsigned char) *ptr))
ptr++;
if (*ptr == '{')
ptr++;
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("malformed multirange literal: \"%s\"",
input_str),
errdetail("Missing left brace.")));
/* consume ranges */
parse_state = MULTIRANGE_BEFORE_RANGE;
for (; parse_state != MULTIRANGE_FINISHED; ptr++)
{
char ch = *ptr;
if (ch == '\0')
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("malformed multirange literal: \"%s\"",
input_str),
errdetail("Unexpected end of input.")));
/* skip whitespace */
if (isspace((unsigned char) ch))
continue;
switch (parse_state)
{
case MULTIRANGE_BEFORE_RANGE:
if (ch == '[' || ch == '(')
{
range_str_begin = ptr;
parse_state = MULTIRANGE_IN_RANGE;
}
else if (ch == '}' && ranges_seen == 0)
parse_state = MULTIRANGE_FINISHED;
else if (pg_strncasecmp(ptr, RANGE_EMPTY_LITERAL,
strlen(RANGE_EMPTY_LITERAL)) == 0)
{
ranges_seen++;
/* nothing to do with an empty range */
ptr += strlen(RANGE_EMPTY_LITERAL) - 1;
parse_state = MULTIRANGE_AFTER_RANGE;
}
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("malformed multirange literal: \"%s\"",
input_str),
errdetail("Expected range start.")));
break;
case MULTIRANGE_IN_RANGE:
if (ch == ']' || ch == ')')
{
range_str_len = ptr - range_str_begin + 1;
range_str = pnstrdup(range_str_begin, range_str_len);
if (range_capacity == range_count)
{
range_capacity *= 2;
ranges = (RangeType **)
repalloc(ranges, range_capacity * sizeof(RangeType *));
}
ranges_seen++;
range = DatumGetRangeTypeP(InputFunctionCall(&cache->typioproc,
range_str,
cache->typioparam,
typmod));
if (!RangeIsEmpty(range))
ranges[range_count++] = range;
parse_state = MULTIRANGE_AFTER_RANGE;
}
else
{
if (ch == '"')
parse_state = MULTIRANGE_IN_RANGE_QUOTED;
else if (ch == '\\')
parse_state = MULTIRANGE_IN_RANGE_ESCAPED;
/*
* We will include this character into range_str once we
* find the end of the range value.
*/
}
break;
case MULTIRANGE_IN_RANGE_ESCAPED:
/*
* We will include this character into range_str once we find
* the end of the range value.
*/
parse_state = MULTIRANGE_IN_RANGE;
break;
case MULTIRANGE_IN_RANGE_QUOTED:
if (ch == '"')
if (*(ptr + 1) == '"')
{
/* two quote marks means an escaped quote mark */
ptr++;
}
else
parse_state = MULTIRANGE_IN_RANGE;
else if (ch == '\\')
parse_state = MULTIRANGE_IN_RANGE_QUOTED_ESCAPED;
/*
* We will include this character into range_str once we find
* the end of the range value.
*/
break;
case MULTIRANGE_AFTER_RANGE:
if (ch == ',')
parse_state = MULTIRANGE_BEFORE_RANGE;
else if (ch == '}')
parse_state = MULTIRANGE_FINISHED;
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("malformed multirange literal: \"%s\"",
input_str),
errdetail("Expected comma or end of multirange.")));
break;
case MULTIRANGE_IN_RANGE_QUOTED_ESCAPED:
/*
* We will include this character into range_str once we find
* the end of the range value.
*/
parse_state = MULTIRANGE_IN_RANGE_QUOTED;
break;
default:
elog(ERROR, "unknown parse state: %d", parse_state);
}
}
/* consume whitespace */
while (*ptr != '\0' && isspace((unsigned char) *ptr))
ptr++;
if (*ptr != '\0')
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("malformed multirange literal: \"%s\"",
input_str),
errdetail("Junk after right brace.")));
ret = make_multirange(mltrngtypoid, rangetyp, range_count, ranges);
PG_RETURN_MULTIRANGE_P(ret);
}
Datum
multirange_out(PG_FUNCTION_ARGS)
{
MultirangeType *multirange = PG_GETARG_MULTIRANGE_P(0);
Oid mltrngtypoid = MultirangeTypeGetOid(multirange);
MultirangeIOData *cache;
StringInfoData buf;
RangeType *range;
char *rangeStr;
int32 range_count;
int32 i;
RangeType **ranges;
cache = get_multirange_io_data(fcinfo, mltrngtypoid, IOFunc_output);
initStringInfo(&buf);
appendStringInfoChar(&buf, '{');
multirange_deserialize(cache->typcache->rngtype, multirange, &range_count, &ranges);
for (i = 0; i < range_count; i++)
{
if (i > 0)
appendStringInfoChar(&buf, ',');
range = ranges[i];
rangeStr = OutputFunctionCall(&cache->typioproc, RangeTypePGetDatum(range));
appendStringInfoString(&buf, rangeStr);
}
appendStringInfoChar(&buf, '}');
PG_RETURN_CSTRING(buf.data);
}
/*
* Binary representation: First a int32-sized count of ranges, followed by
* ranges in their native binary representation.
*/
Datum
multirange_recv(PG_FUNCTION_ARGS)
{
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
Oid mltrngtypoid = PG_GETARG_OID(1);
int32 typmod = PG_GETARG_INT32(2);
MultirangeIOData *cache;
uint32 range_count;
RangeType **ranges;
MultirangeType *ret;
StringInfoData tmpbuf;
cache = get_multirange_io_data(fcinfo, mltrngtypoid, IOFunc_receive);
range_count = pq_getmsgint(buf, 4);
ranges = palloc(range_count * sizeof(RangeType *));
initStringInfo(&tmpbuf);
for (int i = 0; i < range_count; i++)
{
uint32 range_len = pq_getmsgint(buf, 4);
const char *range_data = pq_getmsgbytes(buf, range_len);
resetStringInfo(&tmpbuf);
appendBinaryStringInfo(&tmpbuf, range_data, range_len);
ranges[i] = DatumGetRangeTypeP(ReceiveFunctionCall(&cache->typioproc,
&tmpbuf,
cache->typioparam,
typmod));
}
pfree(tmpbuf.data);
pq_getmsgend(buf);
ret = make_multirange(mltrngtypoid, cache->typcache->rngtype,
range_count, ranges);
PG_RETURN_MULTIRANGE_P(ret);
}
Datum
multirange_send(PG_FUNCTION_ARGS)
{
MultirangeType *multirange = PG_GETARG_MULTIRANGE_P(0);
Oid mltrngtypoid = MultirangeTypeGetOid(multirange);
StringInfo buf = makeStringInfo();
RangeType **ranges;
int32 range_count;
MultirangeIOData *cache;
cache = get_multirange_io_data(fcinfo, mltrngtypoid, IOFunc_send);
/* construct output */
pq_begintypsend(buf);
pq_sendint32(buf, multirange->rangeCount);
multirange_deserialize(cache->typcache->rngtype, multirange, &range_count, &ranges);
for (int i = 0; i < range_count; i++)
{
Datum range;
range = RangeTypePGetDatum(ranges[i]);
range = PointerGetDatum(SendFunctionCall(&cache->typioproc, range));
pq_sendint32(buf, VARSIZE(range) - VARHDRSZ);
pq_sendbytes(buf, VARDATA(range), VARSIZE(range) - VARHDRSZ);
}
PG_RETURN_BYTEA_P(pq_endtypsend(buf));
}
/*
* get_multirange_io_data: get cached information needed for multirange type I/O
*
* The multirange I/O functions need a bit more cached info than other multirange
* functions, so they store a MultirangeIOData struct in fn_extra, not just a
* pointer to a type cache entry.
*/
static MultirangeIOData *
get_multirange_io_data(FunctionCallInfo fcinfo, Oid mltrngtypid, IOFuncSelector func)
{
MultirangeIOData *cache = (MultirangeIOData *) fcinfo->flinfo->fn_extra;
if (cache == NULL || cache->typcache->type_id != mltrngtypid)
{
Oid typiofunc;
int16 typlen;
bool typbyval;
char typalign;
char typdelim;
cache = (MultirangeIOData *) MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
sizeof(MultirangeIOData));
cache->typcache = lookup_type_cache(mltrngtypid, TYPECACHE_MULTIRANGE_INFO);
if (cache->typcache->rngtype == NULL)
elog(ERROR, "type %u is not a multirange type", mltrngtypid);
/* get_type_io_data does more than we need, but is convenient */
get_type_io_data(cache->typcache->rngtype->type_id,
func,
&typlen,
&typbyval,
&typalign,
&typdelim,
&cache->typioparam,
&typiofunc);
if (!OidIsValid(typiofunc))
{
/* this could only happen for receive or send */
if (func == IOFunc_receive)
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("no binary input function available for type %s",
format_type_be(cache->typcache->rngtype->type_id))));
else
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("no binary output function available for type %s",
format_type_be(cache->typcache->rngtype->type_id))));
}
fmgr_info_cxt(typiofunc, &cache->typioproc,
fcinfo->flinfo->fn_mcxt);
fcinfo->flinfo->fn_extra = (void *) cache;
}
return cache;
}
/*
* Converts a list of arbitrary ranges into a list that is sorted and merged.
* Changes the contents of `ranges`.
*
* Returns the number of slots actually used, which may be less than
* input_range_count but never more.
*
* We assume that no input ranges are null, but empties are okay.
*/
static int32
multirange_canonicalize(TypeCacheEntry *rangetyp, int32 input_range_count,
RangeType **ranges)
{
RangeType *lastRange = NULL;
RangeType *currentRange;
int32 i;
int32 output_range_count = 0;
/* Sort the ranges so we can find the ones that overlap/meet. */
qsort_arg(ranges, input_range_count, sizeof(RangeType *), range_compare,
rangetyp);
/* Now merge where possible: */
for (i = 0; i < input_range_count; i++)
{
currentRange = ranges[i];
if (RangeIsEmpty(currentRange))
continue;
if (lastRange == NULL)
{
ranges[output_range_count++] = lastRange = currentRange;
continue;
}
/*
* range_adjacent_internal gives true if *either* A meets B or B meets
* A, which is not quite want we want, but we rely on the sorting
* above to rule out B meets A ever happening.
*/
if (range_adjacent_internal(rangetyp, lastRange, currentRange))
{
/* The two ranges touch (without overlap), so merge them: */
ranges[output_range_count - 1] = lastRange =
range_union_internal(rangetyp, lastRange, currentRange, false);
}
else if (range_before_internal(rangetyp, lastRange, currentRange))
{
/* There's a gap, so make a new entry: */
lastRange = ranges[output_range_count] = currentRange;
output_range_count++;
}
else
{
/* They must overlap, so merge them: */
ranges[output_range_count - 1] = lastRange =
range_union_internal(rangetyp, lastRange, currentRange, true);
}
}
return output_range_count;
}
/*
*----------------------------------------------------------
* SUPPORT FUNCTIONS
*
* These functions aren't in pg_proc, but are useful for
* defining new generic multirange functions in C.
*----------------------------------------------------------
*/
/*
* multirange_get_typcache: get cached information about a multirange type
*
* This is for use by multirange-related functions that follow the convention
* of using the fn_extra field as a pointer to the type cache entry for
* the multirange type. Functions that need to cache more information than
* that must fend for themselves.
*/
TypeCacheEntry *
multirange_get_typcache(FunctionCallInfo fcinfo, Oid mltrngtypid)
{
TypeCacheEntry *typcache = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
if (typcache == NULL ||
typcache->type_id != mltrngtypid)
{
typcache = lookup_type_cache(mltrngtypid, TYPECACHE_MULTIRANGE_INFO);
if (typcache->rngtype == NULL)
elog(ERROR, "type %u is not a multirange type", mltrngtypid);
fcinfo->flinfo->fn_extra = (void *) typcache;
}
return typcache;
}
/*
* Estimate size occupied by serialized multirange.
*/
static Size
multirange_size_estimate(TypeCacheEntry *rangetyp, int32 range_count,
RangeType **ranges)
{
char elemalign = rangetyp->rngelemtype->typalign;
Size size;
int32 i;
/*
* Count space for MultirangeType struct, items and flags.
*/
size = att_align_nominal(sizeof(MultirangeType) +
Max(range_count - 1, 0) * sizeof(uint32) +
range_count * sizeof(uint8), elemalign);
/* Count space for range bounds */
for (i = 0; i < range_count; i++)
size += att_align_nominal(VARSIZE(ranges[i]) -
sizeof(RangeType) -
sizeof(char), elemalign);
return size;
}
/*
* Write multirange data into pre-allocated space.
*/
static void
write_multirange_data(MultirangeType *multirange, TypeCacheEntry *rangetyp,
int32 range_count, RangeType **ranges)
{
uint32 *items;
uint32 prev_offset = 0;
uint8 *flags;
int32 i;
Pointer begin,
ptr;
char elemalign = rangetyp->rngelemtype->typalign;
items = MultirangeGetItemsPtr(multirange);
flags = MultirangeGetFlagsPtr(multirange);
ptr = begin = MultirangeGetBoundariesPtr(multirange, elemalign);
for (i = 0; i < range_count; i++)
{
uint32 len;
if (i > 0)
{
/*
* Every range, except the first one, has an item. Every
* MULTIRANGE_ITEM_OFFSET_STRIDE item contains an offset, others
* contain lengths.
*/
items[i - 1] = ptr - begin;
if ((i % MULTIRANGE_ITEM_OFFSET_STRIDE) != 0)
items[i - 1] -= prev_offset;
else
items[i - 1] |= MULTIRANGE_ITEM_OFF_BIT;
prev_offset = ptr - begin;
}
flags[i] = *((Pointer) ranges[i] + VARSIZE(ranges[i]) - sizeof(char));
len = VARSIZE(ranges[i]) - sizeof(RangeType) - sizeof(char);
memcpy(ptr, (Pointer) (ranges[i] + 1), len);
ptr += att_align_nominal(len, elemalign);
}
}
/*
* This serializes the multirange from a list of non-null ranges. It also
* sorts the ranges and merges any that touch. The ranges should already be
* detoasted, and there should be no NULLs. This should be used by most
* callers.
*
* Note that we may change the `ranges` parameter (the pointers, but not
* any already-existing RangeType contents).
*/
MultirangeType *
make_multirange(Oid mltrngtypoid, TypeCacheEntry *rangetyp, int32 range_count,
RangeType **ranges)
{
MultirangeType *multirange;
Size size;
/* Sort and merge input ranges. */
range_count = multirange_canonicalize(rangetyp, range_count, ranges);
/* Note: zero-fill is required here, just as in heap tuples */
size = multirange_size_estimate(rangetyp, range_count, ranges);
multirange = palloc0(size);
SET_VARSIZE(multirange, size);
/* Now fill in the datum */
multirange->multirangetypid = mltrngtypoid;
multirange->rangeCount = range_count;
write_multirange_data(multirange, rangetyp, range_count, ranges);
return multirange;
}
/*
* Get offset of bounds values of the i'th range in the multirange.
*/
static uint32
multirange_get_bounds_offset(const MultirangeType *multirange, int32 i)
{
uint32 *items = MultirangeGetItemsPtr(multirange);
uint32 offset = 0;
/*
* Summarize lengths till we meet an offset.
*/
while (i > 0)
{
offset += MULTIRANGE_ITEM_GET_OFFLEN(items[i - 1]);
if (MULTIRANGE_ITEM_HAS_OFF(items[i - 1]))
break;
i--;
}
return offset;
}
/*
* Fetch the i'th range from the multirange.
*/
RangeType *
multirange_get_range(TypeCacheEntry *rangetyp,
const MultirangeType *multirange, int i)
{
uint32 offset;
uint8 flags;
Pointer begin,
ptr;
int16 typlen = rangetyp->rngelemtype->typlen;
char typalign = rangetyp->rngelemtype->typalign;
uint32 len;
RangeType *range;
Assert(i < multirange->rangeCount);
offset = multirange_get_bounds_offset(multirange, i);
flags = MultirangeGetFlagsPtr(multirange)[i];
ptr = begin = MultirangeGetBoundariesPtr(multirange, typalign) + offset;
/*
* Calculate the size of bound values. In principle, we could get offset
* of the next range bound values and calculate accordingly. But range
* bound values are aligned, so we have to walk the values to get the
* exact size.
*/
if (RANGE_HAS_LBOUND(flags))
ptr = (Pointer) att_addlength_pointer(ptr, typlen, ptr);
if (RANGE_HAS_UBOUND(flags))
ptr = (Pointer) att_addlength_pointer(ptr, typlen, ptr);
len = (ptr - begin) + sizeof(RangeType) + sizeof(uint8);
range = palloc0(len);
SET_VARSIZE(range, len);
range->rangetypid = rangetyp->type_id;
memcpy(range + 1, begin, ptr - begin);
*((uint8 *) (range + 1) + (ptr - begin)) = flags;
return range;
}
/*
* Fetch bounds from the i'th range of the multirange. This is the shortcut for
* doing the same thing as multirange_get_range() + range_deserialize(), but
* performing fewer operations.
*/
void
multirange_get_bounds(TypeCacheEntry *rangetyp,
const MultirangeType *multirange,
uint32 i, RangeBound *lower, RangeBound *upper)
{
uint32 offset;
uint8 flags;
Pointer ptr;
int16 typlen = rangetyp->rngelemtype->typlen;
char typalign = rangetyp->rngelemtype->typalign;
bool typbyval = rangetyp->rngelemtype->typbyval;
Datum lbound;
Datum ubound;
Assert(i < multirange->rangeCount);
offset = multirange_get_bounds_offset(multirange, i);
flags = MultirangeGetFlagsPtr(multirange)[i];
ptr = MultirangeGetBoundariesPtr(multirange, typalign) + offset;
/* multirange can't contain empty ranges */
Assert((flags & RANGE_EMPTY) == 0);
/* fetch lower bound, if any */
if (RANGE_HAS_LBOUND(flags))
{
/* att_align_pointer cannot be necessary here */
lbound = fetch_att(ptr, typbyval, typlen);
ptr = (Pointer) att_addlength_pointer(ptr, typlen, ptr);
}
else
lbound = (Datum) 0;
/* fetch upper bound, if any */
if (RANGE_HAS_UBOUND(flags))
{
ptr = (Pointer) att_align_pointer(ptr, typalign, typlen, ptr);
ubound = fetch_att(ptr, typbyval, typlen);
/* no need for att_addlength_pointer */
}
else
ubound = (Datum) 0;
/* emit results */
lower->val = lbound;
lower->infinite = (flags & RANGE_LB_INF) != 0;
lower->inclusive = (flags & RANGE_LB_INC) != 0;
lower->lower = true;
upper->val = ubound;
upper->infinite = (flags & RANGE_UB_INF) != 0;
upper->inclusive = (flags & RANGE_UB_INC) != 0;
upper->lower = false;
}
/*
* Construct union range from the multirange.
*/
RangeType *
multirange_get_union_range(TypeCacheEntry *rangetyp,
const MultirangeType *mr)
{
RangeBound lower,
upper,
tmp;
if (MultirangeIsEmpty(mr))
return make_empty_range(rangetyp);
multirange_get_bounds(rangetyp, mr, 0, &lower, &tmp);
multirange_get_bounds(rangetyp, mr, mr->rangeCount - 1, &tmp, &upper);
return make_range(rangetyp, &lower, &upper, false);
}
/*
* multirange_deserialize: deconstruct a multirange value
*
* NB: the given multirange object must be fully detoasted; it cannot have a
* short varlena header.
*/
void
multirange_deserialize(TypeCacheEntry *rangetyp,
const MultirangeType *multirange, int32 *range_count,
RangeType ***ranges)
{
*range_count = multirange->rangeCount;
/* Convert each ShortRangeType into a RangeType */
if (*range_count > 0)
{
int i;
*ranges = palloc(*range_count * sizeof(RangeType *));
for (i = 0; i < *range_count; i++)
(*ranges)[i] = multirange_get_range(rangetyp, multirange, i);
}
else
{
*ranges = NULL;
}
}
MultirangeType *
make_empty_multirange(Oid mltrngtypoid, TypeCacheEntry *rangetyp)
{
return make_multirange(mltrngtypoid, rangetyp, 0, NULL);
}
/*
* Similar to range_overlaps_internal(), but takes range bounds instead of
* ranges as arguments.
*/
static bool
range_bounds_overlaps(TypeCacheEntry *typcache,
RangeBound *lower1, RangeBound *upper1,
RangeBound *lower2, RangeBound *upper2)
{
if (range_cmp_bounds(typcache, lower1, lower2) >= 0 &&
range_cmp_bounds(typcache, lower1, upper2) <= 0)
return true;
if (range_cmp_bounds(typcache, lower2, lower1) >= 0 &&
range_cmp_bounds(typcache, lower2, upper1) <= 0)
return true;
return false;
}
/*
* Similar to range_contains_internal(), but takes range bounds instead of
* ranges as arguments.
*/
static bool
range_bounds_contains(TypeCacheEntry *typcache,
RangeBound *lower1, RangeBound *upper1,
RangeBound *lower2, RangeBound *upper2)
{
if (range_cmp_bounds(typcache, lower1, lower2) <= 0 &&
range_cmp_bounds(typcache, upper1, upper2) >= 0)
return true;
return false;
}
/*
* Check if the given key matches any range in multirange using binary search.
* If the required range isn't found, that counts as a mismatch. When the
* required range is found, the comparison function can still report this as
* either match or mismatch. For instance, if we search for containment, we can
* found a range, which is overlapping but not containing the key range, and
* that would count as a mismatch.
*/
static bool
multirange_bsearch_match(TypeCacheEntry *typcache, const MultirangeType *mr,
void *key, multirange_bsearch_comparison cmp_func)
{
uint32 l,
u,
idx;
int comparison;
bool match = false;
l = 0;
u = mr->rangeCount;
while (l < u)
{
RangeBound lower,
upper;
idx = (l + u) / 2;
multirange_get_bounds(typcache, mr, idx, &lower, &upper);
comparison = (*cmp_func) (typcache, &lower, &upper, key, &match);
if (comparison < 0)
u = idx;
else if (comparison > 0)
l = idx + 1;
else
return match;
}
return false;
}
/*
*----------------------------------------------------------
* GENERIC FUNCTIONS
*----------------------------------------------------------
*/
/*
* Construct multirange value from zero or more ranges. Since this is a
* variadic function we get passed an array. The array must contain ranges
* that match our return value, and there must be no NULLs.
*/
Datum
multirange_constructor2(PG_FUNCTION_ARGS)
{
Oid mltrngtypid = get_fn_expr_rettype(fcinfo->flinfo);
Oid rngtypid;
TypeCacheEntry *typcache;
TypeCacheEntry *rangetyp;
ArrayType *rangeArray;
int range_count;
Datum *elements;
bool *nulls;
RangeType **ranges;
int dims;
int i;
typcache = multirange_get_typcache(fcinfo, mltrngtypid);
rangetyp = typcache->rngtype;
/*
* A no-arg invocation should call multirange_constructor0 instead, but
* returning an empty range is what that does.
*/
if (PG_NARGS() == 0)
PG_RETURN_MULTIRANGE_P(make_multirange(mltrngtypid, rangetyp, 0, NULL));
/*
* This check should be guaranteed by our signature, but let's do it just
* in case.
*/
if (PG_ARGISNULL(0))
elog(ERROR,
"multirange values cannot contain NULL members");
rangeArray = PG_GETARG_ARRAYTYPE_P(0);
dims = ARR_NDIM(rangeArray);
if (dims > 1)
ereport(ERROR,
(errcode(ERRCODE_CARDINALITY_VIOLATION),
errmsg("multiranges cannot be constructed from multi-dimensional arrays")));
rngtypid = ARR_ELEMTYPE(rangeArray);
if (rngtypid != rangetyp->type_id)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("type %u does not match constructor type", rngtypid)));
/*
* Be careful: we can still be called with zero ranges, like this:
* `int4multirange(variadic '{}'::int4range[])
*/
if (dims == 0)
{
range_count = 0;
ranges = NULL;
}
else
{
deconstruct_array(rangeArray, rngtypid, rangetyp->typlen, rangetyp->typbyval,
rangetyp->typalign, &elements, &nulls, &range_count);
ranges = palloc0(range_count * sizeof(RangeType *));
for (i = 0; i < range_count; i++)
{
if (nulls[i])
ereport(ERROR,
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
errmsg("multirange values cannot contain NULL members")));