Skip to content

Commit f73a163

Browse files
committed
Fix contrib/pg_trgm's similarity() function for trigram-free strings.
Cases such as similarity('', '') produced a NaN result due to computing 0/0. Per discussion, make it return zero instead. This appears to be the basic cause of bug #7867 from Michele Baravalle, although it remains unclear why her installation doesn't think Cyrillic letters are letters. Back-patch to all active branches.
1 parent 52c889e commit f73a163

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

contrib/pg_trgm/expected/pg_trgm.out

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,12 @@ select similarity('wow',' WOW ');
5353
1
5454
(1 row)
5555

56+
select similarity('---', '####---');
57+
similarity
58+
------------
59+
0
60+
(1 row)
61+
5662
CREATE TABLE test_trgm(t text);
5763
\copy test_trgm from 'data/trgm.data
5864
select t,similarity(t,'qwertyu0988') as sml from test_trgm where t % 'qwertyu0988' order by sml desc, t;

contrib/pg_trgm/sql/pg_trgm.sql

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ select show_trgm('a b C0*%^');
1111
select similarity('wow','WOWa ');
1212
select similarity('wow',' WOW ');
1313

14+
select similarity('---', '####---');
15+
1416
CREATE TABLE test_trgm(t text);
1517

1618
\copy test_trgm from 'data/trgm.data

contrib/pg_trgm/trgm_op.c

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -554,6 +554,10 @@ cnt_sml(TRGM *trg1, TRGM *trg2)
554554
len1 = ARRNELEM(trg1);
555555
len2 = ARRNELEM(trg2);
556556

557+
/* explicit test is needed to avoid 0/0 division when both lengths are 0 */
558+
if (len1 <= 0 || len2 <= 0)
559+
return (float4) 0.0;
560+
557561
while (ptr1 - GETARR(trg1) < len1 && ptr2 - GETARR(trg2) < len2)
558562
{
559563
int res = CMPTRGM(ptr1, ptr2);
@@ -571,9 +575,9 @@ cnt_sml(TRGM *trg1, TRGM *trg2)
571575
}
572576

573577
#ifdef DIVUNION
574-
return ((((float4) count) / ((float4) (len1 + len2 - count))));
578+
return ((float4) count) / ((float4) (len1 + len2 - count));
575579
#else
576-
return (((float) count) / ((float) ((len1 > len2) ? len1 : len2)));
580+
return ((float4) count) / ((float4) ((len1 > len2) ? len1 : len2));
577581
#endif
578582

579583
}

0 commit comments

Comments
 (0)