From df1e8f34ba3f4c8eb28db61be32323437553d673 Mon Sep 17 00:00:00 2001
From: Nikhil Kumar Veldanda <veldanda.nikhilkumar17@gmail.com>
Date: Tue, 15 Sep 2026 23:02:35 -0700
Subject: [PATCH v19 3/5] Add zstd as a TOAST compression method

Allow columns to be compressed with Zstandard, via
COMPRESSION zstd in CREATE TABLE and ALTER TABLE, and via
default_toast_compression = 'zstd'.  It is available when the server
is built with --with-zstd (or -Dzstd for meson); the library was
already linked into the backend for WAL compression, so no build
system changes are needed.

zstd is the first method to use the long form of the compressed
header and of the TOAST pointer introduced by the previous commit, and
is assigned ID 2.  The compressor lays out the datum with
VARHDRSZ_COMPRESSED_LONG bytes of header, and the decompressors expect
that.  Compression uses ZSTD_compressCCtx() at ZSTD_CLEVEL_DEFAULT with
no dictionary.  Slice decompression uses the streaming API, since the
one-shot API can only decode a whole frame; as with lz4, the whole
compressed value has to be fetched from the TOAST table first, because
there is no way to bound how much compressed input a given prefix
needs.

Decompression keeps one ZSTD_DCtx for the life of the backend instead
of creating one per value, which costs more than decompressing a small
value.  For whole-value reads and small (4kB) values this saves a few
percent; it rises to about 40% for small slices and prefixes of large
(32kB) values, where the allocation dominates the decode.
The context is reset at the start of each use, since a slice stops in
the middle of a frame and an error can leave one half decoded; without
the reset, the next value's decoding continues the previous frame.  The
WAL code reuses its zstd contexts too (857340b0263, ce3387b74b7), but
ties the decompression context to the XLogReaderState; detoasting has no
such owner, so the scope here is the backend.  The context is allocated
by zstd outside any memory context, about 100kB, growing to about 2.5MB
after slices of large values until zstd (from 1.4.5) shrinks it again.

The slice decoder's buffer is sized from the window recorded in the
frame header, so a corrupt header could make that backend-lifetime
context grow to zstd's default limit of 128MB.  The context caps the
window at 2^23 bytes, which the default compression level never exceeds
(it uses at most 2^21 in libzstd 1.4.0 through 1.5.7), and the slice
path checks the frame's recorded content size against our header, as
the whole-value path does through ZSTD_decompressDCtx().  The slice
loop feeds the compressed input in ZSTD_DStreamInSize() chunks and
checks for interrupts between them, as decoding a large value can take
a while.

Compression likewise keeps one ZSTD_CCtx for the life of the backend:
a one-shot ZSTD_compress() allocates and frees a compression context
for every value, sized to the input (about 90kB for a 4kB value, about
1.3MB from 1MB up), which dominates a bulk load.

Teach the usual places about the new method: pg_column_compression(),
the default_toast_compression GUC, amcheck, pg_dump (which would
otherwise silently drop the column's compression setting), psql's \d+
and tab completion, and the documentation.

The regression test follows compression_lz4 and skips itself when the
server lacks zstd support.  Beyond the cases covered for lz4, it checks:
slices at the start, end and past the end of a value, and longer than
the value, including bytea slices across zstd's 128kB block boundary,
which take the slice path in every encoding; values that stay
uncompressed because they are below the TOAST threshold or because zstd
cannot shrink them; bytea with zero bytes, jsonb and arrays; inline and
external values with both oid and oid8 TOAST value IDs, including a
value spanning hundreds of TOAST chunks; the EXTERNAL, MAIN and PLAIN
storage modes; copying compressed values between tables and methods in
both directions; VACUUM FULL, CLUSTER and a rewriting ALTER COLUMN TYPE;
that updating or deleting a row removes its old TOAST value; indexes on
compressed keys; and the GUC, including SET COMPRESSION default.  A
pg_dump test checks that the compression setting survives a dump.

Co-authored-by: Manuel Reyes Bravo <manuelreyesbravo@gmail.com>
Reviewed-by: wenhui qiu <qiuwenhuifx@gmail.com>
Reviewed-by: Hannu Krosing <hannuk@google.com>
Discussion: https://postgr.es/m/CAFAfj_GGY4W81XjtYLvYOhqPtvfZbBNj=YRS6Mq_0SA9AqEwoQ@mail.gmail.com
Discussion: https://postgr.es/m/CAOj6k6dy2CRVA6Lsb5N59zE-7KNVKt=oYwWyg8ULK8zOOY8e7A@mail.gmail.com
---
 contrib/amcheck/t/007_verify_toast_pointer.pl | 153 ++++
 doc/src/sgml/catalogs.sgml                    |   6 +-
 doc/src/sgml/config.sgml                      |   6 +-
 doc/src/sgml/installation.sgml                |   1 +
 doc/src/sgml/ref/alter_table.sgml             |   9 +-
 doc/src/sgml/ref/create_table.sgml            |   8 +-
 src/backend/access/common/detoast.c           |  12 +-
 src/backend/access/common/toast_compression.c | 322 +++++++
 src/backend/access/common/toast_internals.c   |   4 +
 src/backend/utils/adt/varlena.c               |   3 +
 src/backend/utils/misc/guc_tables.c           |   3 +
 src/backend/utils/misc/postgresql.conf.sample |   2 +-
 src/bin/pg_dump/pg_dump.c                     |   3 +
 src/bin/pg_dump/t/006_pg_dump_compress.pl     |  18 +
 src/bin/psql/describe.c                       |   5 +-
 src/bin/psql/tab-complete.in.c                |   2 +-
 src/include/access/toast_compression.h        |  18 +-
 .../regress/expected/compression_zstd.out     | 859 ++++++++++++++++++
 .../regress/expected/compression_zstd_1.out   |   7 +
 src/test/regress/parallel_schedule            |   2 +-
 src/test/regress/sql/compression_zstd.sql     | 517 +++++++++++
 21 files changed, 1940 insertions(+), 20 deletions(-)
 create mode 100644 src/test/regress/expected/compression_zstd.out
 create mode 100644 src/test/regress/expected/compression_zstd_1.out
 create mode 100644 src/test/regress/sql/compression_zstd.sql

diff --git a/contrib/amcheck/t/007_verify_toast_pointer.pl b/contrib/amcheck/t/007_verify_toast_pointer.pl
index 4270f21177d..2b6d40ebd82 100644
--- a/contrib/amcheck/t/007_verify_toast_pointer.pl
+++ b/contrib/amcheck/t/007_verify_toast_pointer.pl
@@ -125,4 +125,157 @@ for my $id (1, 2)
 }
 is($node->safe_psql('postgres', q(SELECT 1)), '1', 'server still up');
 
+# zstd values use the long form of the pointer: the method bits say "long
+# form" and the method is the byte after the plain pointer.
+if (!check_pg_config("#define USE_ZSTD 1"))
+{
+	done_testing();
+	exit;
+}
+
+$node->safe_psql(
+	'postgres', qq(
+	CREATE TABLE tz (id int, f text COMPRESSION zstd)
+		WITH (autovacuum_enabled = false, toast_tuple_target = 128);
+	INSERT INTO tz
+		SELECT g, (SELECT string_agg(encode(sha256((g * 1000 + i)::text::bytea),
+											'hex'), '')
+				   FROM generate_series(1, 60) i) || repeat('x', 12000)
+			FROM generate_series(1, 7) g;
+	CHECKPOINT;
+));
+is( $node->safe_psql(
+		'postgres', q(
+	SELECT string_agg(pg_column_compression(f) || ':' ||
+					  (pg_column_toast_chunk_id(f) IS NOT NULL), ',' ORDER BY id)
+		FROM tz)),
+	join(',', ('zstd:true') x 7),
+	'values are compressed with zstd and external');
+is($node->safe_psql('postgres', q(SELECT * FROM verify_heapam('tz'))),
+	'', 'no corruption in long-form pointers before forging');
+
+$relpath = $node->data_dir . '/'
+  . $node->safe_psql('postgres', q(SELECT pg_relation_filepath('tz')));
+%extinfo_off = ();
+for my $row (
+	split /\n/,
+	$node->safe_psql(
+		'postgres', q(
+	SELECT lp, lp_off + t_hoff, get_byte(t_data, 4), get_byte(t_data, 5)
+		FROM heap_page_items(get_raw_page('tz', 0))
+		ORDER BY lp)))
+{
+	my ($lp, $dataoff, $b4, $b5) = split /\|/, $row;
+	is("$b4/$b5", "$va_1b_e/19",
+		"tuple $lp holds a long on-disk TOAST pointer");
+	$extinfo_off{$lp} = $dataoff + 4 + 2 + 4;
+}
+
+$node->stop;
+open($fh, '+<', $relpath) or BAIL_OUT("open failed: $!");
+binmode $fh;
+
+# The method byte follows va_extinfo, va_valueid and va_toastrelid.
+sub set_method_byte
+{
+	my ($extinfo_off, $byte) = @_;
+
+	sysseek($fh, $extinfo_off + 4 + 4 + 4, 0) or BAIL_OUT("sysseek failed: $!");
+	syswrite($fh, pack('C', $byte)) == 1 or BAIL_OUT("syswrite failed: $!");
+}
+
+# Make the pointer say the value is not compressed, leaving the data as it
+# is: set va_rawsize, just before va_extinfo, to the saved size plus the
+# varlena header, the size of an uncompressed value of that length.
+sub set_uncompressed
+{
+	my ($extinfo_off) = @_;
+	my $code = (pack('L', 1) eq pack('V', 1)) ? 'V' : 'N';
+	my $buf;
+
+	sysseek($fh, $extinfo_off, 0) or BAIL_OUT("sysseek failed: $!");
+	sysread($fh, $buf, 4) == 4 or BAIL_OUT("sysread failed: $!");
+	my $extsize = unpack($code, $buf) & 0x3FFFFFFF;
+	sysseek($fh, $extinfo_off - 4, 0) or BAIL_OUT("sysseek failed: $!");
+	syswrite($fh, pack($code, $extsize + 4)) == 4
+	  or BAIL_OUT("syswrite failed: $!");
+}
+
+# Case 1: long pointer whose method bits do not say "long form"
+set_method_bits($extinfo_off{1}, 0);
+
+# Case 2: long pointer whose method byte names pglz, which uses the plain form
+set_method_byte($extinfo_off{2}, 0);
+
+# Case 3: long pointer whose method byte is not a method at all
+set_method_byte($extinfo_off{3}, 200);
+
+# Case 4: long pointer whose method byte is the invalid ID (3), which lies
+# among the real method IDs once there are more than three of them
+set_method_byte($extinfo_off{4}, 3);
+
+# Case 5: long pointer to a value it says is not compressed
+set_uncompressed($extinfo_off{5});
+
+# Case 6: long pointer whose method byte is the first ID after the last
+# method
+set_method_byte($extinfo_off{6}, 4);
+
+# Row 7 is left alone.
+close($fh) or BAIL_OUT("close failed: $!");
+$node->start;
+
+$result = $node->safe_psql('postgres',
+	q(SELECT offnum, msg FROM verify_heapam('tz', check_toast => true)
+		ORDER BY offnum, msg));
+like(
+	$result,
+	qr/^1\|toast value \d+ has a long TOAST pointer but compression method bits 0$/m,
+	'long pointer without long-form method bits is reported');
+like(
+	$result,
+	qr/^2\|toast value \d+ has a long TOAST pointer with invalid compression method id 0$/m,
+	'long pointer naming a plain-form method is reported');
+like(
+	$result,
+	qr/^3\|toast value \d+ has a long TOAST pointer with invalid compression method id 200$/m,
+	'long pointer with an unknown method byte is reported');
+like(
+	$result,
+	qr/^4\|toast value \d+ has a long TOAST pointer with invalid compression method id 3$/m,
+	'long pointer with the invalid method ID is reported');
+like(
+	$result,
+	qr/^5\|toast value \d+ is not compressed but has a long TOAST pointer$/m,
+	'long pointer to an uncompressed value is reported');
+like(
+	$result,
+	qr/^6\|toast value \d+ has a long TOAST pointer with invalid compression method id 4$/m,
+	'long pointer with the first unused method ID is reported');
+unlike($result, qr/^7\|/m, 'well-formed long pointer is not reported');
+
+for my $id (1, 2, 3, 4)
+{
+	my ($ret, $stdout, $stderr) = $node->psql('postgres',
+		"SELECT pg_column_compression(f) FROM tz WHERE id = $id");
+	like($stderr, qr/compressed data is corrupt/,
+		"pg_column_compression() rejects forged long pointer $id");
+}
+for my $query ('pg_column_compression(f)', 'f')
+{
+	my ($ret, $stdout, $stderr) =
+	  $node->psql('postgres', "SELECT $query FROM tz WHERE id = 5");
+	like(
+		$stderr,
+		qr/is not compressed but has a long TOAST pointer/,
+		"SELECT $query rejects a long pointer to an uncompressed value");
+}
+is( $node->safe_psql(
+		'postgres', q(
+	SELECT f = (SELECT string_agg(encode(sha256((7000 + i)::text::bytea),
+									  'hex'), '')
+				FROM generate_series(1, 60) i) || repeat('x', 12000)
+		FROM tz WHERE id = 7)),
+	't', 'well-formed long pointer still reads back');
+
 done_testing();
diff --git a/doc/src/sgml/catalogs.sgml b/doc/src/sgml/catalogs.sgml
index 07ba05dccd9..c9858e5eaaf 100644
--- a/doc/src/sgml/catalogs.sgml
+++ b/doc/src/sgml/catalogs.sgml
@@ -1267,9 +1267,11 @@
        The current compression method of the column.  Typically this is
        <literal>'\0'</literal> to specify use of the current default setting
        (see <xref linkend="guc-default-toast-compression"/>).  Otherwise,
-       <literal>'p'</literal> selects pglz compression, while
+       <literal>'p'</literal> selects pglz compression,
        <literal>'l'</literal> selects <productname>LZ4</productname>
-       compression.  However, this field is ignored
+       compression, and <literal>'z'</literal> selects
+       <productname>Zstandard</productname> compression.
+       However, this field is ignored
        whenever <structfield>attstorage</structfield> does not allow
        compression.
       </para></entry>
diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index 7018ca1e3ea..188c513ccab 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -10552,9 +10552,11 @@ COPY postgres_log FROM '/full/path/to/logfile.csv' WITH csv;
         the <literal>COMPRESSION</literal> column option in
         <command>CREATE TABLE</command> or
         <command>ALTER TABLE</command>.)
-        The supported compression methods are <literal>pglz</literal> and
+        The supported compression methods are <literal>pglz</literal>,
         (if <productname>PostgreSQL</productname> was compiled with
-        <option>--with-lz4</option>) <literal>lz4</literal>.
+        <option>--with-lz4</option>) <literal>lz4</literal>, and
+        (if <productname>PostgreSQL</productname> was compiled with
+        <option>--with-zstd</option>) <literal>zstd</literal>.
         The default is <literal>lz4</literal> (if available); otherwise,
         <literal>pglz</literal>.
        </para>
diff --git a/doc/src/sgml/installation.sgml b/doc/src/sgml/installation.sgml
index e4159522e18..607faca1113 100644
--- a/doc/src/sgml/installation.sgml
+++ b/doc/src/sgml/installation.sgml
@@ -335,6 +335,7 @@
      <para>
       You need <productname>Zstandard</productname>, if you want to support
       compression of data with that method; see
+      <xref linkend="guc-default-toast-compression"/> and
       <xref linkend="guc-wal-compression"/>.
       The minimum required version is 1.4.0.
      </para>
diff --git a/doc/src/sgml/ref/alter_table.sgml b/doc/src/sgml/ref/alter_table.sgml
index 0f9d698d170..004bfe58812 100644
--- a/doc/src/sgml/ref/alter_table.sgml
+++ b/doc/src/sgml/ref/alter_table.sgml
@@ -464,9 +464,12 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM
       its existing compression method, rather than being recompressed with the
       compression method of the target column.
       The supported compression
-      methods are <literal>pglz</literal> and <literal>lz4</literal>.
-      (<literal>lz4</literal> is available only if <option>--with-lz4</option>
-      was used when building <productname>PostgreSQL</productname>.)  In
+      methods are <literal>pglz</literal>, <literal>lz4</literal>, and
+      <literal>zstd</literal>.  (<literal>lz4</literal> and
+      <literal>zstd</literal> are available only if
+      <option>--with-lz4</option> or <option>--with-zstd</option>,
+      respectively, was used when building
+      <productname>PostgreSQL</productname>.)  In
       addition, <replaceable class="parameter">compression_method</replaceable>
       can be <literal>default</literal>, which selects the default behavior of
       consulting the <xref linkend="guc-default-toast-compression"/> setting
diff --git a/doc/src/sgml/ref/create_table.sgml b/doc/src/sgml/ref/create_table.sgml
index fef24d8f3a2..7340c61c1b1 100644
--- a/doc/src/sgml/ref/create_table.sgml
+++ b/doc/src/sgml/ref/create_table.sgml
@@ -363,9 +363,11 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM
       column storage modes.) Setting this property for a partitioned table
       has no direct effect, because such tables have no storage of their own,
       but the configured value will be inherited by newly-created partitions.
-      The supported compression methods are <literal>pglz</literal> and
-      <literal>lz4</literal>.  (<literal>lz4</literal> is available only if
-      <option>--with-lz4</option> was used when building
+      The supported compression methods are <literal>pglz</literal>,
+      <literal>lz4</literal>, and <literal>zstd</literal>.
+      (<literal>lz4</literal> and <literal>zstd</literal> are available only
+      if <option>--with-lz4</option> or <option>--with-zstd</option>,
+      respectively, was used when building
       <productname>PostgreSQL</productname>.)  In addition,
       <replaceable class="parameter">compression_method</replaceable>
       can be <literal>default</literal> to explicitly specify the default
diff --git a/src/backend/access/common/detoast.c b/src/backend/access/common/detoast.c
index b306d8a4e06..1014fba0594 100644
--- a/src/backend/access/common/detoast.c
+++ b/src/backend/access/common/detoast.c
@@ -262,10 +262,10 @@ detoast_attr_slice(varlena *attr,
 			 * Determine maximum amount of compressed data needed for a prefix
 			 * of a given length (after decompression).
 			 *
-			 * At least for now, if it's LZ4 data, we'll have to fetch the
-			 * whole thing, because there doesn't seem to be an API call to
-			 * determine how much compressed data we need to be sure of being
-			 * able to decompress the required slice.
+			 * At least for now, if it's LZ4 or zstd data, we'll have to fetch
+			 * the whole thing, because there doesn't seem to be an API call
+			 * to determine how much compressed data we need to be sure of
+			 * being able to decompress the required slice.
 			 */
 			if (compress_method == TOAST_PGLZ_COMPRESSION_ID)
 				max_size = pglz_maximum_compressed_size(slicelimit, max_size);
@@ -533,6 +533,8 @@ toast_decompress_datum(varlena *attr)
 			return pglz_decompress_datum(attr);
 		case TOAST_LZ4_COMPRESSION_ID:
 			return lz4_decompress_datum(attr);
+		case TOAST_ZSTD_COMPRESSION_ID:
+			return zstd_decompress_datum(attr);
 		default:
 			elog(ERROR, "invalid compression method id %d", cmid);
 			return NULL;		/* keep compiler quiet */
@@ -585,6 +587,8 @@ toast_decompress_datum_slice(varlena *attr, int32 slicelength)
 			return pglz_decompress_datum_slice(attr, slicelength);
 		case TOAST_LZ4_COMPRESSION_ID:
 			return lz4_decompress_datum_slice(attr, slicelength);
+		case TOAST_ZSTD_COMPRESSION_ID:
+			return zstd_decompress_datum_slice(attr, slicelength);
 		default:
 			elog(ERROR, "invalid compression method id %d", cmid);
 			return NULL;		/* keep compiler quiet */
diff --git a/src/backend/access/common/toast_compression.c b/src/backend/access/common/toast_compression.c
index 0d5ed9a81d9..19642c3b3f4 100644
--- a/src/backend/access/common/toast_compression.c
+++ b/src/backend/access/common/toast_compression.c
@@ -17,15 +17,99 @@
 #include <lz4.h>
 #endif
 
+#ifdef USE_ZSTD
+#include <zstd.h>
+#endif
+
 #include "access/detoast.h"
 #include "access/toast_compression.h"
 #include "common/pg_lzcompress.h"
+#include "miscadmin.h"
 #include "utils/memutils.h"
 #include "varatt.h"
 
 /* GUC */
 int			default_toast_compression = DEFAULT_TOAST_COMPRESSION;
 
+#ifdef USE_ZSTD
+/*
+ * zstd decompression context, created on first use and kept for the life of
+ * the backend: creating one per value costs more than decompressing a small
+ * value.
+ *
+ * It is reset at the start of each use.  This is required, not an
+ * optimization: a slice stops in the middle of a frame, and an error can
+ * leave a frame half decoded, so without the reset the next value's decoding
+ * would continue the previous frame and fail or return wrong data.  Anything
+ * else that reuses this context must go through zstd_get_dctx().
+ *
+ * The scope is the backend because detoasting has no owning object to tie
+ * the context to, unlike WAL decoding, which keeps its context in the
+ * XLogReaderState.  WAL compression likewise keeps one context for the
+ * backend.
+ *
+ * zstd allocates the context with malloc(), so its memory is not visible in
+ * pg_backend_memory_contexts.  After full decompressions it is about 100kB.
+ * Slices also leave the streaming decoder's buffer in it, the frame's window
+ * plus a block.  The window size comes from the frame header, so it is
+ * capped at ZSTD_TOAST_WINDOWLOG_MAX, which the default compression level
+ * never exceeds; a corrupt header cannot make the context grow beyond that.
+ * From libzstd 1.4.5, zstd shrinks the buffer by itself once later uses no
+ * longer need it.
+ */
+
+static ZSTD_DCtx *zstd_dctx = NULL;
+
+static ZSTD_DCtx *
+zstd_get_dctx(void)
+{
+	if (zstd_dctx == NULL)
+	{
+		size_t		ret;
+
+		zstd_dctx = ZSTD_createDCtx();
+		if (zstd_dctx == NULL)
+			elog(ERROR, "could not create zstd decompression context");
+		/* a session reset keeps parameters, so this is set once */
+		ret = ZSTD_DCtx_setParameter(zstd_dctx, ZSTD_d_windowLogMax,
+									 ZSTD_TOAST_WINDOWLOG_MAX);
+		if (ZSTD_isError(ret))
+		{
+			ZSTD_freeDCtx(zstd_dctx);
+			zstd_dctx = NULL;
+			elog(ERROR, "could not set zstd decompression window: %s",
+				 ZSTD_getErrorName(ret));
+		}
+	}
+	else
+		ZSTD_DCtx_reset(zstd_dctx, ZSTD_reset_session_only);
+	return zstd_dctx;
+}
+
+/*
+ * A backend-lifetime ZSTD_CCtx for plain (non-dictionary) compression, kept
+ * for the same reason as the decompression context above: a one-shot
+ * ZSTD_compress() allocates and frees a compression context for every value,
+ * sized to the input, from about 90kB for a 4kB value up to about 1.3MB for
+ * values of 1MB or more; for a bulk load that dominates.  The context keeps
+ * the size of the largest value compressed so far, outside any memory
+ * context like the decompression context.
+ */
+static ZSTD_CCtx *zstd_cctx = NULL;
+
+static ZSTD_CCtx *
+zstd_get_cctx(void)
+{
+	if (zstd_cctx == NULL)
+	{
+		zstd_cctx = ZSTD_createCCtx();
+		if (zstd_cctx == NULL)
+			elog(ERROR, "could not create zstd compression context");
+	}
+	return zstd_cctx;
+}
+#endif
+
 #define NO_COMPRESSION_SUPPORT(method) \
 	ereport(ERROR, \
 			(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), \
@@ -282,6 +366,235 @@ lz4_decompress_datum_slice(const varlena *value, int32 slicelength)
 #endif
 }
 
+/*
+ * Compress a varlena using Zstandard.
+ *
+ * Returns the compressed varlena, or NULL if the data is incompressible.
+ *
+ * Unlike pglz and lz4, zstd's method ID does not fit in the two method bits
+ * of the compressed header, so the datum is laid out with the long form of
+ * the header (VARHDRSZ_COMPRESSED_LONG), whose extra byte will receive the ID.
+ */
+varlena *
+zstd_compress_datum(const varlena *value)
+{
+#ifndef USE_ZSTD
+	NO_COMPRESSION_SUPPORT("zstd");
+	return NULL;				/* keep compiler quiet */
+#else
+	int32		valsize;
+	size_t		len;
+	size_t		max_size;
+	varlena    *tmp = NULL;
+
+	valsize = VARSIZE_ANY_EXHDR(value);
+
+	/*
+	 * Figure out the maximum possible size of the zstd output, add the bytes
+	 * that will be needed for varlena overhead, and allocate that amount. As
+	 * for lz4, verify the bound rather than trust the library.
+	 */
+	max_size = ZSTD_compressBound(valsize);
+	if (ZSTD_isError(max_size) || !AllocSizeIsValid(max_size))
+		elog(ERROR, "toast object size is too big");
+	tmp = (varlena *) palloc(max_size + VARHDRSZ_COMPRESSED_LONG);
+
+	len = ZSTD_compressCCtx(zstd_get_cctx(),
+							(char *) tmp + VARHDRSZ_COMPRESSED_LONG,
+							max_size,
+							VARDATA_ANY(value),
+							valsize,
+							ZSTD_CLEVEL_DEFAULT);
+	if (ZSTD_isError(len))
+		elog(ERROR, "zstd compression failed: %s", ZSTD_getErrorName(len));
+
+	/* data is incompressible so just free the memory and return NULL */
+	if (len > (size_t) valsize)
+	{
+		pfree(tmp);
+		return NULL;
+	}
+
+	SET_VARSIZE_COMPRESSED(tmp, len + VARHDRSZ_COMPRESSED_LONG);
+
+	return tmp;
+#endif
+}
+
+/*
+ * Decompress a varlena that was compressed using Zstandard.
+ */
+varlena *
+zstd_decompress_datum(const varlena *value)
+{
+#ifndef USE_ZSTD
+	NO_COMPRESSION_SUPPORT("zstd");
+	return NULL;				/* keep compiler quiet */
+#else
+	size_t		rawsize;
+	varlena    *result;
+
+	Assert(VARDATA_COMPRESSED_GET_COMPRESS_METHOD(value) == TOAST_ZSTD_COMPRESSION_ID);
+
+	/*
+	 * The compressed size is passed to zstd as a size_t, so check it cannot
+	 * underflow; pglz and lz4 take a signed size and reject it themselves.
+	 */
+	if (VARSIZE(value) < VARHDRSZ_COMPRESSED_LONG)
+		ereport(ERROR,
+				(errcode(ERRCODE_DATA_CORRUPTED),
+				 errmsg_internal("compressed zstd data is corrupt")));
+
+	/*
+	 * Allocate memory for the uncompressed data.  VARLENA_EXTSIZE_MASK
+	 * protects this against overflow.
+	 */
+	Assert(AllocSizeIsValid(VARDATA_COMPRESSED_GET_EXTSIZE(value)));
+	result = (varlena *) palloc(VARDATA_COMPRESSED_GET_EXTSIZE(value) + VARHDRSZ);
+
+	/*
+	 * Decompress the data.  zstd checks the frame against its own recorded
+	 * content size; also check that it matches the size in our header, as
+	 * pglz does.
+	 */
+	rawsize = ZSTD_decompressDCtx(zstd_get_dctx(),
+								  VARDATA(result),
+								  VARDATA_COMPRESSED_GET_EXTSIZE(value),
+								  (const char *) value + VARHDRSZ_COMPRESSED_LONG,
+								  VARSIZE(value) - VARHDRSZ_COMPRESSED_LONG);
+	if (ZSTD_isError(rawsize) ||
+		rawsize != VARDATA_COMPRESSED_GET_EXTSIZE(value))
+		ereport(ERROR,
+				(errcode(ERRCODE_DATA_CORRUPTED),
+				 errmsg_internal("compressed zstd data is corrupt")));
+
+	SET_VARSIZE(result, rawsize + VARHDRSZ);
+
+	return result;
+#endif
+}
+
+/*
+ * Decompress part of a varlena that was compressed using Zstandard.
+ */
+varlena *
+zstd_decompress_datum_slice(const varlena *value, int32 slicelength)
+{
+#ifndef USE_ZSTD
+	NO_COMPRESSION_SUPPORT("zstd");
+	return NULL;				/* keep compiler quiet */
+#else
+	ZSTD_DCtx  *dctx;
+	ZSTD_inBuffer inbuf;
+	ZSTD_outBuffer outbuf;
+	const char *src;
+	size_t		srclen;
+	varlena    *result;
+	bool		failed = false;
+
+	Assert(VARDATA_COMPRESSED_GET_COMPRESS_METHOD(value) == TOAST_ZSTD_COMPRESSION_ID);
+
+	/*
+	 * The one-shot API can only decompress a whole frame, so use the
+	 * streaming API instead: it stops as soon as the output buffer is full.
+	 * Note that this means we never reach the end of the frame, so its
+	 * checksum (if any) is not verified; that matches the behavior of the
+	 * other methods here.
+	 *
+	 * Also note that zstd cannot stop inside a block, and a block holds up to
+	 * 128 kB of uncompressed data, so for values smaller than that this
+	 * decodes the whole value anyway and only saves the copy of the rest. The
+	 * saving over a full decompression starts with larger values.
+	 */
+
+	/* As in zstd_decompress_datum(), the compressed size must not underflow */
+	if (VARSIZE(value) < VARHDRSZ_COMPRESSED_LONG)
+		ereport(ERROR,
+				(errcode(ERRCODE_DATA_CORRUPTED),
+				 errmsg_internal("compressed zstd data is corrupt")));
+
+	src = (const char *) value + VARHDRSZ_COMPRESSED_LONG;
+	srclen = VARSIZE(value) - VARHDRSZ_COMPRESSED_LONG;
+
+	/*
+	 * Unlike the one-shot API, the streaming decoder does not check the
+	 * frame's recorded content size against anything, so check it against the
+	 * size in our header here.  Our frames always record it.
+	 */
+	if (ZSTD_getFrameContentSize(src, srclen) !=
+		(unsigned long long) VARDATA_COMPRESSED_GET_EXTSIZE(value))
+		ereport(ERROR,
+				(errcode(ERRCODE_DATA_CORRUPTED),
+				 errmsg_internal("compressed zstd data is corrupt")));
+
+	/*
+	 * Allocate memory for the uncompressed slice.  Caller must have checked
+	 * the requested size, but verify.
+	 */
+	if (!AllocSizeIsValid(slicelength))
+		elog(ERROR, "toast object size is too big");
+	result = (varlena *) palloc(slicelength + VARHDRSZ);
+
+	dctx = zstd_get_dctx();
+
+	inbuf.src = src;
+	inbuf.size = 0;
+	inbuf.pos = 0;
+	outbuf.dst = VARDATA(result);
+	outbuf.size = slicelength;
+	outbuf.pos = 0;
+
+	/*
+	 * Feed the input a chunk at a time, so that a long decode can be
+	 * interrupted.
+	 */
+	while (outbuf.pos < outbuf.size)
+	{
+		size_t		ret;
+
+		CHECK_FOR_INTERRUPTS();
+		if (inbuf.pos == inbuf.size)
+		{
+			if (inbuf.size == srclen)
+			{
+				/* all input consumed without filling the output */
+				failed = true;
+				break;
+			}
+			inbuf.size = Min(srclen, inbuf.size + ZSTD_DStreamInSize());
+		}
+		ret = ZSTD_decompressStream(dctx, &outbuf, &inbuf);
+
+		if (ZSTD_isError(ret))
+		{
+			failed = true;
+			break;
+		}
+
+		/*
+		 * A zero return means the frame is fully decoded.  If we could not
+		 * fill the output buffer by then the data must be truncated or
+		 * corrupt, since the caller has already established that the value
+		 * decompresses to more than slicelength bytes.
+		 */
+		if (ret == 0)
+		{
+			failed = (outbuf.pos < outbuf.size);
+			break;
+		}
+	}
+
+	if (failed)
+		ereport(ERROR,
+				(errcode(ERRCODE_DATA_CORRUPTED),
+				 errmsg_internal("compressed zstd data is corrupt")));
+
+	SET_VARSIZE(result, outbuf.pos + VARHDRSZ);
+
+	return result;
+#endif
+}
+
 /*
  * Extract compression ID from a varlena.
  *
@@ -341,6 +654,13 @@ CompressionNameToMethod(const char *compression)
 #endif
 		return TOAST_LZ4_COMPRESSION;
 	}
+	else if (strcmp(compression, "zstd") == 0)
+	{
+#ifndef USE_ZSTD
+		NO_COMPRESSION_SUPPORT("zstd");
+#endif
+		return TOAST_ZSTD_COMPRESSION;
+	}
 
 	return InvalidCompressionMethod;
 }
@@ -357,6 +677,8 @@ GetCompressionMethodName(char method)
 			return "pglz";
 		case TOAST_LZ4_COMPRESSION:
 			return "lz4";
+		case TOAST_ZSTD_COMPRESSION:
+			return "zstd";
 		default:
 			elog(ERROR, "invalid compression method %c", method);
 			return NULL;		/* keep compiler quiet */
diff --git a/src/backend/access/common/toast_internals.c b/src/backend/access/common/toast_internals.c
index 6a9a2a85e75..174c7197b3c 100644
--- a/src/backend/access/common/toast_internals.c
+++ b/src/backend/access/common/toast_internals.c
@@ -108,6 +108,10 @@ toast_compress_datum(Datum value, char cmethod)
 			tmp = lz4_compress_datum((const varlena *) DatumGetPointer(value));
 			cmid = TOAST_LZ4_COMPRESSION_ID;
 			break;
+		case TOAST_ZSTD_COMPRESSION:
+			tmp = zstd_compress_datum((const varlena *) DatumGetPointer(value));
+			cmid = TOAST_ZSTD_COMPRESSION_ID;
+			break;
 		default:
 			elog(ERROR, "invalid compression method %c", cmethod);
 	}
diff --git a/src/backend/utils/adt/varlena.c b/src/backend/utils/adt/varlena.c
index 6c95fcb24b7..25ca69ce78f 100644
--- a/src/backend/utils/adt/varlena.c
+++ b/src/backend/utils/adt/varlena.c
@@ -4240,6 +4240,9 @@ pg_column_compression(PG_FUNCTION_ARGS)
 		case TOAST_LZ4_COMPRESSION_ID:
 			result = "lz4";
 			break;
+		case TOAST_ZSTD_COMPRESSION_ID:
+			result = "zstd";
+			break;
 		default:
 			elog(ERROR, "invalid compression method id %d", cmid);
 	}
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index a05fc356fc3..7802557b5f4 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -481,6 +481,9 @@ static const struct config_enum_entry default_toast_compression_options[] = {
 	{"pglz", TOAST_PGLZ_COMPRESSION, false},
 #ifdef  USE_LZ4
 	{"lz4", TOAST_LZ4_COMPRESSION, false},
+#endif
+#ifdef  USE_ZSTD
+	{"zstd", TOAST_ZSTD_COMPRESSION, false},
 #endif
 	{NULL, 0, false}
 };
diff --git a/src/backend/utils/misc/postgresql.conf.sample b/src/backend/utils/misc/postgresql.conf.sample
index 01f98de8a9f..c4a61f4d7fb 100644
--- a/src/backend/utils/misc/postgresql.conf.sample
+++ b/src/backend/utils/misc/postgresql.conf.sample
@@ -806,7 +806,7 @@
 #row_security = on
 #default_table_access_method = 'heap'
 #default_tablespace = ''                # a tablespace name, '' uses the default
-#default_toast_compression = pglz       # pglz or lz4
+#default_toast_compression = pglz       # pglz, lz4, or zstd
 #temp_tablespaces = ''                  # a list of tablespace names, '' uses
                                         # only default tablespace
 #check_function_bodies = on
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index a3f38f3b886..082b6b6c84c 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -17955,6 +17955,9 @@ dumpTableSchema(Archive *fout, const TableInfo *tbinfo)
 					case 'l':
 						cmname = "lz4";
 						break;
+					case 'z':
+						cmname = "zstd";
+						break;
 					default:
 						cmname = NULL;
 						break;
diff --git a/src/bin/pg_dump/t/006_pg_dump_compress.pl b/src/bin/pg_dump/t/006_pg_dump_compress.pl
index 32475c05c18..01c1612696d 100644
--- a/src/bin/pg_dump/t/006_pg_dump_compress.pl
+++ b/src/bin/pg_dump/t/006_pg_dump_compress.pl
@@ -454,6 +454,24 @@ my %tests = (
 		like => {%full_runs},
 	},
 
+	'CREATE TABLE test_compression_zstd' => {
+		create_order => 4,
+		create_sql => 'CREATE TABLE test_compression_zstd (
+						   col1 int,
+						   col2 text COMPRESSION zstd
+					   );',
+		regexp => qr/^
+			\QCREATE TABLE public.test_compression_zstd (\E\n
+			\s+\Qcol1 integer,\E\n
+			\s+\Qcol2 text\E\n
+			\);\n
+			.*
+			\QALTER TABLE ONLY public.test_compression_zstd ALTER COLUMN col2 SET COMPRESSION zstd;\E\n
+			/xms,
+		compile_option => 'zstd',
+		like => {%full_runs},
+	},
+
 	# Create a large object so we can test compression of blobs.toc
 	'LO create (using lo_from_bytea)' => {
 		create_order => 50,
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index e4a4ba47280..77475632c11 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -2088,8 +2088,9 @@ describeOneTableDetails(const char *schemaname,
 			/* these strings are literal in our syntax, so not translated. */
 			printTableAddCell(&cont, (compression[0] == 'p' ? "pglz" :
 									  (compression[0] == 'l' ? "lz4" :
-									   (compression[0] == '\0' ? "" :
-										"???"))),
+									   (compression[0] == 'z' ? "zstd" :
+										(compression[0] == '\0' ? "" :
+										 "???")))),
 							  false, false);
 		}
 
diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c
index 96de78cd087..bd1ae0b7a8e 100644
--- a/src/bin/psql/tab-complete.in.c
+++ b/src/bin/psql/tab-complete.in.c
@@ -2972,7 +2972,7 @@ match_previous_words(int pattern_id,
 	/* ALTER TABLE ALTER [COLUMN] <foo> SET COMPRESSION */
 	else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "COMPRESSION") ||
 			 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "COMPRESSION"))
-		COMPLETE_WITH("DEFAULT", "PGLZ", "LZ4");
+		COMPLETE_WITH("DEFAULT", "PGLZ", "LZ4", "ZSTD");
 	/* ALTER TABLE ALTER [COLUMN] <foo> SET EXPRESSION */
 	else if (Matches("ALTER", "TABLE", MatchAny, "ALTER", "COLUMN", MatchAny, "SET", "EXPRESSION") ||
 			 Matches("ALTER", "TABLE", MatchAny, "ALTER", MatchAny, "SET", "EXPRESSION"))
diff --git a/src/include/access/toast_compression.h b/src/include/access/toast_compression.h
index 888269393ba..9a488a39c21 100644
--- a/src/include/access/toast_compression.h
+++ b/src/include/access/toast_compression.h
@@ -50,6 +50,7 @@ typedef enum ToastCompressionId
 {
 	TOAST_PGLZ_COMPRESSION_ID = 0,
 	TOAST_LZ4_COMPRESSION_ID = 1,
+	TOAST_ZSTD_COMPRESSION_ID = 2,
 	TOAST_INVALID_COMPRESSION_ID = 3,
 } ToastCompressionId;
 
@@ -57,7 +58,7 @@ StaticAssertDecl(TOAST_INVALID_COMPRESSION_ID == VARLENA_COMPRESS_METHOD_LONG,
 				 "TOAST_INVALID_COMPRESSION_ID must match VARLENA_COMPRESS_METHOD_LONG");
 
 /* Largest compression method ID in use; IDs above it are not methods. */
-#define TOAST_LAST_COMPRESSION_ID	TOAST_LZ4_COMPRESSION_ID
+#define TOAST_LAST_COMPRESSION_ID	TOAST_ZSTD_COMPRESSION_ID
 
 /*
  * Does this compression method ID need a byte of its own?
@@ -140,6 +141,7 @@ toast_inline_compression_id(const void *PTR)
  */
 #define TOAST_PGLZ_COMPRESSION			'p'
 #define TOAST_LZ4_COMPRESSION			'l'
+#define TOAST_ZSTD_COMPRESSION			'z'
 #define InvalidCompressionMethod		'\0'
 
 #define CompressionMethodIsValid(cm)  ((cm) != InvalidCompressionMethod)
@@ -166,6 +168,20 @@ extern varlena *lz4_decompress_datum(const varlena *value);
 extern varlena *lz4_decompress_datum_slice(const varlena *value,
 										   int32 slicelength);
 
+/*
+ * Largest zstd window, as a power of two, that TOAST decompression accepts:
+ * the window size comes from the frame header, and decides how much memory
+ * a decompression context keeps.  The default compression level never uses
+ * more than 2^21.
+ */
+#define ZSTD_TOAST_WINDOWLOG_MAX	23
+
+/* zstd compression/decompression routines */
+extern varlena *zstd_compress_datum(const varlena *value);
+extern varlena *zstd_decompress_datum(const varlena *value);
+extern varlena *zstd_decompress_datum_slice(const varlena *value,
+											int32 slicelength);
+
 /* other stuff */
 extern ToastCompressionId toast_get_compression_id(varlena *attr);
 extern char CompressionNameToMethod(const char *compression);
diff --git a/src/test/regress/expected/compression_zstd.out b/src/test/regress/expected/compression_zstd.out
new file mode 100644
index 00000000000..d79a484363d
--- /dev/null
+++ b/src/test/regress/expected/compression_zstd.out
@@ -0,0 +1,859 @@
+-- Tests for TOAST compression with zstd
+SELECT NOT(enumvals @> '{zstd}') AS skip_test FROM pg_settings WHERE
+  name = 'default_toast_compression' \gset
+\if :skip_test
+   \echo '*** skipping TOAST tests with zstd (not supported) ***'
+   \quit
+\endif
+CREATE SCHEMA zstd;
+SET search_path TO zstd, public;
+\set HIDE_TOAST_COMPRESSION false
+-- Ensure we get stable results regardless of the installation's default.
+-- We rely on this GUC value for a few tests.
+SET default_toast_compression = 'pglz';
+-- Helpers.  Hash output is poorly compressible, so values built from it
+-- stay large after compression and are stored out of line; a bytea of raw
+-- hash bytes is not compressible at all.  None of the checks below print
+-- compressed sizes, which depend on the zstd version.
+CREATE FUNCTION large_val_zstd() RETURNS TEXT LANGUAGE SQL AS
+'select array_agg(fipshash(g::text))::text from generate_series(1, 256) g';
+CREATE FUNCTION incompressible_val() RETURNS bytea LANGUAGE SQL AS
+$$ select decode(string_agg(fipshash(g::text), '' order by g), 'hex')
+   from generate_series(1, 200) g $$;
+----------------------------------------------------------------------
+-- DDL
+----------------------------------------------------------------------
+-- test creating table with compression method
+CREATE TABLE cmdata_pglz(f1 text COMPRESSION pglz);
+CREATE INDEX idx ON cmdata_pglz(f1);
+INSERT INTO cmdata_pglz VALUES(repeat('1234567890', 1000));
+\d+ cmdata_pglz
+                                       Table "zstd.cmdata_pglz"
+ Column | Type | Collation | Nullable | Default | Storage  | Compression | Stats target | Description 
+--------+------+-----------+----------+---------+----------+-------------+--------------+-------------
+ f1     | text |           |          |         | extended | pglz        |              | 
+Indexes:
+    "idx" btree (f1)
+
+CREATE TABLE cmdata_zstd(f1 TEXT COMPRESSION zstd);
+INSERT INTO cmdata_zstd VALUES(repeat('1234567890', 1004));
+\d+ cmdata_zstd
+                                       Table "zstd.cmdata_zstd"
+ Column | Type | Collation | Nullable | Default | Storage  | Compression | Stats target | Description 
+--------+------+-----------+----------+---------+----------+-------------+--------------+-------------
+ f1     | text |           |          |         | extended | zstd        |              | 
+
+-- the method name is an identifier, so case does not matter
+CREATE TABLE cmupper(f1 text COMPRESSION ZSTD);
+\d+ cmupper
+                                         Table "zstd.cmupper"
+ Column | Type | Collation | Nullable | Default | Storage  | Compression | Stats target | Description 
+--------+------+-----------+----------+---------+----------+-------------+--------------+-------------
+ f1     | text |           |          |         | extended | zstd        |              | 
+
+DROP TABLE cmupper;
+-- a domain over a varlena type can be compressed too
+CREATE DOMAIN zstdtext AS text;
+CREATE TABLE cmdomain(f1 zstdtext COMPRESSION zstd);
+INSERT INTO cmdomain VALUES (repeat('1234567890', 1004));
+\d+ cmdomain
+                                          Table "zstd.cmdomain"
+ Column |   Type   | Collation | Nullable | Default | Storage  | Compression | Stats target | Description 
+--------+----------+-----------+----------+---------+----------+-------------+--------------+-------------
+ f1     | zstdtext |           |          |         | extended | zstd        |              | 
+
+SELECT pg_column_compression(f1), length(f1) FROM cmdomain;
+ pg_column_compression | length 
+-----------------------+--------
+ zstd                  |  10040
+(1 row)
+
+DROP TABLE cmdomain;
+DROP DOMAIN zstdtext;
+-- errors: incompressible data type, unknown method
+CREATE TABLE cmbad(f1 int COMPRESSION zstd);
+ERROR:  column data type integer does not support compression
+CREATE TABLE cmbad(f1 text);
+ALTER TABLE cmbad ALTER COLUMN f1 SET COMPRESSION zstd_nodict;
+ERROR:  invalid compression method "zstd_nodict"
+DROP TABLE cmbad;
+----------------------------------------------------------------------
+-- Compressed-in-line values
+----------------------------------------------------------------------
+-- verify stored compression method in the data, and that compression
+-- did save space
+SELECT pg_column_compression(f1),
+       pg_column_size(f1) < length(f1) AS smaller,
+       pg_column_toast_chunk_id(f1) IS NULL AS is_inline
+  FROM cmdata_zstd;
+ pg_column_compression | smaller | is_inline 
+-----------------------+---------+-----------
+ zstd                  | t       | t
+(1 row)
+
+-- decompress data slice
+SELECT SUBSTR(f1, 200, 5) FROM cmdata_pglz;
+ substr 
+--------
+ 01234
+(1 row)
+
+SELECT SUBSTR(f1, 2000, 50) FROM cmdata_zstd;
+                       substr                       
+----------------------------------------------------
+ 01234567890123456789012345678901234567890123456789
+(1 row)
+
+-- check that slice decompression agrees with full decompression, at the
+-- start, in the middle and at the very end of the value
+SELECT SUBSTR(f1, 1, 100) = SUBSTR(repeat('1234567890', 1004), 1, 100) AS ok_head,
+       SUBSTR(f1, 5000, 100) = SUBSTR(repeat('1234567890', 1004), 5000, 100) AS ok_mid,
+       SUBSTR(f1, 10036, 5) = SUBSTR(repeat('1234567890', 1004), 10036, 5) AS ok_tail,
+       length(f1) AS len
+  FROM cmdata_zstd;
+ ok_head | ok_mid | ok_tail |  len  
+---------+--------+---------+-------
+ t       | t      | t       | 10040
+(1 row)
+
+-- slices of one byte, past the end, and longer than the whole value (the
+-- latter falls back to a full decompression)
+SELECT left(f1, 1) AS first_char,
+       right(f1, 1) AS last_char,
+       SUBSTR(f1, 10040, 1) AS at_end,
+       SUBSTR(f1, 10041, 10) = '' AS past_end,
+       length(SUBSTR(f1, 1, 1000000)) AS full_len
+  FROM cmdata_zstd;
+ first_char | last_char | at_end | past_end | full_len 
+------------+-----------+--------+----------+----------
+ 1          | 0         | 0      | t        |    10040
+(1 row)
+
+----------------------------------------------------------------------
+-- Values that do not get compressed
+----------------------------------------------------------------------
+-- values below the TOAST threshold are stored as they are; NULL and the
+-- empty string are fine too
+CREATE TABLE cmshort(f1 text COMPRESSION zstd);
+INSERT INTO cmshort VALUES (repeat('x', 100)), (''), (NULL);
+SELECT pg_column_compression(f1), length(f1) FROM cmshort ORDER BY length(f1);
+ pg_column_compression | length 
+-----------------------+--------
+                       |      0
+                       |    100
+                       |       
+(3 rows)
+
+DROP TABLE cmshort;
+-- data that zstd cannot shrink is stored uncompressed, out of line if
+-- needed, with no compression method recorded
+CREATE TABLE cmincompressible(f1 bytea COMPRESSION zstd);
+INSERT INTO cmincompressible SELECT incompressible_val();
+SELECT pg_column_compression(f1) IS NULL AS uncompressed,
+       pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       pg_column_size(f1) = octet_length(f1) AS same_size,
+       length(f1) AS len,
+       f1 = incompressible_val() AS ok_full,
+       substr(f1, 3000, 40) = substr(incompressible_val(), 3000, 40) AS ok_slice
+  FROM cmincompressible;
+ uncompressed | is_external | same_size | len  | ok_full | ok_slice 
+--------------+-------------+-----------+------+---------+----------
+ t            | t           | t         | 3200 | t       | t
+(1 row)
+
+DROP TABLE cmincompressible;
+----------------------------------------------------------------------
+-- Other varlena types
+----------------------------------------------------------------------
+-- binary data with zero and high bytes
+CREATE TABLE cmbytea(f1 bytea COMPRESSION zstd);
+INSERT INTO cmbytea VALUES (decode(repeat('00ff10', 2000), 'hex'));
+SELECT pg_column_compression(f1), length(f1),
+       f1 = decode(repeat('00ff10', 2000), 'hex') AS ok_full,
+       get_byte(f1, 0) AS byte0, get_byte(f1, 1) AS byte1,
+       substr(f1, 3001, 3) = decode('00ff10', 'hex') AS ok_slice
+  FROM cmbytea;
+ pg_column_compression | length | ok_full | byte0 | byte1 | ok_slice 
+-----------------------+--------+---------+-------+-------+----------
+ zstd                  |   6000 | t       |     0 |   255 | t
+(1 row)
+
+DROP TABLE cmbytea;
+-- jsonb, compressed inline and out of line
+CREATE TABLE cmjsonb(j jsonb COMPRESSION zstd);
+INSERT INTO cmjsonb SELECT jsonb_build_object('k', repeat('v', 5000), 'n', 1);
+INSERT INTO cmjsonb SELECT jsonb_object_agg(g::text, fipshash(g::text))
+  FROM generate_series(1, 300) g;
+SELECT pg_column_compression(j),
+       pg_column_toast_chunk_id(j) IS NOT NULL AS is_external,
+       length(j ->> 'k') AS klen,
+       j ->> 'n' AS n,
+       j ->> '150' = fipshash('150') AS ok_150
+  FROM cmjsonb ORDER BY is_external;
+ pg_column_compression | is_external | klen | n | ok_150 
+-----------------------+-------------+------+---+--------
+ zstd                  | f           | 5000 | 1 | 
+ zstd                  | t           |      |   | t
+(2 rows)
+
+DROP TABLE cmjsonb;
+-- arrays
+CREATE TABLE cmarray(f1 text[] COMPRESSION zstd);
+INSERT INTO cmarray SELECT array_agg(repeat('x', 100) || g ORDER BY g)
+  FROM generate_series(1, 200) g;
+SELECT pg_column_compression(f1), array_length(f1, 1) AS n,
+       f1[1] = repeat('x', 100) || '1' AS ok_first,
+       f1[200] = repeat('x', 100) || '200' AS ok_last
+  FROM cmarray;
+ pg_column_compression |  n  | ok_first | ok_last 
+-----------------------+-----+----------+---------
+ zstd                  | 200 | t        | t
+(1 row)
+
+DROP TABLE cmarray;
+----------------------------------------------------------------------
+-- Moving data between tables and methods
+----------------------------------------------------------------------
+-- copy with table creation
+SELECT * INTO cmmove1 FROM cmdata_zstd;
+\d+ cmmove1
+                                         Table "zstd.cmmove1"
+ Column | Type | Collation | Nullable | Default | Storage  | Compression | Stats target | Description 
+--------+------+-----------+----------+---------+----------+-------------+--------------+-------------
+ f1     | text |           |          |         | extended |             |              | 
+
+SELECT pg_column_compression(f1) FROM cmmove1;
+ pg_column_compression 
+-----------------------
+ zstd
+(1 row)
+
+-- test LIKE INCLUDING COMPRESSION.  The GUC default_toast_compression
+-- has no effect, the compression method is taken from the table being copied.
+CREATE TABLE cmdata2 (LIKE cmdata_zstd INCLUDING COMPRESSION);
+\d+ cmdata2
+                                         Table "zstd.cmdata2"
+ Column | Type | Collation | Nullable | Default | Storage  | Compression | Stats target | Description 
+--------+------+-----------+----------+---------+----------+-------------+--------------+-------------
+ f1     | text |           |          |         | extended | zstd        |              | 
+
+DROP TABLE cmdata2;
+-- copy to existing table: a compressed datum keeps its own method, in both
+-- directions, so a table can hold values compressed with different methods
+CREATE TABLE cmmove3(f1 text COMPRESSION pglz);
+INSERT INTO cmmove3 SELECT * FROM cmdata_pglz;
+INSERT INTO cmmove3 SELECT * FROM cmdata_zstd;
+SELECT pg_column_compression(f1) FROM cmmove3 ORDER BY 1;
+ pg_column_compression 
+-----------------------
+ pglz
+ zstd
+(2 rows)
+
+INSERT INTO cmdata_zstd SELECT * FROM cmdata_pglz;
+SELECT pg_column_compression(f1), count(*) FROM cmdata_zstd GROUP BY 1 ORDER BY 1;
+ pg_column_compression | count 
+-----------------------+-------
+ pglz                  |     1
+ zstd                  |     1
+(2 rows)
+
+DELETE FROM cmdata_zstd WHERE pg_column_compression(f1) = 'pglz';
+-- update using datum from different table with zstd data.
+CREATE TABLE cmmove2(f1 text COMPRESSION pglz);
+INSERT INTO cmmove2 VALUES (repeat('1234567890', 1004));
+SELECT pg_column_compression(f1) FROM cmmove2;
+ pg_column_compression 
+-----------------------
+ pglz
+(1 row)
+
+UPDATE cmmove2 SET f1 = cmdata_zstd.f1 FROM cmdata_zstd;
+SELECT pg_column_compression(f1) FROM cmmove2;
+ pg_column_compression 
+-----------------------
+ zstd
+(1 row)
+
+----------------------------------------------------------------------
+-- Externally stored compressed values
+----------------------------------------------------------------------
+CREATE TABLE cmdata2 (f1 text COMPRESSION zstd);
+INSERT INTO cmdata2 SELECT large_val_zstd() || repeat('a', 4000);
+SELECT pg_column_compression(f1), pg_column_size(f1) < length(f1) AS smaller
+  FROM cmdata2;
+ pg_column_compression | smaller 
+-----------------------+---------
+ zstd                  | t
+(1 row)
+
+SELECT SUBSTR(f1, 200, 5) FROM cmdata2;
+ substr 
+--------
+ 79026
+(1 row)
+
+SELECT SUBSTR(f1, 200, 5) = SUBSTR(large_val_zstd() || repeat('a', 4000), 200, 5) AS ok_slice
+  FROM cmdata2;
+ ok_slice 
+----------
+ t
+(1 row)
+
+DROP TABLE cmdata2;
+-- test that both TOAST value ID widths carry the compression method through
+-- an external TOAST pointer.  The data here is poorly compressible on
+-- purpose, so that the value is certain to be stored out of line.
+CREATE TABLE cmdata_oid(f1 text COMPRESSION zstd)
+  WITH (toast_value_type = 'oid');
+CREATE TABLE cmdata_oid8(f1 text COMPRESSION zstd)
+  WITH (toast_value_type = 'oid8');
+INSERT INTO cmdata_oid SELECT large_val_zstd();
+INSERT INTO cmdata_oid8 SELECT large_val_zstd();
+-- confirm the values really are out of line, so that the checks below
+-- exercise the external TOAST pointer rather than the inline header
+SELECT pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       pg_column_compression(f1) FROM cmdata_oid;
+ is_external | pg_column_compression 
+-------------+-----------------------
+ t           | zstd
+(1 row)
+
+SELECT pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       pg_column_compression(f1) FROM cmdata_oid8;
+ is_external | pg_column_compression 
+-------------+-----------------------
+ t           | zstd
+(1 row)
+
+SELECT length(f1) = length(large_val_zstd()) AS ok_len,
+       f1 = large_val_zstd() AS ok_full,
+       SUBSTR(f1, 3000, 40) = SUBSTR(large_val_zstd(), 3000, 40) AS ok_slice
+  FROM cmdata_oid;
+ ok_len | ok_full | ok_slice 
+--------+---------+----------
+ t      | t       | t
+(1 row)
+
+SELECT length(f1) = length(large_val_zstd()) AS ok_len,
+       f1 = large_val_zstd() AS ok_full,
+       SUBSTR(f1, 3000, 40) = SUBSTR(large_val_zstd(), 3000, 40) AS ok_slice
+  FROM cmdata_oid8;
+ ok_len | ok_full | ok_slice 
+--------+---------+----------
+ t      | t       | t
+(1 row)
+
+-- a value spanning many TOAST chunks, with slices from the front, from
+-- near the end (which has to decompress almost everything), and longer
+-- than the value
+CREATE TABLE cmbig(f1 text COMPRESSION zstd);
+INSERT INTO cmbig SELECT string_agg(fipshash(g::text) || repeat('-', 40), '' ORDER BY g)
+  FROM generate_series(1, 10000) g;
+SELECT pg_column_compression(f1),
+       pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       pg_column_size(f1) < length(f1) AS smaller,
+       length(f1) AS len,
+       left(f1, 32) = fipshash('1') AS ok_head,
+       SUBSTR(f1, 360001, 32) = fipshash('5001') AS ok_mid,
+       SUBSTR(f1, 719929, 32) = fipshash('10000') AS ok_tail,
+       length(SUBSTR(f1, 1, 2000000)) AS full_len
+  FROM cmbig;
+ pg_column_compression | is_external | smaller |  len   | ok_head | ok_mid | ok_tail | full_len 
+-----------------------+-------------+---------+--------+---------+--------+---------+----------
+ zstd                  | t           | t       | 720000 | t       | t      | t       |   720000
+(1 row)
+
+DROP TABLE cmbig;
+-- the same as bytea, whose slices are byte offsets in every encoding, so
+-- that these do take the slice decompression path: within the first zstd
+-- block, across the 128kB block boundary, and near the end
+CREATE TABLE cmbigb(f1 bytea COMPRESSION zstd);
+INSERT INTO cmbigb SELECT convert_to(string_agg(fipshash(g::text) || repeat('-', 40), '' ORDER BY g), 'SQL_ASCII')
+  FROM generate_series(1, 10000) g;
+SELECT pg_column_compression(f1),
+       pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       octet_length(f1) AS len,
+       substr(f1, 1, 32) = convert_to(fipshash('1'), 'SQL_ASCII') AS ok_head,
+       substr(f1, 131057, 40) = convert_to(substr(fipshash('1821'), 17) || repeat('-', 24), 'SQL_ASCII') AS ok_boundary,
+       substr(f1, 719929, 32) = convert_to(fipshash('10000'), 'SQL_ASCII') AS ok_tail,
+       substr(f1, 719961, 10) = '\x2d2d2d2d2d2d2d2d2d2d'::bytea AS ok_last
+  FROM cmbigb;
+ pg_column_compression | is_external |  len   | ok_head | ok_boundary | ok_tail | ok_last 
+-----------------------+-------------+--------+---------+-------------+---------+---------
+ zstd                  | t           | 720000 | t       | t           | t       | t
+(1 row)
+
+DROP TABLE cmbigb;
+-- a smaller toast_tuple_target makes even a small compressed value go out
+-- of line
+CREATE TABLE cmtarget(f1 text COMPRESSION zstd) WITH (toast_tuple_target = 128);
+INSERT INTO cmtarget SELECT substr(large_val_zstd(), 1, 3000);
+SELECT pg_column_compression(f1),
+       pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       f1 = substr(large_val_zstd(), 1, 3000) AS ok_full
+  FROM cmtarget;
+ pg_column_compression | is_external | ok_full 
+-----------------------+-------------+---------
+ zstd                  | t           | t
+(1 row)
+
+DROP TABLE cmtarget;
+-- an external zstd value copied into a table with a different chunk_id type
+-- and compression setting keeps its compression, and is re-externalized
+-- with a fresh TOAST pointer; try both chunk_id types as destination
+CREATE TABLE cmmove_ext (f1 text COMPRESSION pglz) WITH (toast_value_type = 'oid');
+CREATE TABLE cmmove_ext8 (f1 text COMPRESSION pglz) WITH (toast_value_type = 'oid8');
+INSERT INTO cmmove_ext SELECT f1 FROM cmdata_oid8;
+INSERT INTO cmmove_ext8 SELECT f1 FROM cmdata_oid;
+SELECT pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       pg_column_compression(f1),
+       f1 = large_val_zstd() AS ok_full
+  FROM cmmove_ext;
+ is_external | pg_column_compression | ok_full 
+-------------+-----------------------+---------
+ t           | zstd                  | t
+(1 row)
+
+SELECT pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       pg_column_compression(f1),
+       f1 = large_val_zstd() AS ok_full
+  FROM cmmove_ext8;
+ is_external | pg_column_compression | ok_full 
+-------------+-----------------------+---------
+ t           | zstd                  | t
+(1 row)
+
+DROP TABLE cmmove_ext, cmmove_ext8;
+----------------------------------------------------------------------
+-- Storage modes
+----------------------------------------------------------------------
+-- EXTERNAL: stored out of line but never compressed, slices cross chunk
+-- boundaries directly
+CREATE TABLE cmstorage(f1 text COMPRESSION zstd);
+ALTER TABLE cmstorage ALTER COLUMN f1 SET STORAGE EXTERNAL;
+INSERT INTO cmstorage SELECT large_val_zstd();
+SELECT pg_column_compression(f1) IS NULL AS uncompressed,
+       pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       pg_column_size(f1) = octet_length(f1) AS same_size,
+       SUBSTR(f1, 1990, 20) = SUBSTR(large_val_zstd(), 1990, 20) AS ok_slice
+  FROM cmstorage;
+ uncompressed | is_external | same_size | ok_slice 
+--------------+-------------+-----------+----------
+ t            | t           | t         | t
+(1 row)
+
+-- MAIN: compressed, and kept in the tuple when that makes it fit
+TRUNCATE cmstorage;
+ALTER TABLE cmstorage ALTER COLUMN f1 SET STORAGE MAIN;
+INSERT INTO cmstorage VALUES (repeat('1234567890', 1004));
+SELECT pg_column_compression(f1),
+       pg_column_toast_chunk_id(f1) IS NULL AS is_inline,
+       length(f1) AS len
+  FROM cmstorage;
+ pg_column_compression | is_inline |  len  
+-----------------------+-----------+-------
+ zstd                  | t         | 10040
+(1 row)
+
+DROP TABLE cmstorage;
+-- PLAIN: new values are never compressed.  An external compressed datum
+-- coming from another table is fetched and decompressed before being
+-- stored, while a datum that is already compressed in line is stored as it
+-- is, like for the other methods.
+CREATE TABLE cmsmall(f1 text COMPRESSION zstd) WITH (toast_tuple_target = 128);
+INSERT INTO cmsmall VALUES (repeat('1234567890', 300));
+INSERT INTO cmsmall SELECT substr(large_val_zstd(), 1, 3000);
+SELECT pg_column_compression(f1),
+       pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external
+  FROM cmsmall ORDER BY is_external;
+ pg_column_compression | is_external 
+-----------------------+-------------
+ zstd                  | f
+ zstd                  | t
+(2 rows)
+
+CREATE TABLE cmplain(f1 text COMPRESSION zstd);
+ALTER TABLE cmplain ALTER COLUMN f1 SET STORAGE PLAIN;
+INSERT INTO cmplain VALUES (repeat('1234567890', 300));
+INSERT INTO cmplain SELECT f1 FROM cmsmall;
+SELECT pg_column_compression(f1), length(f1),
+       f1 IN (repeat('1234567890', 300), substr(large_val_zstd(), 1, 3000)) AS ok_full
+  FROM cmplain ORDER BY pg_column_compression(f1) NULLS FIRST, length(f1);
+ pg_column_compression | length | ok_full 
+-----------------------+--------+---------
+                       |   3000 | t
+                       |   3000 | t
+ zstd                  |   3000 | t
+(3 rows)
+
+DROP TABLE cmplain, cmsmall;
+----------------------------------------------------------------------
+-- Table rewrites and updates of external values
+----------------------------------------------------------------------
+CREATE TABLE cmrewrite(id int, f1 text COMPRESSION zstd)
+  WITH (toast_value_type = 'oid8');
+INSERT INTO cmrewrite VALUES (1, large_val_zstd()), (2, repeat('1234567890', 1004));
+CREATE INDEX cmrewrite_id ON cmrewrite(id);
+-- VACUUM FULL and CLUSTER preserve the values and do not recompress
+VACUUM FULL cmrewrite;
+SELECT id, pg_column_compression(f1),
+       pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       f1 = CASE id WHEN 1 THEN large_val_zstd() ELSE repeat('1234567890', 1004) END AS ok_full
+  FROM cmrewrite ORDER BY id;
+ id | pg_column_compression | is_external | ok_full 
+----+-----------------------+-------------+---------
+  1 | zstd                  | t           | t
+  2 | zstd                  | f           | t
+(2 rows)
+
+CLUSTER cmrewrite USING cmrewrite_id;
+SELECT id, pg_column_compression(f1),
+       pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       f1 = CASE id WHEN 1 THEN large_val_zstd() ELSE repeat('1234567890', 1004) END AS ok_full
+  FROM cmrewrite ORDER BY id;
+ id | pg_column_compression | is_external | ok_full 
+----+-----------------------+-------------+---------
+  1 | zstd                  | t           | t
+  2 | zstd                  | f           | t
+(2 rows)
+
+-- a column type change resets the column's compression method to the
+-- default (as it does its storage), so the rewritten values follow the
+-- default_toast_compression GUC; values that were external come back in
+-- one piece
+ALTER TABLE cmrewrite ALTER COLUMN f1 TYPE varchar(30000);
+\d+ cmrewrite
+                                                  Table "zstd.cmrewrite"
+ Column |           Type           | Collation | Nullable | Default | Storage  | Compression | Stats target | Description 
+--------+--------------------------+-----------+----------+---------+----------+-------------+--------------+-------------
+ id     | integer                  |           |          |         | plain    |             |              | 
+ f1     | character varying(30000) |           |          |         | extended |             |              | 
+Indexes:
+    "cmrewrite_id" btree (id) CLUSTER
+Options: toast_value_type=oid8
+
+SELECT id, pg_column_compression(f1),
+       f1 = CASE id WHEN 1 THEN large_val_zstd() ELSE repeat('1234567890', 1004) END AS ok_full
+  FROM cmrewrite ORDER BY id;
+ id | pg_column_compression | ok_full 
+----+-----------------------+---------
+  1 |                       | t
+  2 | pglz                  | t
+(2 rows)
+
+SET default_toast_compression = 'zstd';
+ALTER TABLE cmrewrite ALTER COLUMN f1 TYPE varchar(20000);
+SELECT id, pg_column_compression(f1),
+       f1 = CASE id WHEN 1 THEN large_val_zstd() ELSE repeat('1234567890', 1004) END AS ok_full
+  FROM cmrewrite ORDER BY id;
+ id | pg_column_compression | ok_full 
+----+-----------------------+---------
+  1 | zstd                  | t
+  2 | zstd                  | t
+(2 rows)
+
+SET default_toast_compression = 'pglz';
+DROP TABLE cmrewrite;
+-- an UPDATE that leaves the external value alone must keep the same TOAST
+-- value rather than re-toasting it
+ALTER TABLE cmdata_oid ADD COLUMN n int DEFAULT 0;
+SELECT pg_column_toast_chunk_id(f1) AS chunk_before FROM cmdata_oid \gset
+UPDATE cmdata_oid SET n = 1;
+SELECT pg_column_toast_chunk_id(f1) = :'chunk_before' AS same_toast_value,
+       f1 = large_val_zstd() AS ok_full
+  FROM cmdata_oid;
+ same_toast_value | ok_full 
+------------------+---------
+ t                | t
+(1 row)
+
+-- whereas an UPDATE of the value itself replaces the TOAST value; the old
+-- chunks are gone from the TOAST table as soon as the update commits
+SELECT reltoastrelid::regclass AS toastrel FROM pg_class
+  WHERE oid = 'cmdata_oid'::regclass \gset
+UPDATE cmdata_oid SET f1 = f1 || 'x';
+SELECT pg_column_toast_chunk_id(f1) <> :'chunk_before' AS new_toast_value,
+       pg_column_compression(f1),
+       f1 = large_val_zstd() || 'x' AS ok_full
+  FROM cmdata_oid;
+ new_toast_value | pg_column_compression | ok_full 
+-----------------+-----------------------+---------
+ t               | zstd                  | t
+(1 row)
+
+SELECT count(DISTINCT chunk_id) AS live_toast_values FROM :toastrel;
+ live_toast_values 
+-------------------
+                 1
+(1 row)
+
+-- deleting the row deletes its TOAST value, for both chunk_id types
+DELETE FROM cmdata_oid;
+SELECT count(*) AS chunks_left FROM :toastrel;
+ chunks_left 
+-------------
+           0
+(1 row)
+
+SELECT reltoastrelid::regclass AS toastrel FROM pg_class
+  WHERE oid = 'cmdata_oid8'::regclass \gset
+DELETE FROM cmdata_oid8;
+SELECT count(*) AS chunks_left FROM :toastrel;
+ chunks_left 
+-------------
+           0
+(1 row)
+
+DROP TABLE cmdata_oid, cmdata_oid8;
+----------------------------------------------------------------------
+-- Indexes
+----------------------------------------------------------------------
+-- a compressible key large enough to need compression to fit in an index
+-- entry; the index must be usable to find the row
+CREATE TABLE cmindex(f1 text COMPRESSION zstd);
+CREATE INDEX cmindex_f1 ON cmindex(f1);
+INSERT INTO cmindex VALUES (repeat('abcdefghij', 300)), (repeat('klmnopqrst', 300));
+SET enable_seqscan = off;
+SET enable_bitmapscan = off;
+SELECT length(f1), left(f1, 10) FROM cmindex WHERE f1 = repeat('klmnopqrst', 300);
+ length |    left    
+--------+------------
+   3000 | klmnopqrst
+(1 row)
+
+RESET enable_seqscan;
+RESET enable_bitmapscan;
+DROP TABLE cmindex;
+-- test expression index
+CREATE TABLE cmdata2 (f1 TEXT COMPRESSION pglz, f2 TEXT COMPRESSION zstd);
+CREATE UNIQUE INDEX idx1 ON cmdata2 ((f1 || f2));
+INSERT INTO cmdata2 VALUES((SELECT array_agg(fipshash(g::TEXT))::TEXT FROM
+generate_series(1, 50) g), VERSION());
+DROP TABLE cmdata2;
+----------------------------------------------------------------------
+-- Materialized views, partitions, inheritance, temporary tables
+----------------------------------------------------------------------
+-- test compression with materialized view
+CREATE MATERIALIZED VIEW compressmv(x) AS SELECT * FROM cmdata_zstd;
+\d+ compressmv
+                                 Materialized view "zstd.compressmv"
+ Column | Type | Collation | Nullable | Default | Storage  | Compression | Stats target | Description 
+--------+------+-----------+----------+---------+----------+-------------+--------------+-------------
+ x      | text |           |          |         | extended |             |              | 
+View definition:
+ SELECT f1 AS x
+   FROM cmdata_zstd;
+
+SELECT pg_column_compression(f1) FROM cmdata_zstd;
+ pg_column_compression 
+-----------------------
+ zstd
+(1 row)
+
+SELECT pg_column_compression(x) FROM compressmv;
+ pg_column_compression 
+-----------------------
+ zstd
+(1 row)
+
+-- test compression with partition
+CREATE TABLE cmpart(f1 text COMPRESSION zstd) PARTITION BY HASH(f1);
+CREATE TABLE cmpart1 PARTITION OF cmpart FOR VALUES WITH (MODULUS 2, REMAINDER 0);
+CREATE TABLE cmpart2(f1 text COMPRESSION pglz);
+ALTER TABLE cmpart ATTACH PARTITION cmpart2 FOR VALUES WITH (MODULUS 2, REMAINDER 1);
+INSERT INTO cmpart VALUES (repeat('123456789', 1004));
+INSERT INTO cmpart VALUES (repeat('123456789', 4004));
+SELECT pg_column_compression(f1) FROM cmpart1;
+ pg_column_compression 
+-----------------------
+ zstd
+(1 row)
+
+SELECT pg_column_compression(f1) FROM cmpart2;
+ pg_column_compression 
+-----------------------
+ pglz
+(1 row)
+
+-- test compression with inheritance
+CREATE TABLE cminh() INHERITS(cmdata_pglz, cmdata_zstd); -- error
+NOTICE:  merging multiple inherited definitions of column "f1"
+ERROR:  column "f1" has a compression method conflict
+DETAIL:  pglz versus zstd
+CREATE TABLE cminh(f1 TEXT COMPRESSION zstd) INHERITS(cmdata_pglz); -- error
+NOTICE:  merging column "f1" with inherited definition
+ERROR:  column "f1" has a compression method conflict
+DETAIL:  pglz versus zstd
+CREATE TABLE cmdata3(f1 text);
+CREATE TABLE cminh() INHERITS (cmdata_pglz, cmdata3);
+NOTICE:  merging multiple inherited definitions of column "f1"
+-- temporary table
+CREATE TEMP TABLE cmtemp(f1 text COMPRESSION zstd);
+INSERT INTO cmtemp SELECT large_val_zstd();
+SELECT pg_column_compression(f1),
+       pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       f1 = large_val_zstd() AS ok_full
+  FROM cmtemp;
+ pg_column_compression | is_external | ok_full 
+-----------------------+-------------+---------
+ zstd                  | t           | t
+(1 row)
+
+DROP TABLE cmtemp;
+----------------------------------------------------------------------
+-- default_toast_compression GUC
+----------------------------------------------------------------------
+-- test default_toast_compression GUC; the value is case-insensitive
+SET default_toast_compression = 'ZSTD';
+SHOW default_toast_compression;
+ default_toast_compression 
+---------------------------
+ zstd
+(1 row)
+
+SET default_toast_compression = 'zstd';
+-- the GUC drives the method for columns with no explicit COMPRESSION, so
+-- the column keeps a default attcompression but the data comes out zstd
+CREATE TABLE cmdata_default(f1 text);
+INSERT INTO cmdata_default VALUES(repeat('1234567890', 1004));
+\d+ cmdata_default
+                                     Table "zstd.cmdata_default"
+ Column | Type | Collation | Nullable | Default | Storage  | Compression | Stats target | Description 
+--------+------+-----------+----------+---------+----------+-------------+--------------+-------------
+ f1     | text |           |          |         | extended |             |              | 
+
+SELECT pg_column_compression(f1) FROM cmdata_default;
+ pg_column_compression 
+-----------------------
+ zstd
+(1 row)
+
+SELECT f1 = repeat('1234567890', 1004) AS ok_full,
+       SUBSTR(f1, 4000, 20) = SUBSTR(repeat('1234567890', 1004), 4000, 20) AS ok_slice
+  FROM cmdata_default;
+ ok_full | ok_slice 
+---------+----------
+ t       | t
+(1 row)
+
+-- SET COMPRESSION default makes a column follow the GUC again
+ALTER TABLE cmdata_default ALTER COLUMN f1 SET COMPRESSION pglz;
+INSERT INTO cmdata_default VALUES(repeat('1234567890', 1004));
+ALTER TABLE cmdata_default ALTER COLUMN f1 SET COMPRESSION default;
+\d+ cmdata_default
+                                     Table "zstd.cmdata_default"
+ Column | Type | Collation | Nullable | Default | Storage  | Compression | Stats target | Description 
+--------+------+-----------+----------+---------+----------+-------------+--------------+-------------
+ f1     | text |           |          |         | extended |             |              | 
+
+INSERT INTO cmdata_default VALUES(repeat('1234567890', 1004));
+SELECT pg_column_compression(f1), count(*) FROM cmdata_default GROUP BY 1 ORDER BY 1;
+ pg_column_compression | count 
+-----------------------+-------
+ pglz                  |     1
+ zstd                  |     2
+(2 rows)
+
+DROP TABLE cmdata_default;
+-- test alter compression method
+ALTER TABLE cmdata_pglz ALTER COLUMN f1 SET COMPRESSION zstd;
+INSERT INTO cmdata_pglz VALUES (repeat('123456789', 4004));
+\d+ cmdata_pglz
+                                       Table "zstd.cmdata_pglz"
+ Column | Type | Collation | Nullable | Default | Storage  | Compression | Stats target | Description 
+--------+------+-----------+----------+---------+----------+-------------+--------------+-------------
+ f1     | text |           |          |         | extended | zstd        |              | 
+Indexes:
+    "idx" btree (f1)
+Child tables:
+    cminh
+
+SELECT pg_column_compression(f1) FROM cmdata_pglz;
+ pg_column_compression 
+-----------------------
+ pglz
+ zstd
+(2 rows)
+
+ALTER TABLE cmdata_pglz ALTER COLUMN f1 SET COMPRESSION pglz;
+-- test alter compression method for materialized views
+ALTER MATERIALIZED VIEW compressmv ALTER COLUMN x SET COMPRESSION zstd;
+\d+ compressmv
+                                 Materialized view "zstd.compressmv"
+ Column | Type | Collation | Nullable | Default | Storage  | Compression | Stats target | Description 
+--------+------+-----------+----------+---------+----------+-------------+--------------+-------------
+ x      | text |           |          |         | extended | zstd        |              | 
+View definition:
+ SELECT f1 AS x
+   FROM cmdata_zstd;
+
+-- test alter compression method for partitioned tables
+ALTER TABLE cmpart1 ALTER COLUMN f1 SET COMPRESSION pglz;
+ALTER TABLE cmpart2 ALTER COLUMN f1 SET COMPRESSION zstd;
+-- new data should be compressed with the current compression method
+INSERT INTO cmpart VALUES (repeat('123456789', 1004));
+INSERT INTO cmpart VALUES (repeat('123456789', 4004));
+SELECT pg_column_compression(f1) FROM cmpart1;
+ pg_column_compression 
+-----------------------
+ zstd
+ pglz
+(2 rows)
+
+SELECT pg_column_compression(f1) FROM cmpart2;
+ pg_column_compression 
+-----------------------
+ pglz
+ zstd
+(2 rows)
+
+-- VACUUM FULL does not recompress
+SELECT pg_column_compression(f1) FROM cmdata_zstd;
+ pg_column_compression 
+-----------------------
+ zstd
+(1 row)
+
+VACUUM FULL cmdata_zstd;
+SELECT pg_column_compression(f1) FROM cmdata_zstd;
+ pg_column_compression 
+-----------------------
+ zstd
+(1 row)
+
+RESET default_toast_compression;
+-- check data is ok
+SELECT length(f1) FROM cmdata_pglz;
+ length 
+--------
+  10000
+  36036
+(2 rows)
+
+SELECT length(f1) FROM cmdata_zstd;
+ length 
+--------
+  10040
+(1 row)
+
+SELECT length(f1) FROM cmmove1;
+ length 
+--------
+  10040
+(1 row)
+
+SELECT length(f1) FROM cmmove2;
+ length 
+--------
+  10040
+(1 row)
+
+SELECT length(f1) FROM cmmove3;
+ length 
+--------
+  10000
+  10040
+(2 rows)
+
+\set HIDE_TOAST_COMPRESSION true
diff --git a/src/test/regress/expected/compression_zstd_1.out b/src/test/regress/expected/compression_zstd_1.out
new file mode 100644
index 00000000000..5f07342fd51
--- /dev/null
+++ b/src/test/regress/expected/compression_zstd_1.out
@@ -0,0 +1,7 @@
+-- Tests for TOAST compression with zstd
+SELECT NOT(enumvals @> '{zstd}') AS skip_test FROM pg_settings WHERE
+  name = 'default_toast_compression' \gset
+\if :skip_test
+   \echo '*** skipping TOAST tests with zstd (not supported) ***'
+*** skipping TOAST tests with zstd (not supported) ***
+   \quit
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index bb13a7b6b8f..7dc272e4434 100644
--- a/src/test/regress/parallel_schedule
+++ b/src/test/regress/parallel_schedule
@@ -133,7 +133,7 @@ test: partition_join partition_prune reloptions hash_part indexing partition_agg
 # ----------
 # Another group of parallel tests (compression)
 # ----------
-test: compression compression_lz4 compression_pglz cluster
+test: compression compression_lz4 compression_pglz compression_zstd cluster
 
 # event_trigger depends on create_am and cannot run concurrently with
 # any test that runs DDL
diff --git a/src/test/regress/sql/compression_zstd.sql b/src/test/regress/sql/compression_zstd.sql
new file mode 100644
index 00000000000..da5fa0d2b2b
--- /dev/null
+++ b/src/test/regress/sql/compression_zstd.sql
@@ -0,0 +1,517 @@
+-- Tests for TOAST compression with zstd
+
+SELECT NOT(enumvals @> '{zstd}') AS skip_test FROM pg_settings WHERE
+  name = 'default_toast_compression' \gset
+\if :skip_test
+   \echo '*** skipping TOAST tests with zstd (not supported) ***'
+   \quit
+\endif
+
+CREATE SCHEMA zstd;
+SET search_path TO zstd, public;
+
+\set HIDE_TOAST_COMPRESSION false
+
+-- Ensure we get stable results regardless of the installation's default.
+-- We rely on this GUC value for a few tests.
+SET default_toast_compression = 'pglz';
+
+-- Helpers.  Hash output is poorly compressible, so values built from it
+-- stay large after compression and are stored out of line; a bytea of raw
+-- hash bytes is not compressible at all.  None of the checks below print
+-- compressed sizes, which depend on the zstd version.
+CREATE FUNCTION large_val_zstd() RETURNS TEXT LANGUAGE SQL AS
+'select array_agg(fipshash(g::text))::text from generate_series(1, 256) g';
+CREATE FUNCTION incompressible_val() RETURNS bytea LANGUAGE SQL AS
+$$ select decode(string_agg(fipshash(g::text), '' order by g), 'hex')
+   from generate_series(1, 200) g $$;
+
+----------------------------------------------------------------------
+-- DDL
+----------------------------------------------------------------------
+
+-- test creating table with compression method
+CREATE TABLE cmdata_pglz(f1 text COMPRESSION pglz);
+CREATE INDEX idx ON cmdata_pglz(f1);
+INSERT INTO cmdata_pglz VALUES(repeat('1234567890', 1000));
+\d+ cmdata_pglz
+CREATE TABLE cmdata_zstd(f1 TEXT COMPRESSION zstd);
+INSERT INTO cmdata_zstd VALUES(repeat('1234567890', 1004));
+\d+ cmdata_zstd
+
+-- the method name is an identifier, so case does not matter
+CREATE TABLE cmupper(f1 text COMPRESSION ZSTD);
+\d+ cmupper
+DROP TABLE cmupper;
+
+-- a domain over a varlena type can be compressed too
+CREATE DOMAIN zstdtext AS text;
+CREATE TABLE cmdomain(f1 zstdtext COMPRESSION zstd);
+INSERT INTO cmdomain VALUES (repeat('1234567890', 1004));
+\d+ cmdomain
+SELECT pg_column_compression(f1), length(f1) FROM cmdomain;
+DROP TABLE cmdomain;
+DROP DOMAIN zstdtext;
+
+-- errors: incompressible data type, unknown method
+CREATE TABLE cmbad(f1 int COMPRESSION zstd);
+CREATE TABLE cmbad(f1 text);
+ALTER TABLE cmbad ALTER COLUMN f1 SET COMPRESSION zstd_nodict;
+DROP TABLE cmbad;
+
+----------------------------------------------------------------------
+-- Compressed-in-line values
+----------------------------------------------------------------------
+
+-- verify stored compression method in the data, and that compression
+-- did save space
+SELECT pg_column_compression(f1),
+       pg_column_size(f1) < length(f1) AS smaller,
+       pg_column_toast_chunk_id(f1) IS NULL AS is_inline
+  FROM cmdata_zstd;
+
+-- decompress data slice
+SELECT SUBSTR(f1, 200, 5) FROM cmdata_pglz;
+SELECT SUBSTR(f1, 2000, 50) FROM cmdata_zstd;
+
+-- check that slice decompression agrees with full decompression, at the
+-- start, in the middle and at the very end of the value
+SELECT SUBSTR(f1, 1, 100) = SUBSTR(repeat('1234567890', 1004), 1, 100) AS ok_head,
+       SUBSTR(f1, 5000, 100) = SUBSTR(repeat('1234567890', 1004), 5000, 100) AS ok_mid,
+       SUBSTR(f1, 10036, 5) = SUBSTR(repeat('1234567890', 1004), 10036, 5) AS ok_tail,
+       length(f1) AS len
+  FROM cmdata_zstd;
+
+-- slices of one byte, past the end, and longer than the whole value (the
+-- latter falls back to a full decompression)
+SELECT left(f1, 1) AS first_char,
+       right(f1, 1) AS last_char,
+       SUBSTR(f1, 10040, 1) AS at_end,
+       SUBSTR(f1, 10041, 10) = '' AS past_end,
+       length(SUBSTR(f1, 1, 1000000)) AS full_len
+  FROM cmdata_zstd;
+
+----------------------------------------------------------------------
+-- Values that do not get compressed
+----------------------------------------------------------------------
+
+-- values below the TOAST threshold are stored as they are; NULL and the
+-- empty string are fine too
+CREATE TABLE cmshort(f1 text COMPRESSION zstd);
+INSERT INTO cmshort VALUES (repeat('x', 100)), (''), (NULL);
+SELECT pg_column_compression(f1), length(f1) FROM cmshort ORDER BY length(f1);
+DROP TABLE cmshort;
+
+-- data that zstd cannot shrink is stored uncompressed, out of line if
+-- needed, with no compression method recorded
+CREATE TABLE cmincompressible(f1 bytea COMPRESSION zstd);
+INSERT INTO cmincompressible SELECT incompressible_val();
+SELECT pg_column_compression(f1) IS NULL AS uncompressed,
+       pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       pg_column_size(f1) = octet_length(f1) AS same_size,
+       length(f1) AS len,
+       f1 = incompressible_val() AS ok_full,
+       substr(f1, 3000, 40) = substr(incompressible_val(), 3000, 40) AS ok_slice
+  FROM cmincompressible;
+DROP TABLE cmincompressible;
+
+----------------------------------------------------------------------
+-- Other varlena types
+----------------------------------------------------------------------
+
+-- binary data with zero and high bytes
+CREATE TABLE cmbytea(f1 bytea COMPRESSION zstd);
+INSERT INTO cmbytea VALUES (decode(repeat('00ff10', 2000), 'hex'));
+SELECT pg_column_compression(f1), length(f1),
+       f1 = decode(repeat('00ff10', 2000), 'hex') AS ok_full,
+       get_byte(f1, 0) AS byte0, get_byte(f1, 1) AS byte1,
+       substr(f1, 3001, 3) = decode('00ff10', 'hex') AS ok_slice
+  FROM cmbytea;
+DROP TABLE cmbytea;
+
+-- jsonb, compressed inline and out of line
+CREATE TABLE cmjsonb(j jsonb COMPRESSION zstd);
+INSERT INTO cmjsonb SELECT jsonb_build_object('k', repeat('v', 5000), 'n', 1);
+INSERT INTO cmjsonb SELECT jsonb_object_agg(g::text, fipshash(g::text))
+  FROM generate_series(1, 300) g;
+SELECT pg_column_compression(j),
+       pg_column_toast_chunk_id(j) IS NOT NULL AS is_external,
+       length(j ->> 'k') AS klen,
+       j ->> 'n' AS n,
+       j ->> '150' = fipshash('150') AS ok_150
+  FROM cmjsonb ORDER BY is_external;
+DROP TABLE cmjsonb;
+
+-- arrays
+CREATE TABLE cmarray(f1 text[] COMPRESSION zstd);
+INSERT INTO cmarray SELECT array_agg(repeat('x', 100) || g ORDER BY g)
+  FROM generate_series(1, 200) g;
+SELECT pg_column_compression(f1), array_length(f1, 1) AS n,
+       f1[1] = repeat('x', 100) || '1' AS ok_first,
+       f1[200] = repeat('x', 100) || '200' AS ok_last
+  FROM cmarray;
+DROP TABLE cmarray;
+
+----------------------------------------------------------------------
+-- Moving data between tables and methods
+----------------------------------------------------------------------
+
+-- copy with table creation
+SELECT * INTO cmmove1 FROM cmdata_zstd;
+\d+ cmmove1
+SELECT pg_column_compression(f1) FROM cmmove1;
+
+-- test LIKE INCLUDING COMPRESSION.  The GUC default_toast_compression
+-- has no effect, the compression method is taken from the table being copied.
+CREATE TABLE cmdata2 (LIKE cmdata_zstd INCLUDING COMPRESSION);
+\d+ cmdata2
+DROP TABLE cmdata2;
+
+-- copy to existing table: a compressed datum keeps its own method, in both
+-- directions, so a table can hold values compressed with different methods
+CREATE TABLE cmmove3(f1 text COMPRESSION pglz);
+INSERT INTO cmmove3 SELECT * FROM cmdata_pglz;
+INSERT INTO cmmove3 SELECT * FROM cmdata_zstd;
+SELECT pg_column_compression(f1) FROM cmmove3 ORDER BY 1;
+INSERT INTO cmdata_zstd SELECT * FROM cmdata_pglz;
+SELECT pg_column_compression(f1), count(*) FROM cmdata_zstd GROUP BY 1 ORDER BY 1;
+DELETE FROM cmdata_zstd WHERE pg_column_compression(f1) = 'pglz';
+
+-- update using datum from different table with zstd data.
+CREATE TABLE cmmove2(f1 text COMPRESSION pglz);
+INSERT INTO cmmove2 VALUES (repeat('1234567890', 1004));
+SELECT pg_column_compression(f1) FROM cmmove2;
+UPDATE cmmove2 SET f1 = cmdata_zstd.f1 FROM cmdata_zstd;
+SELECT pg_column_compression(f1) FROM cmmove2;
+
+----------------------------------------------------------------------
+-- Externally stored compressed values
+----------------------------------------------------------------------
+
+CREATE TABLE cmdata2 (f1 text COMPRESSION zstd);
+INSERT INTO cmdata2 SELECT large_val_zstd() || repeat('a', 4000);
+SELECT pg_column_compression(f1), pg_column_size(f1) < length(f1) AS smaller
+  FROM cmdata2;
+SELECT SUBSTR(f1, 200, 5) FROM cmdata2;
+SELECT SUBSTR(f1, 200, 5) = SUBSTR(large_val_zstd() || repeat('a', 4000), 200, 5) AS ok_slice
+  FROM cmdata2;
+DROP TABLE cmdata2;
+
+-- test that both TOAST value ID widths carry the compression method through
+-- an external TOAST pointer.  The data here is poorly compressible on
+-- purpose, so that the value is certain to be stored out of line.
+CREATE TABLE cmdata_oid(f1 text COMPRESSION zstd)
+  WITH (toast_value_type = 'oid');
+CREATE TABLE cmdata_oid8(f1 text COMPRESSION zstd)
+  WITH (toast_value_type = 'oid8');
+INSERT INTO cmdata_oid SELECT large_val_zstd();
+INSERT INTO cmdata_oid8 SELECT large_val_zstd();
+-- confirm the values really are out of line, so that the checks below
+-- exercise the external TOAST pointer rather than the inline header
+SELECT pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       pg_column_compression(f1) FROM cmdata_oid;
+SELECT pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       pg_column_compression(f1) FROM cmdata_oid8;
+SELECT length(f1) = length(large_val_zstd()) AS ok_len,
+       f1 = large_val_zstd() AS ok_full,
+       SUBSTR(f1, 3000, 40) = SUBSTR(large_val_zstd(), 3000, 40) AS ok_slice
+  FROM cmdata_oid;
+SELECT length(f1) = length(large_val_zstd()) AS ok_len,
+       f1 = large_val_zstd() AS ok_full,
+       SUBSTR(f1, 3000, 40) = SUBSTR(large_val_zstd(), 3000, 40) AS ok_slice
+  FROM cmdata_oid8;
+
+-- a value spanning many TOAST chunks, with slices from the front, from
+-- near the end (which has to decompress almost everything), and longer
+-- than the value
+CREATE TABLE cmbig(f1 text COMPRESSION zstd);
+INSERT INTO cmbig SELECT string_agg(fipshash(g::text) || repeat('-', 40), '' ORDER BY g)
+  FROM generate_series(1, 10000) g;
+SELECT pg_column_compression(f1),
+       pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       pg_column_size(f1) < length(f1) AS smaller,
+       length(f1) AS len,
+       left(f1, 32) = fipshash('1') AS ok_head,
+       SUBSTR(f1, 360001, 32) = fipshash('5001') AS ok_mid,
+       SUBSTR(f1, 719929, 32) = fipshash('10000') AS ok_tail,
+       length(SUBSTR(f1, 1, 2000000)) AS full_len
+  FROM cmbig;
+DROP TABLE cmbig;
+
+-- the same as bytea, whose slices are byte offsets in every encoding, so
+-- that these do take the slice decompression path: within the first zstd
+-- block, across the 128kB block boundary, and near the end
+CREATE TABLE cmbigb(f1 bytea COMPRESSION zstd);
+INSERT INTO cmbigb SELECT convert_to(string_agg(fipshash(g::text) || repeat('-', 40), '' ORDER BY g), 'SQL_ASCII')
+  FROM generate_series(1, 10000) g;
+SELECT pg_column_compression(f1),
+       pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       octet_length(f1) AS len,
+       substr(f1, 1, 32) = convert_to(fipshash('1'), 'SQL_ASCII') AS ok_head,
+       substr(f1, 131057, 40) = convert_to(substr(fipshash('1821'), 17) || repeat('-', 24), 'SQL_ASCII') AS ok_boundary,
+       substr(f1, 719929, 32) = convert_to(fipshash('10000'), 'SQL_ASCII') AS ok_tail,
+       substr(f1, 719961, 10) = '\x2d2d2d2d2d2d2d2d2d2d'::bytea AS ok_last
+  FROM cmbigb;
+DROP TABLE cmbigb;
+
+-- a smaller toast_tuple_target makes even a small compressed value go out
+-- of line
+CREATE TABLE cmtarget(f1 text COMPRESSION zstd) WITH (toast_tuple_target = 128);
+INSERT INTO cmtarget SELECT substr(large_val_zstd(), 1, 3000);
+SELECT pg_column_compression(f1),
+       pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       f1 = substr(large_val_zstd(), 1, 3000) AS ok_full
+  FROM cmtarget;
+DROP TABLE cmtarget;
+
+-- an external zstd value copied into a table with a different chunk_id type
+-- and compression setting keeps its compression, and is re-externalized
+-- with a fresh TOAST pointer; try both chunk_id types as destination
+CREATE TABLE cmmove_ext (f1 text COMPRESSION pglz) WITH (toast_value_type = 'oid');
+CREATE TABLE cmmove_ext8 (f1 text COMPRESSION pglz) WITH (toast_value_type = 'oid8');
+INSERT INTO cmmove_ext SELECT f1 FROM cmdata_oid8;
+INSERT INTO cmmove_ext8 SELECT f1 FROM cmdata_oid;
+SELECT pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       pg_column_compression(f1),
+       f1 = large_val_zstd() AS ok_full
+  FROM cmmove_ext;
+SELECT pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       pg_column_compression(f1),
+       f1 = large_val_zstd() AS ok_full
+  FROM cmmove_ext8;
+DROP TABLE cmmove_ext, cmmove_ext8;
+
+----------------------------------------------------------------------
+-- Storage modes
+----------------------------------------------------------------------
+
+-- EXTERNAL: stored out of line but never compressed, slices cross chunk
+-- boundaries directly
+CREATE TABLE cmstorage(f1 text COMPRESSION zstd);
+ALTER TABLE cmstorage ALTER COLUMN f1 SET STORAGE EXTERNAL;
+INSERT INTO cmstorage SELECT large_val_zstd();
+SELECT pg_column_compression(f1) IS NULL AS uncompressed,
+       pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       pg_column_size(f1) = octet_length(f1) AS same_size,
+       SUBSTR(f1, 1990, 20) = SUBSTR(large_val_zstd(), 1990, 20) AS ok_slice
+  FROM cmstorage;
+
+-- MAIN: compressed, and kept in the tuple when that makes it fit
+TRUNCATE cmstorage;
+ALTER TABLE cmstorage ALTER COLUMN f1 SET STORAGE MAIN;
+INSERT INTO cmstorage VALUES (repeat('1234567890', 1004));
+SELECT pg_column_compression(f1),
+       pg_column_toast_chunk_id(f1) IS NULL AS is_inline,
+       length(f1) AS len
+  FROM cmstorage;
+DROP TABLE cmstorage;
+
+-- PLAIN: new values are never compressed.  An external compressed datum
+-- coming from another table is fetched and decompressed before being
+-- stored, while a datum that is already compressed in line is stored as it
+-- is, like for the other methods.
+CREATE TABLE cmsmall(f1 text COMPRESSION zstd) WITH (toast_tuple_target = 128);
+INSERT INTO cmsmall VALUES (repeat('1234567890', 300));
+INSERT INTO cmsmall SELECT substr(large_val_zstd(), 1, 3000);
+SELECT pg_column_compression(f1),
+       pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external
+  FROM cmsmall ORDER BY is_external;
+CREATE TABLE cmplain(f1 text COMPRESSION zstd);
+ALTER TABLE cmplain ALTER COLUMN f1 SET STORAGE PLAIN;
+INSERT INTO cmplain VALUES (repeat('1234567890', 300));
+INSERT INTO cmplain SELECT f1 FROM cmsmall;
+SELECT pg_column_compression(f1), length(f1),
+       f1 IN (repeat('1234567890', 300), substr(large_val_zstd(), 1, 3000)) AS ok_full
+  FROM cmplain ORDER BY pg_column_compression(f1) NULLS FIRST, length(f1);
+DROP TABLE cmplain, cmsmall;
+
+----------------------------------------------------------------------
+-- Table rewrites and updates of external values
+----------------------------------------------------------------------
+
+CREATE TABLE cmrewrite(id int, f1 text COMPRESSION zstd)
+  WITH (toast_value_type = 'oid8');
+INSERT INTO cmrewrite VALUES (1, large_val_zstd()), (2, repeat('1234567890', 1004));
+CREATE INDEX cmrewrite_id ON cmrewrite(id);
+
+-- VACUUM FULL and CLUSTER preserve the values and do not recompress
+VACUUM FULL cmrewrite;
+SELECT id, pg_column_compression(f1),
+       pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       f1 = CASE id WHEN 1 THEN large_val_zstd() ELSE repeat('1234567890', 1004) END AS ok_full
+  FROM cmrewrite ORDER BY id;
+CLUSTER cmrewrite USING cmrewrite_id;
+SELECT id, pg_column_compression(f1),
+       pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       f1 = CASE id WHEN 1 THEN large_val_zstd() ELSE repeat('1234567890', 1004) END AS ok_full
+  FROM cmrewrite ORDER BY id;
+
+-- a column type change resets the column's compression method to the
+-- default (as it does its storage), so the rewritten values follow the
+-- default_toast_compression GUC; values that were external come back in
+-- one piece
+ALTER TABLE cmrewrite ALTER COLUMN f1 TYPE varchar(30000);
+\d+ cmrewrite
+SELECT id, pg_column_compression(f1),
+       f1 = CASE id WHEN 1 THEN large_val_zstd() ELSE repeat('1234567890', 1004) END AS ok_full
+  FROM cmrewrite ORDER BY id;
+SET default_toast_compression = 'zstd';
+ALTER TABLE cmrewrite ALTER COLUMN f1 TYPE varchar(20000);
+SELECT id, pg_column_compression(f1),
+       f1 = CASE id WHEN 1 THEN large_val_zstd() ELSE repeat('1234567890', 1004) END AS ok_full
+  FROM cmrewrite ORDER BY id;
+SET default_toast_compression = 'pglz';
+DROP TABLE cmrewrite;
+
+-- an UPDATE that leaves the external value alone must keep the same TOAST
+-- value rather than re-toasting it
+ALTER TABLE cmdata_oid ADD COLUMN n int DEFAULT 0;
+SELECT pg_column_toast_chunk_id(f1) AS chunk_before FROM cmdata_oid \gset
+UPDATE cmdata_oid SET n = 1;
+SELECT pg_column_toast_chunk_id(f1) = :'chunk_before' AS same_toast_value,
+       f1 = large_val_zstd() AS ok_full
+  FROM cmdata_oid;
+
+-- whereas an UPDATE of the value itself replaces the TOAST value; the old
+-- chunks are gone from the TOAST table as soon as the update commits
+SELECT reltoastrelid::regclass AS toastrel FROM pg_class
+  WHERE oid = 'cmdata_oid'::regclass \gset
+UPDATE cmdata_oid SET f1 = f1 || 'x';
+SELECT pg_column_toast_chunk_id(f1) <> :'chunk_before' AS new_toast_value,
+       pg_column_compression(f1),
+       f1 = large_val_zstd() || 'x' AS ok_full
+  FROM cmdata_oid;
+SELECT count(DISTINCT chunk_id) AS live_toast_values FROM :toastrel;
+
+-- deleting the row deletes its TOAST value, for both chunk_id types
+DELETE FROM cmdata_oid;
+SELECT count(*) AS chunks_left FROM :toastrel;
+SELECT reltoastrelid::regclass AS toastrel FROM pg_class
+  WHERE oid = 'cmdata_oid8'::regclass \gset
+DELETE FROM cmdata_oid8;
+SELECT count(*) AS chunks_left FROM :toastrel;
+DROP TABLE cmdata_oid, cmdata_oid8;
+
+----------------------------------------------------------------------
+-- Indexes
+----------------------------------------------------------------------
+
+-- a compressible key large enough to need compression to fit in an index
+-- entry; the index must be usable to find the row
+CREATE TABLE cmindex(f1 text COMPRESSION zstd);
+CREATE INDEX cmindex_f1 ON cmindex(f1);
+INSERT INTO cmindex VALUES (repeat('abcdefghij', 300)), (repeat('klmnopqrst', 300));
+SET enable_seqscan = off;
+SET enable_bitmapscan = off;
+SELECT length(f1), left(f1, 10) FROM cmindex WHERE f1 = repeat('klmnopqrst', 300);
+RESET enable_seqscan;
+RESET enable_bitmapscan;
+DROP TABLE cmindex;
+
+-- test expression index
+CREATE TABLE cmdata2 (f1 TEXT COMPRESSION pglz, f2 TEXT COMPRESSION zstd);
+CREATE UNIQUE INDEX idx1 ON cmdata2 ((f1 || f2));
+INSERT INTO cmdata2 VALUES((SELECT array_agg(fipshash(g::TEXT))::TEXT FROM
+generate_series(1, 50) g), VERSION());
+DROP TABLE cmdata2;
+
+----------------------------------------------------------------------
+-- Materialized views, partitions, inheritance, temporary tables
+----------------------------------------------------------------------
+
+-- test compression with materialized view
+CREATE MATERIALIZED VIEW compressmv(x) AS SELECT * FROM cmdata_zstd;
+\d+ compressmv
+SELECT pg_column_compression(f1) FROM cmdata_zstd;
+SELECT pg_column_compression(x) FROM compressmv;
+
+-- test compression with partition
+CREATE TABLE cmpart(f1 text COMPRESSION zstd) PARTITION BY HASH(f1);
+CREATE TABLE cmpart1 PARTITION OF cmpart FOR VALUES WITH (MODULUS 2, REMAINDER 0);
+CREATE TABLE cmpart2(f1 text COMPRESSION pglz);
+
+ALTER TABLE cmpart ATTACH PARTITION cmpart2 FOR VALUES WITH (MODULUS 2, REMAINDER 1);
+INSERT INTO cmpart VALUES (repeat('123456789', 1004));
+INSERT INTO cmpart VALUES (repeat('123456789', 4004));
+SELECT pg_column_compression(f1) FROM cmpart1;
+SELECT pg_column_compression(f1) FROM cmpart2;
+
+-- test compression with inheritance
+CREATE TABLE cminh() INHERITS(cmdata_pglz, cmdata_zstd); -- error
+CREATE TABLE cminh(f1 TEXT COMPRESSION zstd) INHERITS(cmdata_pglz); -- error
+CREATE TABLE cmdata3(f1 text);
+CREATE TABLE cminh() INHERITS (cmdata_pglz, cmdata3);
+
+-- temporary table
+CREATE TEMP TABLE cmtemp(f1 text COMPRESSION zstd);
+INSERT INTO cmtemp SELECT large_val_zstd();
+SELECT pg_column_compression(f1),
+       pg_column_toast_chunk_id(f1) IS NOT NULL AS is_external,
+       f1 = large_val_zstd() AS ok_full
+  FROM cmtemp;
+DROP TABLE cmtemp;
+
+----------------------------------------------------------------------
+-- default_toast_compression GUC
+----------------------------------------------------------------------
+
+-- test default_toast_compression GUC; the value is case-insensitive
+SET default_toast_compression = 'ZSTD';
+SHOW default_toast_compression;
+SET default_toast_compression = 'zstd';
+
+-- the GUC drives the method for columns with no explicit COMPRESSION, so
+-- the column keeps a default attcompression but the data comes out zstd
+CREATE TABLE cmdata_default(f1 text);
+INSERT INTO cmdata_default VALUES(repeat('1234567890', 1004));
+\d+ cmdata_default
+SELECT pg_column_compression(f1) FROM cmdata_default;
+SELECT f1 = repeat('1234567890', 1004) AS ok_full,
+       SUBSTR(f1, 4000, 20) = SUBSTR(repeat('1234567890', 1004), 4000, 20) AS ok_slice
+  FROM cmdata_default;
+
+-- SET COMPRESSION default makes a column follow the GUC again
+ALTER TABLE cmdata_default ALTER COLUMN f1 SET COMPRESSION pglz;
+INSERT INTO cmdata_default VALUES(repeat('1234567890', 1004));
+ALTER TABLE cmdata_default ALTER COLUMN f1 SET COMPRESSION default;
+\d+ cmdata_default
+INSERT INTO cmdata_default VALUES(repeat('1234567890', 1004));
+SELECT pg_column_compression(f1), count(*) FROM cmdata_default GROUP BY 1 ORDER BY 1;
+DROP TABLE cmdata_default;
+
+-- test alter compression method
+ALTER TABLE cmdata_pglz ALTER COLUMN f1 SET COMPRESSION zstd;
+INSERT INTO cmdata_pglz VALUES (repeat('123456789', 4004));
+\d+ cmdata_pglz
+SELECT pg_column_compression(f1) FROM cmdata_pglz;
+ALTER TABLE cmdata_pglz ALTER COLUMN f1 SET COMPRESSION pglz;
+
+-- test alter compression method for materialized views
+ALTER MATERIALIZED VIEW compressmv ALTER COLUMN x SET COMPRESSION zstd;
+\d+ compressmv
+
+-- test alter compression method for partitioned tables
+ALTER TABLE cmpart1 ALTER COLUMN f1 SET COMPRESSION pglz;
+ALTER TABLE cmpart2 ALTER COLUMN f1 SET COMPRESSION zstd;
+
+-- new data should be compressed with the current compression method
+INSERT INTO cmpart VALUES (repeat('123456789', 1004));
+INSERT INTO cmpart VALUES (repeat('123456789', 4004));
+SELECT pg_column_compression(f1) FROM cmpart1;
+SELECT pg_column_compression(f1) FROM cmpart2;
+
+-- VACUUM FULL does not recompress
+SELECT pg_column_compression(f1) FROM cmdata_zstd;
+VACUUM FULL cmdata_zstd;
+SELECT pg_column_compression(f1) FROM cmdata_zstd;
+
+RESET default_toast_compression;
+
+-- check data is ok
+SELECT length(f1) FROM cmdata_pglz;
+SELECT length(f1) FROM cmdata_zstd;
+SELECT length(f1) FROM cmmove1;
+SELECT length(f1) FROM cmmove2;
+SELECT length(f1) FROM cmmove3;
+
+\set HIDE_TOAST_COMPRESSION true
-- 
2.50.1

