From 343801cf8dfa79c3983cab813c5c48db3a390adb Mon Sep 17 00:00:00 2001
From: Dilip Kumar <dilipkumar@localhost.localdomain>
Date: Mon, 22 Mar 2021 20:40:43 +0530
Subject: [PATCH v1] fix slice decompression

If the slicelength is more than the actual size of the data then no
point in trying to decompress the slice so directly decompress complete
data.
---
 src/backend/access/common/detoast.c  | 8 ++++++++
 src/include/access/toast_internals.h | 2 ++
 2 files changed, 10 insertions(+)

diff --git a/src/backend/access/common/detoast.c b/src/backend/access/common/detoast.c
index bed50e8..e6e57ad 100644
--- a/src/backend/access/common/detoast.c
+++ b/src/backend/access/common/detoast.c
@@ -506,6 +506,14 @@ toast_decompress_datum_slice(struct varlena *attr, int32 slicelength)
 
 	Assert(VARATT_IS_COMPRESSED(attr));
 
+	/* 
+	 * If the slicelength is more than the actual size of the data then no
+	 * point in trying to decompress the slice so directly decompress complete
+	 * data.
+	 */
+	if (slicelength >= TOAST_COMPRESS_RAWSIZE(attr))
+		return toast_decompress_datum(attr);
+
 	/*
 	 * Fetch the compression method id stored in the compression header and
 	 * decompress the data slice using the appropriate decompression routine.
diff --git a/src/include/access/toast_internals.h b/src/include/access/toast_internals.h
index b4d0684..e1e3521 100644
--- a/src/include/access/toast_internals.h
+++ b/src/include/access/toast_internals.h
@@ -31,6 +31,8 @@ typedef struct toast_compress_header
  * Utilities for manipulation of header information for compressed
  * toast entries.
  */
+#define TOAST_COMPRESS_RAWSIZE(ptr) \
+		(((toast_compress_header *) (ptr))->tcinfo & VARLENA_RAWSIZE_MASK)
 #define TOAST_COMPRESS_METHOD(ptr)	\
 		(((toast_compress_header *) (ptr))->tcinfo >> VARLENA_RAWSIZE_BITS)
 #define TOAST_COMPRESS_SET_SIZE_AND_METHOD(ptr, len, cm_method) \
-- 
1.8.3.1

