Skip to content

Commit 4875931

Browse files
committed
Fix normalization of numeric values in JSONB GIN indexes.
The default JSONB GIN opclass (jsonb_ops) converts numeric data values to strings for storage in the index. It must ensure that numeric values that would compare equal (such as 12 and 12.00) produce identical strings, else index searches would have behavior different from regular JSONB comparisons. Unfortunately the function charged with doing this was completely wrong: it could reduce distinct numeric values to the same string, or reduce equivalent numeric values to different strings. The former type of error would only lead to search inefficiency, but the latter type of error would cause index entries that should be found by a search to not be found. Repairing this bug therefore means that it will be necessary for 9.4 beta testers to reindex GIN jsonb_ops indexes, if they care about getting correct results from index searches involving numeric data values within the comparison JSONB object. Per report from Thomas Fanghaenel.
1 parent 5332b8c commit 4875931

File tree

1 file changed

+20
-12
lines changed

1 file changed

+20
-12
lines changed

src/backend/utils/adt/numeric.c

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -629,15 +629,17 @@ numeric_out_sci(Numeric num, int scale)
629629
/*
630630
* numeric_normalize() -
631631
*
632-
* Output function for numeric data type without trailing zeroes.
632+
* Output function for numeric data type, suppressing insignificant trailing
633+
* zeroes and then any trailing decimal point. The intent of this is to
634+
* produce strings that are equal if and only if the input numeric values
635+
* compare equal.
633636
*/
634637
char *
635638
numeric_normalize(Numeric num)
636639
{
637640
NumericVar x;
638641
char *str;
639-
int orig,
640-
last;
642+
int last;
641643

642644
/*
643645
* Handle NaN
@@ -649,18 +651,24 @@ numeric_normalize(Numeric num)
649651

650652
str = get_str_from_var(&x);
651653

652-
orig = last = strlen(str) - 1;
653-
654-
for (;;)
654+
/* If there's no decimal point, there's certainly nothing to remove. */
655+
if (strchr(str, '.') != NULL)
655656
{
656-
if (last == 0 || str[last] != '0')
657-
break;
657+
/*
658+
* Back up over trailing fractional zeroes. Since there is a decimal
659+
* point, this loop will terminate safely.
660+
*/
661+
last = strlen(str) - 1;
662+
while (str[last] == '0')
663+
last--;
658664

659-
last--;
660-
}
665+
/* We want to get rid of the decimal point too, if it's now last. */
666+
if (str[last] == '.')
667+
last--;
661668

662-
if (last > 0 && last != orig)
663-
str[last] = '\0';
669+
/* Delete whatever we backed up over. */
670+
str[last + 1] = '\0';
671+
}
664672

665673
return str;
666674
}

0 commit comments

Comments
 (0)