Debian Codegraph @

contrib/pg_trgm/trgm_gist.c

raw
1 /*
2 * contrib/pg_trgm/trgm_gist.c
3 */
4 #include "postgres.h"
5
6 #include "access/reloptions.h"
7 #include "access/stratnum.h"
8 #include "fmgr.h"
9 #include "port/pg_bitutils.h"
10 #include "trgm.h"
11 #include "varatt.h"
12
13 /* gist_trgm_ops opclass options */
14 typedef struct
15 {
16 int32 vl_len_; /* varlena header (do not touch directly!) */
17 int siglen; /* signature length in bytes */
18 } TrgmGistOptions;
19
20 #define GET_SIGLEN() (PG_HAS_OPCLASS_OPTIONS() ? \
21 ((TrgmGistOptions *) PG_GET_OPCLASS_OPTIONS())->siglen : \
22 SIGLEN_DEFAULT)
23
24 typedef struct
25 {
26 /* most recent inputs to gtrgm_consistent */
27 StrategyNumber strategy;
28 text *query;
29 /* extracted trigrams for query */
30 TRGM *trigrams;
31 /* if a regex operator, the extracted graph */
32 TrgmPackedGraph *graph;
33
34 /*
35 * The "query" and "trigrams" are stored in the same palloc block as this
36 * cache struct, at MAXALIGN'ed offsets. The graph however isn't.
37 */
38 } gtrgm_consistent_cache;
39
40 #define GETENTRY(vec,pos) ((TRGM *) DatumGetPointer((vec)->vector[(pos)].key))
41
42
43 PG_FUNCTION_INFO_V1(gtrgm_in);
44 PG_FUNCTION_INFO_V1(gtrgm_out);
45 PG_FUNCTION_INFO_V1(gtrgm_compress);
46 PG_FUNCTION_INFO_V1(gtrgm_decompress);
47 PG_FUNCTION_INFO_V1(gtrgm_consistent);
48 PG_FUNCTION_INFO_V1(gtrgm_distance);
49 PG_FUNCTION_INFO_V1(gtrgm_union);
50 PG_FUNCTION_INFO_V1(gtrgm_same);
51 PG_FUNCTION_INFO_V1(gtrgm_penalty);
52 PG_FUNCTION_INFO_V1(gtrgm_picksplit);
53 PG_FUNCTION_INFO_V1(gtrgm_options);
54
55
56 Datum
57 gtrgm_in(PG_FUNCTION_ARGS)
58 {
59 ereport(ERROR,
60 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
61 errmsg("cannot accept a value of type %s", "gtrgm")));
62
63 PG_RETURN_VOID(); /* keep compiler quiet */
64 }
65
66 Datum
67 gtrgm_out(PG_FUNCTION_ARGS)
68 {
69 ereport(ERROR,
70 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
71 errmsg("cannot display a value of type %s", "gtrgm")));
72
73 PG_RETURN_VOID(); /* keep compiler quiet */
74 }
75
76 static TRGM *
77 gtrgm_alloc(bool isalltrue, int siglen, BITVECP sign)
78 {
79 int flag = SIGNKEY | (isalltrue ? ALLISTRUE : 0);
80 int size = CALCGTSIZE(flag, siglen);
81 TRGM *res = palloc(size);
82
83 SET_VARSIZE(res, size);
84 res->flag = flag;
85
86 if (!isalltrue)
87 {
88 if (sign)
89 memcpy(GETSIGN(res), sign, siglen);
90 else
91 memset(GETSIGN(res), 0, siglen);
92 }
93
94 return res;
95 }
96
97 static void
98 makesign(BITVECP sign, TRGM *a, int siglen)
99 {
100 int32 k,
101 len = ARRNELEM(a);
102 trgm *ptr = GETARR(a);
103 int32 tmp = 0;
104
105 MemSet(sign, 0, siglen);
106 SETBIT(sign, SIGLENBIT(siglen)); /* set last unused bit */
107 for (k = 0; k < len; k++)
108 {
109 CPTRGM(&tmp, ptr + k);
110 HASH(sign, tmp, siglen);
111 }
112 }
113
114 Datum
115 gtrgm_compress(PG_FUNCTION_ARGS)
116 {
117 GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
118 int siglen = GET_SIGLEN();
119 GISTENTRY *retval = entry;
120
121 if (entry->leafkey)
122 { /* trgm */
123 TRGM *res;
124 text *val = DatumGetTextPP(entry->key);
125
126 res = generate_trgm(VARDATA_ANY(val), VARSIZE_ANY_EXHDR(val));
127 retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
128 gistentryinit(*retval, PointerGetDatum(res),
129 entry->rel, entry->page,
130 entry->offset, false);
131 }
132 else if (ISSIGNKEY(DatumGetPointer(entry->key)) &&
133 !ISALLTRUE(DatumGetPointer(entry->key)))
134 {
135 int32 i;
136 TRGM *res;
137 BITVECP sign = GETSIGN(DatumGetPointer(entry->key));
138
139 LOOPBYTE(siglen)
140 {
141 if ((sign[i] & 0xff) != 0xff)
142 PG_RETURN_POINTER(retval);
143 }
144
145 res = gtrgm_alloc(true, siglen, sign);
146 retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
147 gistentryinit(*retval, PointerGetDatum(res),
148 entry->rel, entry->page,
149 entry->offset, false);
150 }
151 PG_RETURN_POINTER(retval);
152 }
153
154 Datum
155 gtrgm_decompress(PG_FUNCTION_ARGS)
156 {
157 GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
158 GISTENTRY *retval;
159 text *key;
160
161 key = DatumGetTextPP(entry->key);
162
163 if (key != (text *) DatumGetPointer(entry->key))
164 {
165 /* need to pass back the decompressed item */
166 retval = palloc(sizeof(GISTENTRY));
167 gistentryinit(*retval, PointerGetDatum(key),
168 entry->rel, entry->page, entry->offset, entry->leafkey);
169 PG_RETURN_POINTER(retval);
170 }
171 else
172 {
173 /* we can return the entry as-is */
174 PG_RETURN_POINTER(entry);
175 }
176 }
177
178 static int32
179 cnt_sml_sign_common(TRGM *qtrg, BITVECP sign, int siglen)
180 {
181 int32 count = 0;
182 int32 k,
183 len = ARRNELEM(qtrg);
184 trgm *ptr = GETARR(qtrg);
185 int32 tmp = 0;
186
187 for (k = 0; k < len; k++)
188 {
189 CPTRGM(&tmp, ptr + k);
190 count += GETBIT(sign, HASHVAL(tmp, siglen));
191 }
192
193 return count;
194 }
195
196 Datum
197 gtrgm_consistent(PG_FUNCTION_ARGS)
198 {
199 GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
200 text *query = PG_GETARG_TEXT_P(1);
201 StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
202
203 /* Oid subtype = PG_GETARG_OID(3); */
204 bool *recheck = (bool *) PG_GETARG_POINTER(4);
205 int siglen = GET_SIGLEN();
206 TRGM *key = (TRGM *) DatumGetPointer(entry->key);
207 TRGM *qtrg;
208 bool res;
209 Size querysize = VARSIZE(query);
210 gtrgm_consistent_cache *cache;
211 double nlimit;
212
213 /*
214 * We keep the extracted trigrams in cache, because trigram extraction is
215 * relatively CPU-expensive. When trying to reuse a cached value, check
216 * strategy number not just query itself, because trigram extraction
217 * depends on strategy.
218 *
219 * The cached structure is a single palloc chunk containing the
220 * gtrgm_consistent_cache header, then the input query (4-byte length
221 * word, uncompressed, starting at a MAXALIGN boundary), then the TRGM
222 * value (also starting at a MAXALIGN boundary). However we don't try to
223 * include the regex graph (if any) in that struct. (XXX currently, this
224 * approach can leak regex graphs across index rescans. Not clear if
225 * that's worth fixing.)
226 */
227 cache = (gtrgm_consistent_cache *) fcinfo->flinfo->fn_extra;
228 if (cache == NULL ||
229 cache->strategy != strategy ||
230 VARSIZE(cache->query) != querysize ||
231 memcmp(cache->query, query, querysize) != 0)
232 {
233 gtrgm_consistent_cache *newcache;
234 TrgmPackedGraph *graph = NULL;
235 Size qtrgsize;
236
237 switch (strategy)
238 {
239 case SimilarityStrategyNumber:
240 case WordSimilarityStrategyNumber:
241 case StrictWordSimilarityStrategyNumber:
242 case EqualStrategyNumber:
243 qtrg = generate_trgm(VARDATA(query),
244 querysize - VARHDRSZ);
245 break;
246 case ILikeStrategyNumber:
247 #ifndef IGNORECASE
248 elog(ERROR, "cannot handle ~~* with case-sensitive trigrams");
249 #endif
250 /* FALL THRU */
251 case LikeStrategyNumber:
252 qtrg = generate_wildcard_trgm(VARDATA(query),
253 querysize - VARHDRSZ);
254 break;
255 case RegExpICaseStrategyNumber:
256 #ifndef IGNORECASE
257 elog(ERROR, "cannot handle ~* with case-sensitive trigrams");
258 #endif
259 /* FALL THRU */
260 case RegExpStrategyNumber:
261 qtrg = createTrgmNFA(query, PG_GET_COLLATION(),
262 &graph, fcinfo->flinfo->fn_mcxt);
263 /* just in case an empty array is returned ... */
264 if (qtrg && ARRNELEM(qtrg) <= 0)
265 {
266 pfree(qtrg);
267 qtrg = NULL;
268 }
269 break;
270 default:
271 elog(ERROR, "unrecognized strategy number: %d", strategy);
272 qtrg = NULL; /* keep compiler quiet */
273 break;
274 }
275
276 qtrgsize = qtrg ? VARSIZE(qtrg) : 0;
277
278 newcache = (gtrgm_consistent_cache *)
279 MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
280 MAXALIGN(sizeof(gtrgm_consistent_cache)) +
281 MAXALIGN(querysize) +
282 qtrgsize);
283
284 newcache->strategy = strategy;
285 newcache->query = (text *)
286 ((char *) newcache + MAXALIGN(sizeof(gtrgm_consistent_cache)));
287 memcpy(newcache->query, query, querysize);
288 if (qtrg)
289 {
290 newcache->trigrams = (TRGM *)
291 ((char *) newcache->query + MAXALIGN(querysize));
292 memcpy((char *) newcache->trigrams, qtrg, qtrgsize);
293 /* release qtrg in case it was made in fn_mcxt */
294 pfree(qtrg);
295 }
296 else
297 newcache->trigrams = NULL;
298 newcache->graph = graph;
299
300 if (cache)
301 pfree(cache);
302 fcinfo->flinfo->fn_extra = newcache;
303 cache = newcache;
304 }
305
306 qtrg = cache->trigrams;
307
308 switch (strategy)
309 {
310 case SimilarityStrategyNumber:
311 case WordSimilarityStrategyNumber:
312 case StrictWordSimilarityStrategyNumber:
313
314 /*
315 * Similarity search is exact. (Strict) word similarity search is
316 * inexact
317 */
318 *recheck = (strategy != SimilarityStrategyNumber);
319
320 nlimit = index_strategy_get_limit(strategy);
321
322 if (GIST_LEAF(entry))
323 { /* all leafs contains orig trgm */
324 double tmpsml = cnt_sml(qtrg, key, *recheck);
325
326 res = (tmpsml >= nlimit);
327 }
328 else if (ISALLTRUE(key))
329 { /* non-leaf contains signature */
330 res = true;
331 }
332 else
333 { /* non-leaf contains signature */
334 int32 count = cnt_sml_sign_common(qtrg, GETSIGN(key), siglen);
335 int32 len = ARRNELEM(qtrg);
336
337 if (len == 0)
338 res = false;
339 else
340 res = (((((float8) count) / ((float8) len))) >= nlimit);
341 }
342 break;
343 case ILikeStrategyNumber:
344 #ifndef IGNORECASE
345 elog(ERROR, "cannot handle ~~* with case-sensitive trigrams");
346 #endif
347 /* FALL THRU */
348 case LikeStrategyNumber:
349 case EqualStrategyNumber:
350 /* Wildcard and equal search are inexact */
351 *recheck = true;
352
353 /*
354 * Check if all the extracted trigrams can be present in child
355 * nodes.
356 */
357 if (GIST_LEAF(entry))
358 { /* all leafs contains orig trgm */
359 res = trgm_contained_by(qtrg, key);
360 }
361 else if (ISALLTRUE(key))
362 { /* non-leaf contains signature */
363 res = true;
364 }
365 else
366 { /* non-leaf contains signature */
367 int32 k,
368 tmp = 0,
369 len = ARRNELEM(qtrg);
370 trgm *ptr = GETARR(qtrg);
371 BITVECP sign = GETSIGN(key);
372
373 res = true;
374 for (k = 0; k < len; k++)
375 {
376 CPTRGM(&tmp, ptr + k);
377 if (!GETBIT(sign, HASHVAL(tmp, siglen)))
378 {
379 res = false;
380 break;
381 }
382 }
383 }
384 break;
385 case RegExpICaseStrategyNumber:
386 #ifndef IGNORECASE
387 elog(ERROR, "cannot handle ~* with case-sensitive trigrams");
388 #endif
389 /* FALL THRU */
390 case RegExpStrategyNumber:
391 /* Regexp search is inexact */
392 *recheck = true;
393
394 /* Check regex match as much as we can with available info */
395 if (qtrg)
396 {
397 if (GIST_LEAF(entry))
398 { /* all leafs contains orig trgm */
399 bool *check;
400
401 check = trgm_presence_map(qtrg, key);
402 res = trigramsMatchGraph(cache->graph, check);
403 pfree(check);
404 }
405 else if (ISALLTRUE(key))
406 { /* non-leaf contains signature */
407 res = true;
408 }
409 else
410 { /* non-leaf contains signature */
411 int32 k,
412 tmp = 0,
413 len = ARRNELEM(qtrg);
414 trgm *ptr = GETARR(qtrg);
415 BITVECP sign = GETSIGN(key);
416 bool *check;
417
418 /*
419 * GETBIT() tests may give false positives, due to limited
420 * size of the sign array. But since trigramsMatchGraph()
421 * implements a monotone boolean function, false positives
422 * in the check array can't lead to false negative answer.
423 * So we can apply trigramsMatchGraph despite uncertainty,
424 * and that usefully improves the quality of the search.
425 */
426 check = (bool *) palloc(len * sizeof(bool));
427 for (k = 0; k < len; k++)
428 {
429 CPTRGM(&tmp, ptr + k);
430 check[k] = GETBIT(sign, HASHVAL(tmp, siglen));
431 }
432 res = trigramsMatchGraph(cache->graph, check);
433 pfree(check);
434 }
435 }
436 else
437 {
438 /* trigram-free query must be rechecked everywhere */
439 res = true;
440 }
441 break;
442 default:
443 elog(ERROR, "unrecognized strategy number: %d", strategy);
444 res = false; /* keep compiler quiet */
445 break;
446 }
447
448 PG_RETURN_BOOL(res);
449 }
450
451 Datum
452 gtrgm_distance(PG_FUNCTION_ARGS)
453 {
454 GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
455 text *query = PG_GETARG_TEXT_P(1);
456 StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
457
458 /* Oid subtype = PG_GETARG_OID(3); */
459 bool *recheck = (bool *) PG_GETARG_POINTER(4);
460 int siglen = GET_SIGLEN();
461 TRGM *key = (TRGM *) DatumGetPointer(entry->key);
462 TRGM *qtrg;
463 float8 res;
464 Size querysize = VARSIZE(query);
465 char *cache = (char *) fcinfo->flinfo->fn_extra;
466
467 /*
468 * Cache the generated trigrams across multiple calls with the same query.
469 */
470 if (cache == NULL ||
471 VARSIZE(cache) != querysize ||
472 memcmp(cache, query, querysize) != 0)
473 {
474 char *newcache;
475
476 qtrg = generate_trgm(VARDATA(query), querysize - VARHDRSZ);
477
478 newcache = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
479 MAXALIGN(querysize) +
480 VARSIZE(qtrg));
481
482 memcpy(newcache, query, querysize);
483 memcpy(newcache + MAXALIGN(querysize), qtrg, VARSIZE(qtrg));
484
485 if (cache)
486 pfree(cache);
487 fcinfo->flinfo->fn_extra = newcache;
488 cache = newcache;
489 }
490
491 qtrg = (TRGM *) (cache + MAXALIGN(querysize));
492
493 switch (strategy)
494 {
495 case DistanceStrategyNumber:
496 case WordDistanceStrategyNumber:
497 case StrictWordDistanceStrategyNumber:
498 /* Only plain trigram distance is exact */
499 *recheck = (strategy != DistanceStrategyNumber);
500 if (GIST_LEAF(entry))
501 { /* all leafs contains orig trgm */
502
503 /*
504 * Prevent gcc optimizing the sml variable using volatile
505 * keyword. Otherwise res can differ from the
506 * word_similarity_dist_op() function.
507 */
508 float4 volatile sml = cnt_sml(qtrg, key, *recheck);
509
510 res = 1.0 - sml;
511 }
512 else if (ISALLTRUE(key))
513 { /* all leafs contains orig trgm */
514 res = 0.0;
515 }
516 else
517 { /* non-leaf contains signature */
518 int32 count = cnt_sml_sign_common(qtrg, GETSIGN(key), siglen);
519 int32 len = ARRNELEM(qtrg);
520
521 res = (len == 0) ? -1.0 : 1.0 - ((float8) count) / ((float8) len);
522 }
523 break;
524 default:
525 elog(ERROR, "unrecognized strategy number: %d", strategy);
526 res = 0; /* keep compiler quiet */
527 break;
528 }
529
530 PG_RETURN_FLOAT8(res);
531 }
532
533 static int32
534 unionkey(BITVECP sbase, TRGM *add, int siglen)
535 {
536 int32 i;
537
538 if (ISSIGNKEY(add))
539 {
540 BITVECP sadd = GETSIGN(add);
541
542 if (ISALLTRUE(add))
543 return 1;
544
545 LOOPBYTE(siglen)
546 sbase[i] |= sadd[i];
547 }
548 else
549 {
550 trgm *ptr = GETARR(add);
551 int32 tmp = 0;
552
553 for (i = 0; i < ARRNELEM(add); i++)
554 {
555 CPTRGM(&tmp, ptr + i);
556 HASH(sbase, tmp, siglen);
557 }
558 }
559 return 0;
560 }
561
562
563 Datum
564 gtrgm_union(PG_FUNCTION_ARGS)
565 {
566 GistEntryVector *entryvec = (GistEntryVector *) PG_GETARG_POINTER(0);
567 int32 len = entryvec->n;
568 int *size = (int *) PG_GETARG_POINTER(1);
569 int siglen = GET_SIGLEN();
570 int32 i;
571 TRGM *result = gtrgm_alloc(false, siglen, NULL);
572 BITVECP base = GETSIGN(result);
573
574 for (i = 0; i < len; i++)
575 {
576 if (unionkey(base, GETENTRY(entryvec, i), siglen))
577 {
578 result->flag = ALLISTRUE;
579 SET_VARSIZE(result, CALCGTSIZE(ALLISTRUE, siglen));
580 break;
581 }
582 }
583
584 *size = VARSIZE(result);
585
586 PG_RETURN_POINTER(result);
587 }
588
589 Datum
590 gtrgm_same(PG_FUNCTION_ARGS)
591 {
592 TRGM *a = (TRGM *) PG_GETARG_POINTER(0);
593 TRGM *b = (TRGM *) PG_GETARG_POINTER(1);
594 bool *result = (bool *) PG_GETARG_POINTER(2);
595 int siglen = GET_SIGLEN();
596
597 if (ISSIGNKEY(a))
598 { /* then b also ISSIGNKEY */
599 if (ISALLTRUE(a) && ISALLTRUE(b))
600 *result = true;
601 else if (ISALLTRUE(a))
602 *result = false;
603 else if (ISALLTRUE(b))
604 *result = false;
605 else
606 {
607 int32 i;
608 BITVECP sa = GETSIGN(a),
609 sb = GETSIGN(b);
610
611 *result = true;
612 LOOPBYTE(siglen)
613 {
614 if (sa[i] != sb[i])
615 {
616 *result = false;
617 break;
618 }
619 }
620 }
621 }
622 else
623 { /* a and b ISARRKEY */
624 int32 lena = ARRNELEM(a),
625 lenb = ARRNELEM(b);
626
627 if (lena != lenb)
628 *result = false;
629 else
630 {
631 trgm *ptra = GETARR(a),
632 *ptrb = GETARR(b);
633 int32 i;
634
635 *result = true;
636 for (i = 0; i < lena; i++)
637 if (CMPTRGM(ptra + i, ptrb + i))
638 {
639 *result = false;
640 break;
641 }
642 }
643 }
644
645 PG_RETURN_POINTER(result);
646 }
647
648 static int32
649 sizebitvec(BITVECP sign, int siglen)
650 {
651 return pg_popcount(sign, siglen);
652 }
653
654 static int
655 hemdistsign(BITVECP a, BITVECP b, int siglen)
656 {
657 int i,
658 diff,
659 dist = 0;
660
661 LOOPBYTE(siglen)
662 {
663 diff = (unsigned char) (a[i] ^ b[i]);
664 /* Using the popcount functions here isn't likely to win */
665 dist += pg_number_of_ones[diff];
666 }
667 return dist;
668 }
669
670 static int
671 hemdist(TRGM *a, TRGM *b, int siglen)
672 {
673 if (ISALLTRUE(a))
674 {
675 if (ISALLTRUE(b))
676 return 0;
677 else
678 return SIGLENBIT(siglen) - sizebitvec(GETSIGN(b), siglen);
679 }
680 else if (ISALLTRUE(b))
681 return SIGLENBIT(siglen) - sizebitvec(GETSIGN(a), siglen);
682
683 return hemdistsign(GETSIGN(a), GETSIGN(b), siglen);
684 }
685
686 Datum
687 gtrgm_penalty(PG_FUNCTION_ARGS)
688 {
689 GISTENTRY *origentry = (GISTENTRY *) PG_GETARG_POINTER(0); /* always ISSIGNKEY */
690 GISTENTRY *newentry = (GISTENTRY *) PG_GETARG_POINTER(1);
691 float *penalty = (float *) PG_GETARG_POINTER(2);
692 int siglen = GET_SIGLEN();
693 TRGM *origval = (TRGM *) DatumGetPointer(origentry->key);
694 TRGM *newval = (TRGM *) DatumGetPointer(newentry->key);
695 BITVECP orig = GETSIGN(origval);
696
697 *penalty = 0.0;
698
699 if (ISARRKEY(newval))
700 {
701 char *cache = (char *) fcinfo->flinfo->fn_extra;
702 TRGM *cachedVal = NULL;
703 Size newvalsize = VARSIZE(newval);
704 BITVECP sign;
705
706 if (cache != NULL)
707 cachedVal = (TRGM *) (cache + MAXALIGN(siglen));
708
709 /*
710 * Cache the sign data across multiple calls with the same newval.
711 */
712 if (cache == NULL ||
713 VARSIZE(cachedVal) != newvalsize ||
714 memcmp(cachedVal, newval, newvalsize) != 0)
715 {
716 char *newcache;
717
718 newcache = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
719 MAXALIGN(siglen) +
720 newvalsize);
721
722 makesign((BITVECP) newcache, newval, siglen);
723
724 cachedVal = (TRGM *) (newcache + MAXALIGN(siglen));
725 memcpy(cachedVal, newval, newvalsize);
726
727 if (cache)
728 pfree(cache);
729 fcinfo->flinfo->fn_extra = newcache;
730 cache = newcache;
731 }
732
733 sign = (BITVECP) cache;
734
735 if (ISALLTRUE(origval))
736 *penalty = ((float) (SIGLENBIT(siglen) - sizebitvec(sign, siglen))) / (float) (SIGLENBIT(siglen) + 1);
737 else
738 *penalty = hemdistsign(sign, orig, siglen);
739 }
740 else
741 *penalty = hemdist(origval, newval, siglen);
742 PG_RETURN_POINTER(penalty);
743 }
744
745 typedef struct
746 {
747 bool allistrue;
748 BITVECP sign;
749 } CACHESIGN;
750
751 static void
752 fillcache(CACHESIGN *item, TRGM *key, BITVECP sign, int siglen)
753 {
754 item->allistrue = false;
755 item->sign = sign;
756 if (ISARRKEY(key))
757 makesign(item->sign, key, siglen);
758 else if (ISALLTRUE(key))
759 item->allistrue = true;
760 else
761 memcpy(item->sign, GETSIGN(key), siglen);
762 }
763
764 #define WISH_F(a,b,c) (double)( -(double)(((a)-(b))*((a)-(b))*((a)-(b)))*(c) )
765 typedef struct
766 {
767 OffsetNumber pos;
768 int32 cost;
769 } SPLITCOST;
770
771 static int
772 comparecost(const void *a, const void *b)
773 {
774 if (((const SPLITCOST *) a)->cost == ((const SPLITCOST *) b)->cost)
775 return 0;
776 else
777 return (((const SPLITCOST *) a)->cost > ((const SPLITCOST *) b)->cost) ? 1 : -1;
778 }
779
780
781 static int
782 hemdistcache(CACHESIGN *a, CACHESIGN *b, int siglen)
783 {
784 if (a->allistrue)
785 {
786 if (b->allistrue)
787 return 0;
788 else
789 return SIGLENBIT(siglen) - sizebitvec(b->sign, siglen);
790 }
791 else if (b->allistrue)
792 return SIGLENBIT(siglen) - sizebitvec(a->sign, siglen);
793
794 return hemdistsign(a->sign, b->sign, siglen);
795 }
796
797 Datum
798 gtrgm_picksplit(PG_FUNCTION_ARGS)
799 {
800 GistEntryVector *entryvec = (GistEntryVector *) PG_GETARG_POINTER(0);
801 OffsetNumber maxoff = entryvec->n - 1;
802 GIST_SPLITVEC *v = (GIST_SPLITVEC *) PG_GETARG_POINTER(1);
803 int siglen = GET_SIGLEN();
804 OffsetNumber k,
805 j;
806 TRGM *datum_l,
807 *datum_r;
808 BITVECP union_l,
809 union_r;
810 int32 size_alpha,
811 size_beta;
812 int32 size_waste,
813 waste = -1;
814 int32 nbytes;
815 OffsetNumber seed_1 = 0,
816 seed_2 = 0;
817 OffsetNumber *left,
818 *right;
819 BITVECP ptr;
820 int i;
821 CACHESIGN *cache;
822 char *cache_sign;
823 SPLITCOST *costvector;
824
825 /* cache the sign data for each existing item */
826 cache = (CACHESIGN *) palloc(sizeof(CACHESIGN) * (maxoff + 1));
827 cache_sign = palloc(siglen * (maxoff + 1));
828
829 for (k = FirstOffsetNumber; k <= maxoff; k = OffsetNumberNext(k))
830 fillcache(&cache[k], GETENTRY(entryvec, k), &cache_sign[siglen * k],
831 siglen);
832
833 /* now find the two furthest-apart items */
834 for (k = FirstOffsetNumber; k < maxoff; k = OffsetNumberNext(k))
835 {
836 for (j = OffsetNumberNext(k); j <= maxoff; j = OffsetNumberNext(j))
837 {
838 size_waste = hemdistcache(&(cache[j]), &(cache[k]), siglen);
839 if (size_waste > waste)
840 {
841 waste = size_waste;
842 seed_1 = k;
843 seed_2 = j;
844 }
845 }
846 }
847
848 /* just in case we didn't make a selection ... */
849 if (seed_1 == 0 || seed_2 == 0)
850 {
851 seed_1 = 1;
852 seed_2 = 2;
853 }
854
855 /* initialize the result vectors */
856 nbytes = maxoff * sizeof(OffsetNumber);
857 v->spl_left = left = (OffsetNumber *) palloc(nbytes);
858 v->spl_right = right = (OffsetNumber *) palloc(nbytes);
859 v->spl_nleft = 0;
860 v->spl_nright = 0;
861
862 /* form initial .. */
863 datum_l = gtrgm_alloc(cache[seed_1].allistrue, siglen, cache[seed_1].sign);
864 datum_r = gtrgm_alloc(cache[seed_2].allistrue, siglen, cache[seed_2].sign);
865
866 union_l = GETSIGN(datum_l);
867 union_r = GETSIGN(datum_r);
868
869 /* sort before ... */
870 costvector = (SPLITCOST *) palloc(sizeof(SPLITCOST) * maxoff);
871 for (j = FirstOffsetNumber; j <= maxoff; j = OffsetNumberNext(j))
872 {
873 costvector[j - 1].pos = j;
874 size_alpha = hemdistcache(&(cache[seed_1]), &(cache[j]), siglen);
875 size_beta = hemdistcache(&(cache[seed_2]), &(cache[j]), siglen);
876 costvector[j - 1].cost = abs(size_alpha - size_beta);
877 }
878 qsort(costvector, maxoff, sizeof(SPLITCOST), comparecost);
879
880 for (k = 0; k < maxoff; k++)
881 {
882 j = costvector[k].pos;
883 if (j == seed_1)
884 {
885 *left++ = j;
886 v->spl_nleft++;
887 continue;
888 }
889 else if (j == seed_2)
890 {
891 *right++ = j;
892 v->spl_nright++;
893 continue;
894 }
895
896 if (ISALLTRUE(datum_l) || cache[j].allistrue)
897 {
898 if (ISALLTRUE(datum_l) && cache[j].allistrue)
899 size_alpha = 0;
900 else
901 size_alpha = SIGLENBIT(siglen) -
902 sizebitvec((cache[j].allistrue) ? GETSIGN(datum_l) :
903 cache[j].sign,
904 siglen);
905 }
906 else
907 size_alpha = hemdistsign(cache[j].sign, GETSIGN(datum_l), siglen);
908
909 if (ISALLTRUE(datum_r) || cache[j].allistrue)
910 {
911 if (ISALLTRUE(datum_r) && cache[j].allistrue)
912 size_beta = 0;
913 else
914 size_beta = SIGLENBIT(siglen) -
915 sizebitvec((cache[j].allistrue) ? GETSIGN(datum_r) :
916 cache[j].sign,
917 siglen);
918 }
919 else
920 size_beta = hemdistsign(cache[j].sign, GETSIGN(datum_r), siglen);
921
922 if (size_alpha < size_beta + WISH_F(v->spl_nleft, v->spl_nright, 0.1))
923 {
924 if (ISALLTRUE(datum_l) || cache[j].allistrue)
925 {
926 if (!ISALLTRUE(datum_l))
927 memset(GETSIGN(datum_l), 0xff, siglen);
928 }
929 else
930 {
931 ptr = cache[j].sign;
932 LOOPBYTE(siglen)
933 union_l[i] |= ptr[i];
934 }
935 *left++ = j;
936 v->spl_nleft++;
937 }
938 else
939 {
940 if (ISALLTRUE(datum_r) || cache[j].allistrue)
941 {
942 if (!ISALLTRUE(datum_r))
943 memset(GETSIGN(datum_r), 0xff, siglen);
944 }
945 else
946 {
947 ptr = cache[j].sign;
948 LOOPBYTE(siglen)
949 union_r[i] |= ptr[i];
950 }
951 *right++ = j;
952 v->spl_nright++;
953 }
954 }
955
956 v->spl_ldatum = PointerGetDatum(datum_l);
957 v->spl_rdatum = PointerGetDatum(datum_r);
958
959 PG_RETURN_POINTER(v);
960 }
961
962 Datum
963 gtrgm_options(PG_FUNCTION_ARGS)
964 {
965 local_relopts *relopts = (local_relopts *) PG_GETARG_POINTER(0);
966
967 init_local_reloptions(relopts, sizeof(TrgmGistOptions));
968 add_local_int_reloption(relopts, "siglen",
969 "signature length in bytes",
970 SIGLEN_DEFAULT, 1, SIGLEN_MAX,
971 offsetof(TrgmGistOptions, siglen));
972
973 PG_RETURN_VOID();
974 }