v7 is a trivial rebase because of a meson conflict
From 087cf1381c77593f564ae76a0362d3d8f010a6c8 Mon Sep 17 00:00:00 2001
From: Zsolt Parragi <[email protected]>
Date: Sun, 6 Sep 2026 15:08:04 +0000
Subject: [PATCH v7 1/3] Add durable unlogged-reset LSN to pg_control
Record in pg_control where WAL ended the last time the contents of
unlogged relations were discarded, and mirror it in shared memory.
Crash recovery sets it to the end of WAL right after
ResetUnloggedRelations(); pg_resetwal sets it to the new start of WAL,
but only when the reset actually loses data, that is when pg_control
had to be guessed at or the server had not shut down cleanly.
Resetting the WAL of a cleanly shut down cluster leaves unlogged
contents intact, and pg_upgrade depends on that. initdb starts it at
the bootstrap checkpoint.
Add GetUnloggedPopulatedEpoch(), returning that LSN, to be used in a
following commit to stamp when an unlogged matview was populated. A
stamp is always below the LSN of the pg_class change carrying it, and
any node holding that change resets unlogged storage only after
replaying past it, so a stale stamp can never match the current epoch.
A reset counter would not do: two nodes can reach the same count
independently, for example a standby started without standby.signal
after its primary crashed once, and the timeline does not change then.
This changes the pg_control layout, so PG_CONTROL_VERSION needs a bump;
it is left out here to keep the patch from conflicting on every rebase.
---
src/backend/access/transam/xlog.c | 42 +++++++++++++++++++++++++
src/bin/pg_controldata/pg_controldata.c | 2 ++
src/bin/pg_resetwal/pg_resetwal.c | 19 +++++++++++
src/include/access/xlog.h | 1 +
src/include/catalog/pg_control.h | 3 ++
5 files changed, 67 insertions(+)
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index fd37ea4f607..48b51eec206 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -469,6 +469,9 @@ typedef struct XLogCtlData
/* Fake LSN counter, for unlogged relations. */
pg_atomic_uint64 unloggedLSN;
+ /* Shared-memory mirror of ControlFile->unloggedResetLSN. */
+ pg_atomic_uint64 unloggedResetLSN;
+
/* Time and LSN of last xlog segment switch. Protected by WALWriteLock. */
pg_time_t lastSegSwitchTime;
XLogRecPtr lastSegSwitchLSN;
@@ -5235,6 +5238,26 @@ GetFakeLSNForUnloggedRel(void)
return pg_atomic_fetch_add_u64(&XLogCtl->unloggedLSN, 1);
}
+/*
+ * Epoch stamped into pg_class.relpopulated for a populated unlogged matview:
+ * the end of WAL at the last reset of unlogged relations.
+ *
+ * A node stamps only after its reset, so a stamp is always below the LSN of
+ * the pg_class change carrying it. Any node holding that change has replayed
+ * past it, so its own next reset lands beyond the stamp. Hence a stale stamp
+ * cannot match the current epoch, no matter which node wrote it or on which
+ * timeline. The epoch is always a real WAL position, so never one of the
+ * reserved values 0 and 1.
+ */
+uint64
+GetUnloggedPopulatedEpoch(void)
+{
+ uint64 epoch = pg_atomic_read_u64(&XLogCtl->unloggedResetLSN);
+
+ Assert(epoch > 1);
+ return epoch;
+}
+
/*
* Auto-tune the number of XLOG buffers.
*
@@ -5648,6 +5671,7 @@ XLOGShmemInit(void *arg)
pg_atomic_init_u64(&XLogCtl->logFlushResult, InvalidXLogRecPtr);
pg_atomic_init_u64(&XLogCtl->unloggedLSN, InvalidXLogRecPtr);
pg_atomic_init_u64(&XLogCtl->lastChecksumChangeRecPtr, InvalidXLogRecPtr);
+ pg_atomic_init_u64(&XLogCtl->unloggedResetLSN, InvalidXLogRecPtr);
}
/*
@@ -5834,6 +5858,7 @@ BootStrapXLOG(uint32 data_checksum_version)
ControlFile->time = checkPoint.time;
ControlFile->checkPoint = checkPoint.redo;
ControlFile->checkPointCopy = checkPoint;
+ ControlFile->unloggedResetLSN = checkPoint.redo;
/* some additional ControlFile fields are set in WriteControlFile() */
WriteControlFile();
@@ -6355,6 +6380,9 @@ StartupXLOG(void)
pg_atomic_write_membarrier_u64(&XLogCtl->unloggedLSN,
FirstNormalUnloggedLSN);
+ pg_atomic_write_membarrier_u64(&XLogCtl->unloggedResetLSN,
+ ControlFile->unloggedResetLSN);
+
/*
* Copy any missing timeline history files between 'now' and the recovery
* target timeline from archive to pg_wal. While we don't need those files
@@ -6626,8 +6654,22 @@ StartupXLOG(void)
* end-of-recovery steps fail.
*/
if (InRecovery)
+ {
ResetUnloggedRelations(UNLOGGED_RELATION_INIT);
+ /*
+ * That discarded the contents of every unlogged relation, so start a
+ * new epoch at the end of WAL; see GetUnloggedPopulatedEpoch(). If
+ * we crash before this reaches disk, the next recovery ends at or
+ * beyond this point anyway.
+ */
+ LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
+ ControlFile->unloggedResetLSN = EndOfLog;
+ pg_atomic_write_membarrier_u64(&XLogCtl->unloggedResetLSN,
+ ControlFile->unloggedResetLSN);
+ LWLockRelease(ControlFileLock);
+ }
+
/*
* Pre-scan prepared transactions to find out the range of XIDs present.
* This information is not quite needed yet, but it is positioned here so
diff --git a/src/bin/pg_controldata/pg_controldata.c b/src/bin/pg_controldata/pg_controldata.c
index 6a0f848d8d0..37d113a9db1 100644
--- a/src/bin/pg_controldata/pg_controldata.c
+++ b/src/bin/pg_controldata/pg_controldata.c
@@ -295,6 +295,8 @@ main(int argc, char *argv[])
ckpttime_str);
printf(_("Fake LSN counter for unlogged rels: %X/%08X\n"),
LSN_FORMAT_ARGS(ControlFile->unloggedLSN));
+ printf(_("Unlogged relations reset at: %X/%08X\n"),
+ LSN_FORMAT_ARGS(ControlFile->unloggedResetLSN));
printf(_("Minimum recovery ending location: %X/%08X\n"),
LSN_FORMAT_ARGS(ControlFile->minRecoveryPoint));
printf(_("Min recovery ending loc's timeline: %u\n"),
diff --git a/src/bin/pg_resetwal/pg_resetwal.c b/src/bin/pg_resetwal/pg_resetwal.c
index 634d966da9e..1f2254d1a62 100644
--- a/src/bin/pg_resetwal/pg_resetwal.c
+++ b/src/bin/pg_resetwal/pg_resetwal.c
@@ -63,6 +63,7 @@
static ControlFileData ControlFile; /* pg_control values */
static XLogSegNo newXlogSegNo; /* new XLOG segment # */
static bool guessed = false; /* T if we had to guess at any values */
+static bool unlogged_suspect = false; /* T if unlogged data is untrustworthy */
static const char *progname;
/*
@@ -548,6 +549,14 @@ main(int argc, char *argv[])
exit(1);
}
+ /*
+ * Decide whether the contents of unlogged relations survive this reset.
+ * They do if the server shut down cleanly and we did not have to guess at
+ * pg_control; otherwise they are torn, and nothing resets them later
+ * because the next startup will not run crash recovery.
+ */
+ unlogged_suspect = guessed || ControlFile.state != DB_SHUTDOWNED;
+
/*
* Else, do the dirty deed.
*/
@@ -919,6 +928,16 @@ RewriteControlFile(void)
ControlFile.state = DB_SHUTDOWNED;
ControlFile.checkPoint = ControlFile.checkPointCopy.redo;
+
+ /*
+ * Resetting the WAL skips the crash recovery that would otherwise reset
+ * unlogged relations. If their contents cannot be trusted, start a new
+ * epoch at the new start of WAL, which is past any pre-reset epoch stamp
+ * so those read as "not populated".
+ */
+ if (unlogged_suspect)
+ ControlFile.unloggedResetLSN = ControlFile.checkPointCopy.redo;
+
ControlFile.minRecoveryPoint = InvalidXLogRecPtr;
ControlFile.minRecoveryPointTLI = 0;
ControlFile.backupStartPoint = InvalidXLogRecPtr;
diff --git a/src/include/access/xlog.h b/src/include/access/xlog.h
index 2bf5714b51e..50a4a0e73ee 100644
--- a/src/include/access/xlog.h
+++ b/src/include/access/xlog.h
@@ -278,6 +278,7 @@ extern void InitLocalDataChecksumState(void);
extern void SetLocalDataChecksumState(uint32 data_checksum_version);
extern bool GetDefaultCharSignedness(void);
extern XLogRecPtr GetFakeLSNForUnloggedRel(void);
+extern uint64 GetUnloggedPopulatedEpoch(void);
extern void BootStrapXLOG(uint32 data_checksum_version);
extern void InitializeWalConsistencyChecking(void);
extern void LocalProcessControlFile(bool reset);
diff --git a/src/include/catalog/pg_control.h b/src/include/catalog/pg_control.h
index c3c934d0012..888b7f8e325 100644
--- a/src/include/catalog/pg_control.h
+++ b/src/include/catalog/pg_control.h
@@ -143,6 +143,9 @@ typedef struct ControlFileData
CheckPoint checkPointCopy; /* copy of last check point record */
XLogRecPtr unloggedLSN; /* current fake LSN value, for unlogged rels */
+ XLogRecPtr unloggedResetLSN; /* end of WAL when unlogged relations
+ * were last reset (end of recovery) or
+ * became unsafe to trust (pg_resetwal) */
/*
* These two values determine the minimum point we must recover up to
base-commit: 732c475ff803de84136fc79860d535187d9f6986
--
2.56.1
From b3be5ea55202a5113769324a143506f4a554b327 Mon Sep 17 00:00:00 2001
From: Zsolt Parragi <[email protected]>
Date: Sun, 6 Sep 2026 21:03:48 +0000
Subject: [PATCH v7 2/3] Replace pg_class.relispopulated with epoch-capable
relpopulated
Retype the bool relispopulated to an int64 relpopulated: 0 means no
data, 1 means crash-safe populated (every relation except unlogged
matviews), anything else is an epoch stamp recording when an unlogged
matview was populated.
The read side moves to RelationIsPopulated() in matview.c, replacing
the old rel.h macros. Rename rather than reuse the column so external
queries fail loudly. Add pg_matview_is_populated(regclass), used by
pg_matviews. pg_dump reads relpopulated <> 0 and, in binary upgrade,
calls binary_upgrade_set_matview_populated() instead of poking pg_class.
This changes the catalogs, so a catversion bump is needed; it is left
out here to keep the patch from conflicting on every rebase.
---
doc/src/sgml/catalogs.sgml | 27 +++++----
doc/src/sgml/func/func-info.sgml | 16 ++++++
src/backend/catalog/heap.c | 2 +-
src/backend/catalog/system_views.sql | 2 +-
src/backend/commands/copyto.c | 1 +
src/backend/commands/matview.c | 64 +++++++++++++++++++++-
src/backend/commands/repack.c | 1 +
src/backend/executor/execUtils.c | 3 +-
src/backend/utils/adt/pg_upgrade_support.c | 20 +++++++
src/backend/utils/cache/relcache.c | 8 +--
src/bin/pg_dump/pg_dump.c | 39 +++++++++----
src/include/catalog/pg_class.h | 18 ++++--
src/include/catalog/pg_proc.dat | 8 +++
src/include/commands/matview.h | 2 +
src/include/utils/rel.h | 16 ------
src/test/regress/expected/matview.out | 31 ++++++++---
src/test/regress/expected/rules.out | 2 +-
src/test/regress/sql/matview.sql | 9 ++-
18 files changed, 206 insertions(+), 63 deletions(-)
diff --git a/doc/src/sgml/catalogs.sgml b/doc/src/sgml/catalogs.sgml
index 742388d355b..63e47fb5524 100644
--- a/doc/src/sgml/catalogs.sgml
+++ b/doc/src/sgml/catalogs.sgml
@@ -2247,16 +2247,6 @@ SCRAM-SHA-256$<replaceable><iteration count></replaceable>:<replaceable>&l
</para></entry>
</row>
- <row>
- <entry role="catalog_table_entry"><para role="column_definition">
- <structfield>relispopulated</structfield> <type>bool</type>
- </para>
- <para>
- True if relation is populated (this is true for all
- relations other than some materialized views)
- </para></entry>
- </row>
-
<row>
<entry role="catalog_table_entry"><para role="column_definition">
<structfield>relreplident</structfield> <type>char</type>
@@ -2320,6 +2310,23 @@ SCRAM-SHA-256$<replaceable><iteration count></replaceable>:<replaceable>&l
</para></entry>
</row>
+ <row>
+ <entry role="catalog_table_entry"><para role="column_definition">
+ <structfield>relpopulated</structfield> <type>int8</type>
+ </para>
+ <para>
+ Populated epoch. Zero if the relation does not hold data (a
+ materialized view created or refreshed <literal>WITH NO DATA</literal>).
+ One if the relation is populated with crash-safe storage; this is the
+ value for every relation other than a materialized view, and for
+ populated permanent materialized views. Any other value is an epoch
+ stamp recording when an unlogged materialized view was populated; its
+ data is valid only while the cluster remains in that epoch. Use
+ <function>pg_matview_is_populated</function> instead of reading this
+ column directly.
+ </para></entry>
+ </row>
+
<row>
<entry role="catalog_table_entry"><para role="column_definition">
<structfield>relacl</structfield> <type>aclitem[]</type>
diff --git a/doc/src/sgml/func/func-info.sgml b/doc/src/sgml/func/func-info.sgml
index b6c080715ba..6370a0fbd70 100644
--- a/doc/src/sgml/func/func-info.sgml
+++ b/doc/src/sgml/func/func-info.sgml
@@ -1867,6 +1867,22 @@ SELECT currval(pg_get_serial_sequence('sometable', 'id'));
</para></entry>
</row>
+ <row>
+ <entry role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_matview_is_populated</primary>
+ </indexterm>
+ <function>pg_matview_is_populated</function> ( <type>regclass</type> )
+ <returnvalue>boolean</returnvalue>
+ </para>
+ <para>
+ Returns true if the materialized view currently holds valid data,
+ false if it must be refreshed before use. Returns
+ <literal>NULL</literal> for arguments that are not materialized
+ views.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/catalog/heap.c b/src/backend/catalog/heap.c
index 49ef6652203..c5db017aeaa 100644
--- a/src/backend/catalog/heap.c
+++ b/src/backend/catalog/heap.c
@@ -1214,12 +1214,12 @@ InsertPgClassTuple(Relation pg_class_desc,
values[Anum_pg_class_relrowsecurity - 1] = BoolGetDatum(rd_rel->relrowsecurity);
values[Anum_pg_class_relforcerowsecurity - 1] = BoolGetDatum(rd_rel->relforcerowsecurity);
values[Anum_pg_class_relhassubclass - 1] = BoolGetDatum(rd_rel->relhassubclass);
- values[Anum_pg_class_relispopulated - 1] = BoolGetDatum(rd_rel->relispopulated);
values[Anum_pg_class_relreplident - 1] = CharGetDatum(rd_rel->relreplident);
values[Anum_pg_class_relispartition - 1] = BoolGetDatum(rd_rel->relispartition);
values[Anum_pg_class_relrewrite - 1] = ObjectIdGetDatum(rd_rel->relrewrite);
values[Anum_pg_class_relfrozenxid - 1] = TransactionIdGetDatum(rd_rel->relfrozenxid);
values[Anum_pg_class_relminmxid - 1] = MultiXactIdGetDatum(rd_rel->relminmxid);
+ values[Anum_pg_class_relpopulated - 1] = Int64GetDatum(rd_rel->relpopulated);
if (relacl != (Datum) 0)
values[Anum_pg_class_relacl - 1] = relacl;
else
diff --git a/src/backend/catalog/system_views.sql b/src/backend/catalog/system_views.sql
index 6dce9192ba0..aa16e037a2e 100644
--- a/src/backend/catalog/system_views.sql
+++ b/src/backend/catalog/system_views.sql
@@ -150,7 +150,7 @@ CREATE VIEW pg_matviews AS
pg_get_userbyid(C.relowner) AS matviewowner,
T.spcname AS tablespace,
C.relhasindex AS hasindexes,
- C.relispopulated AS ispopulated,
+ pg_matview_is_populated(C.oid) AS ispopulated,
pg_get_viewdef(C.oid) AS definition
FROM pg_class C LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
LEFT JOIN pg_tablespace T ON (T.oid = C.reltablespace)
diff --git a/src/backend/commands/copyto.c b/src/backend/commands/copyto.c
index 9ca06ed3e18..c6f7f6ed8d5 100644
--- a/src/backend/commands/copyto.c
+++ b/src/backend/commands/copyto.c
@@ -24,6 +24,7 @@
#include "access/xlog.h"
#include "catalog/pg_inherits.h"
#include "commands/copyapi.h"
+#include "commands/matview.h"
#include "commands/progress.h"
#include "executor/execdesc.h"
#include "executor/executor.h"
diff --git a/src/backend/commands/matview.c b/src/backend/commands/matview.c
index 40748958eaf..f8c18720e99 100644
--- a/src/backend/commands/matview.c
+++ b/src/backend/commands/matview.c
@@ -20,6 +20,7 @@
#include "access/multixact.h"
#include "access/tableam.h"
#include "access/xact.h"
+#include "access/xlog.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/pg_am.h"
@@ -79,6 +80,7 @@ SetMatViewPopulatedState(Relation relation, bool newstate)
{
Relation pgrel;
HeapTuple tuple;
+ Form_pg_class classform;
Assert(relation->rd_rel->relkind == RELKIND_MATVIEW);
@@ -94,7 +96,14 @@ SetMatViewPopulatedState(Relation relation, bool newstate)
elog(ERROR, "cache lookup failed for relation %u",
RelationGetRelid(relation));
- ((Form_pg_class) GETSTRUCT(tuple))->relispopulated = newstate;
+ classform = (Form_pg_class) GETSTRUCT(tuple);
+
+ if (!newstate)
+ classform->relpopulated = RELPOPULATED_NONE;
+ else if (relation->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED)
+ classform->relpopulated = (int64) GetUnloggedPopulatedEpoch();
+ else
+ classform->relpopulated = RELPOPULATED_ETERNAL;
CatalogTupleUpdate(pgrel, &tuple->t_self, tuple);
@@ -108,6 +117,59 @@ SetMatViewPopulatedState(Relation relation, bool newstate)
CommandCounterIncrement();
}
+/*
+ * MatViewPopulatedValueIsValid
+ * Does this pg_class.relpopulated value denote currently valid data?
+ *
+ * This only distinguishes RELPOPULATED_NONE from everything else; any other
+ * value, whether RELPOPULATED_ETERNAL or an epoch stamp, counts as valid.
+ */
+bool
+MatViewPopulatedValueIsValid(int64 value)
+{
+ return value != RELPOPULATED_NONE;
+}
+
+/*
+ * RelationIsPopulated
+ * Does this relation currently hold valid data? Only a materialized
+ * view can return false.
+ */
+bool
+RelationIsPopulated(Relation relation)
+{
+ return MatViewPopulatedValueIsValid(relation->rd_rel->relpopulated);
+}
+
+/*
+ * pg_matview_is_populated
+ * Does the materialized view currently hold valid data?
+ *
+ * Returns NULL if the argument is not a materialized view, or if it does
+ * not exist.
+ */
+Datum
+pg_matview_is_populated(PG_FUNCTION_ARGS)
+{
+ Oid relid = PG_GETARG_OID(0);
+ HeapTuple tuple;
+ Form_pg_class classform;
+ bool result;
+
+ tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
+ if (!HeapTupleIsValid(tuple))
+ PG_RETURN_NULL();
+ classform = (Form_pg_class) GETSTRUCT(tuple);
+ if (classform->relkind != RELKIND_MATVIEW)
+ {
+ ReleaseSysCache(tuple);
+ PG_RETURN_NULL();
+ }
+ result = MatViewPopulatedValueIsValid(classform->relpopulated);
+ ReleaseSysCache(tuple);
+ PG_RETURN_BOOL(result);
+}
+
/*
* ExecRefreshMatView -- execute a REFRESH MATERIALIZED VIEW command
*
diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 8cf339a9cc7..7b511c5153a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -53,6 +53,7 @@
#include "catalog/pg_inherits.h"
#include "catalog/toasting.h"
#include "commands/defrem.h"
+#include "commands/matview.h"
#include "commands/progress.h"
#include "commands/repack.h"
#include "commands/repack_internal.h"
diff --git a/src/backend/executor/execUtils.c b/src/backend/executor/execUtils.c
index c0c4276acbf..3433e29cad8 100644
--- a/src/backend/executor/execUtils.c
+++ b/src/backend/executor/execUtils.c
@@ -49,6 +49,7 @@
#include "access/table.h"
#include "access/tableam.h"
#include "access/tupconvert.h"
+#include "commands/matview.h"
#include "executor/executor.h"
#include "executor/nodeModifyTable.h"
#include "jit/jit.h"
@@ -778,7 +779,7 @@ ExecOpenScanRelation(EState *estate, Index scanrelid, int eflags)
* to do this, perhaps, but there is no better place.
*/
if ((eflags & (EXEC_FLAG_EXPLAIN_ONLY | EXEC_FLAG_WITH_NO_DATA)) == 0 &&
- !RelationIsScannable(rel))
+ !RelationIsPopulated(rel))
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("materialized view \"%s\" has not been populated",
diff --git a/src/backend/utils/adt/pg_upgrade_support.c b/src/backend/utils/adt/pg_upgrade_support.c
index d7b1c56b2ea..dfb204eb1d6 100644
--- a/src/backend/utils/adt/pg_upgrade_support.c
+++ b/src/backend/utils/adt/pg_upgrade_support.c
@@ -19,6 +19,7 @@
#include "catalog/pg_subscription_rel.h"
#include "catalog/pg_type.h"
#include "commands/extension.h"
+#include "commands/matview.h"
#include "miscadmin.h"
#include "replication/logical.h"
#include "replication/logicallauncher.h"
@@ -30,6 +31,7 @@
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/pg_lsn.h"
+#include "utils/rel.h"
#define CHECK_IS_BINARY_UPGRADE \
@@ -238,6 +240,24 @@ binary_upgrade_set_next_pg_authid_oid(PG_FUNCTION_ARGS)
PG_RETURN_VOID();
}
+Datum
+binary_upgrade_set_matview_populated(PG_FUNCTION_ARGS)
+{
+ Oid relid = PG_GETARG_OID(0);
+ Relation rel;
+
+ CHECK_IS_BINARY_UPGRADE;
+
+ rel = relation_open(relid, AccessExclusiveLock);
+ if (rel->rd_rel->relkind != RELKIND_MATVIEW)
+ elog(ERROR, "relation \"%s\" is not a materialized view",
+ RelationGetRelationName(rel));
+ SetMatViewPopulatedState(rel, true);
+ relation_close(rel, NoLock);
+
+ PG_RETURN_VOID();
+}
+
Datum
binary_upgrade_create_empty_extension(PG_FUNCTION_ARGS)
{
diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c
index 07868bafee2..8758ded07b3 100644
--- a/src/backend/utils/cache/relcache.c
+++ b/src/backend/utils/cache/relcache.c
@@ -1986,7 +1986,7 @@ formrdesc(const char *relationName, Oid relationReltype,
relation->rd_rel->relpersistence = RELPERSISTENCE_PERMANENT;
/* ... and they're always populated, too */
- relation->rd_rel->relispopulated = true;
+ relation->rd_rel->relpopulated = RELPOPULATED_ETERNAL;
relation->rd_rel->relreplident = REPLICA_IDENTITY_NOTHING;
relation->rd_rel->relpages = 0;
@@ -3701,10 +3701,8 @@ RelationBuildLocalRelation(const char *relname,
}
/* if it's a materialized view, it's not populated initially */
- if (relkind == RELKIND_MATVIEW)
- rel->rd_rel->relispopulated = false;
- else
- rel->rd_rel->relispopulated = true;
+ rel->rd_rel->relpopulated = (relkind == RELKIND_MATVIEW) ?
+ RELPOPULATED_NONE : RELPOPULATED_ETERNAL;
/* set replica identity -- system catalogs and non-tables don't have one */
if (!IsCatalogNamespace(relnamespace) &&
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index a3f38f3b886..d9d69dae944 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -7286,8 +7286,26 @@ getTables(Archive *fout, int *numTables)
appendPQExpBufferStr(query,
"c.relhasoids, ");
- appendPQExpBufferStr(query,
- "c.relispopulated, ");
+ /*
+ * A normal dump repopulates matviews with REFRESH, so any nonzero
+ * relpopulated value (the user's intent to have the matview populated)
+ * should dump as populated. Binary upgrade instead transfers the heap
+ * storage as-is, so it must use the effective state: an unlogged matview
+ * whose epoch stamp went stale (storage reset by a crash and never
+ * refreshed) has to be restored as unpopulated, or the new cluster would
+ * present the transferred empty heap as valid data.
+ */
+ if (fout->remoteVersion >= 200000 && fout->dopt->binary_upgrade)
+ appendPQExpBufferStr(query,
+ "(CASE WHEN c.relkind = " CppAsString2(RELKIND_MATVIEW)
+ " THEN pg_catalog.pg_matview_is_populated(c.oid) "
+ "ELSE true END) AS relispopulated, ");
+ else if (fout->remoteVersion >= 200000)
+ appendPQExpBufferStr(query,
+ "c.relpopulated <> 0 AS relispopulated, ");
+ else
+ appendPQExpBufferStr(query,
+ "c.relispopulated, ");
appendPQExpBufferStr(query,
"c.relreplident, ");
@@ -17868,21 +17886,20 @@ dumpTableSchema(Archive *fout, const TableInfo *tbinfo)
}
/*
- * In binary_upgrade mode, restore matviews' populated status by
- * poking pg_class directly. This is pretty ugly, but we can't use
- * REFRESH MATERIALIZED VIEW since it's possible that some underlying
- * matview is not populated even though this matview is; in any case,
- * we want to transfer the matview's heap storage, not run REFRESH.
+ * In binary_upgrade mode, restore matviews' populated status using
+ * the binary_upgrade_set_matview_populated() support function. We
+ * can't use REFRESH MATERIALIZED VIEW since it's possible that some
+ * underlying matview is not populated even though this matview is;
+ * in any case, we want to transfer the matview's heap storage, not
+ * run REFRESH.
*/
if (dopt->binary_upgrade && tbinfo->relkind == RELKIND_MATVIEW &&
tbinfo->relispopulated)
{
appendPQExpBufferStr(q, "\n-- For binary upgrade, mark materialized view as populated\n");
- appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_class\n"
- "SET relispopulated = 't'\n"
- "WHERE oid = ");
+ appendPQExpBufferStr(q, "SELECT pg_catalog.binary_upgrade_set_matview_populated(");
appendStringLiteralAH(q, qualrelname, fout);
- appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
+ appendPQExpBufferStr(q, "::pg_catalog.regclass);\n");
}
/*
diff --git a/src/include/catalog/pg_class.h b/src/include/catalog/pg_class.h
index 0f6aa6d472a..1ace69d9557 100644
--- a/src/include/catalog/pg_class.h
+++ b/src/include/catalog/pg_class.h
@@ -115,9 +115,6 @@ CATALOG(pg_class,1259,RelationRelationId) BKI_BOOTSTRAP BKI_ROWTYPE_OID(83,Relat
/* row security forced for owners or not */
bool relforcerowsecurity BKI_DEFAULT(f);
- /* matview currently holds query results */
- bool relispopulated BKI_DEFAULT(t);
-
/* see REPLICA_IDENTITY_xxx constants */
char relreplident BKI_DEFAULT(n);
@@ -133,6 +130,15 @@ CATALOG(pg_class,1259,RelationRelationId) BKI_BOOTSTRAP BKI_ROWTYPE_OID(83,Relat
/* all multixacts in this rel are >= this; it is really a MultiXactId */
TransactionId relminmxid BKI_DEFAULT(1); /* FirstMultiXactId */
+ /*
+ * Populated epoch. 0 (RELPOPULATED_NONE): no data. 1
+ * (RELPOPULATED_ETERNAL): crash-safe populated, used for every relation
+ * except unlogged matviews. Any other value is an epoch stamp for a
+ * populated unlogged matview, valid only while the cluster stays in that
+ * epoch. See MatViewPopulatedValueIsValid().
+ */
+ int64 relpopulated BKI_DEFAULT(1);
+
#ifdef CATALOG_VARLEN /* variable-length fields start here */
/* NOTE: These fields are not present in a relcache entry's rd_rel field. */
/* access permissions */
@@ -150,7 +156,7 @@ END_CATALOG_STRUCT
/* Size of fixed part of pg_class tuples, not counting var-length fields */
#define CLASS_TUPLE_SIZE \
- (offsetof(FormData_pg_class,relminmxid) + sizeof(TransactionId))
+ (offsetof(FormData_pg_class,relpopulated) + sizeof(int64))
/* ----------------
* Form_pg_class corresponds to a pointer to a tuple with
@@ -179,6 +185,10 @@ MAKE_SYSCACHE(RELNAMENSP, pg_class_relname_nsp_index, 128);
#define RELKIND_PARTITIONED_TABLE 'p' /* partitioned table */
#define RELKIND_PARTITIONED_INDEX 'I' /* partitioned index */
+/* Reserved values of pg_class.relpopulated; any other value is an epoch. */
+#define RELPOPULATED_NONE 0 /* not populated */
+#define RELPOPULATED_ETERNAL 1 /* populated, storage is crash-safe */
+
#define RELPERSISTENCE_PERMANENT 'p' /* regular table */
#define RELPERSISTENCE_UNLOGGED 'u' /* unlogged permanent table */
#define RELPERSISTENCE_TEMP 't' /* temporary table */
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 50fb182cb79..20e1fe09efa 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -12039,6 +12039,10 @@
proname => 'binary_upgrade_set_next_pg_tablespace_oid', provolatile => 'v',
proparallel => 'u', prorettype => 'void', proargtypes => 'oid',
prosrc => 'binary_upgrade_set_next_pg_tablespace_oid' },
+{ oid => '8668', descr => 'for use by pg_upgrade',
+ proname => 'binary_upgrade_set_matview_populated', provolatile => 'v',
+ proparallel => 'u', prorettype => 'void', proargtypes => 'oid',
+ prosrc => 'binary_upgrade_set_matview_populated' },
{ oid => '6312', descr => 'for use by pg_upgrade',
proname => 'binary_upgrade_check_logical_slot_pending_wal',
provolatile => 'v', proparallel => 'u', prorettype => 'pg_lsn',
@@ -12412,6 +12416,10 @@
proname => 'pg_relation_is_publishable', provolatile => 's',
prorettype => 'bool', proargtypes => 'regclass',
prosrc => 'pg_relation_is_publishable' },
+{ oid => '8667', descr => 'is materialized view populated',
+ proname => 'pg_matview_is_populated', provolatile => 's',
+ prorettype => 'bool', proargtypes => 'regclass',
+ prosrc => 'pg_matview_is_populated' },
# rls
{ oid => '3298',
diff --git a/src/include/commands/matview.h b/src/include/commands/matview.h
index 738c731c1a9..06096e43601 100644
--- a/src/include/commands/matview.h
+++ b/src/include/commands/matview.h
@@ -22,6 +22,8 @@
extern void SetMatViewPopulatedState(Relation relation, bool newstate);
+extern bool MatViewPopulatedValueIsValid(int64 value);
+extern bool RelationIsPopulated(Relation relation);
extern ObjectAddress ExecRefreshMatView(RefreshMatViewStmt *stmt, const char *queryString,
QueryCompletion *qc);
diff --git a/src/include/utils/rel.h b/src/include/utils/rel.h
index 7b8c2b1e362..65a5933a26f 100644
--- a/src/include/utils/rel.h
+++ b/src/include/utils/rel.h
@@ -708,22 +708,6 @@ RelationCloseSmgr(Relation relation)
!(relation)->rd_islocaltemp)
-/*
- * RelationIsScannable
- * Currently can only be false for a materialized view which has not been
- * populated by its query. This is likely to get more complicated later,
- * so use a macro which looks like a function.
- */
-#define RelationIsScannable(relation) ((relation)->rd_rel->relispopulated)
-
-/*
- * RelationIsPopulated
- * Currently, we don't physically distinguish the "populated" and
- * "scannable" properties of matviews, but that may change later.
- * Hence, use the appropriate one of these macros in code tests.
- */
-#define RelationIsPopulated(relation) ((relation)->rd_rel->relispopulated)
-
/*
* RelationIsAccessibleInLogicalDecoding
* True if we need to log enough information to have access via
diff --git a/src/test/regress/expected/matview.out b/src/test/regress/expected/matview.out
index 0355720dfc6..7500bf027da 100644
--- a/src/test/regress/expected/matview.out
+++ b/src/test/regress/expected/matview.out
@@ -27,9 +27,9 @@ EXPLAIN (costs off)
(3 rows)
CREATE MATERIALIZED VIEW mvtest_tm AS SELECT type, sum(amt) AS totamt FROM mvtest_t GROUP BY type WITH NO DATA;
-SELECT relispopulated FROM pg_class WHERE oid = 'mvtest_tm'::regclass;
- relispopulated
-----------------
+SELECT pg_matview_is_populated('mvtest_tm'::regclass);
+ pg_matview_is_populated
+-------------------------
f
(1 row)
@@ -37,12 +37,25 @@ SELECT * FROM mvtest_tm ORDER BY type;
ERROR: materialized view "mvtest_tm" has not been populated
HINT: Use the REFRESH MATERIALIZED VIEW command.
REFRESH MATERIALIZED VIEW mvtest_tm;
-SELECT relispopulated FROM pg_class WHERE oid = 'mvtest_tm'::regclass;
- relispopulated
-----------------
+SELECT pg_matview_is_populated('mvtest_tm'::regclass);
+ pg_matview_is_populated
+-------------------------
t
(1 row)
+-- ... but NULL for a relation that is not a materialized view, or nonexistent
+SELECT pg_matview_is_populated('mvtest_t'::regclass);
+ pg_matview_is_populated
+-------------------------
+
+(1 row)
+
+SELECT pg_matview_is_populated(0);
+ pg_matview_is_populated
+-------------------------
+
+(1 row)
+
CREATE UNIQUE INDEX mvtest_tm_type ON mvtest_tm (type);
SELECT * FROM mvtest_tm ORDER BY type;
type | totamt
@@ -376,9 +389,9 @@ UNION ALL
FROM mvtest_vt2;
CREATE MATERIALIZED VIEW mv_test3 AS SELECT * FROM mv_test2 WHERE moo = 12345;
-SELECT relispopulated FROM pg_class WHERE oid = 'mv_test3'::regclass;
- relispopulated
-----------------
+SELECT pg_matview_is_populated('mv_test3'::regclass);
+ pg_matview_is_populated
+-------------------------
t
(1 row)
diff --git a/src/test/regress/expected/rules.out b/src/test/regress/expected/rules.out
index acbe4667d89..f8a9e1edfd4 100644
--- a/src/test/regress/expected/rules.out
+++ b/src/test/regress/expected/rules.out
@@ -1414,7 +1414,7 @@ pg_matviews| SELECT n.nspname AS schemaname,
pg_get_userbyid(c.relowner) AS matviewowner,
t.spcname AS tablespace,
c.relhasindex AS hasindexes,
- c.relispopulated AS ispopulated,
+ pg_matview_is_populated((c.oid)::regclass) AS ispopulated,
pg_get_viewdef(c.oid) AS definition
FROM ((pg_class c
LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace)))
diff --git a/src/test/regress/sql/matview.sql b/src/test/regress/sql/matview.sql
index 934426b9ae8..8890a2f7932 100644
--- a/src/test/regress/sql/matview.sql
+++ b/src/test/regress/sql/matview.sql
@@ -15,10 +15,13 @@ SELECT * FROM mvtest_tv ORDER BY type;
EXPLAIN (costs off)
CREATE MATERIALIZED VIEW mvtest_tm AS SELECT type, sum(amt) AS totamt FROM mvtest_t GROUP BY type WITH NO DATA;
CREATE MATERIALIZED VIEW mvtest_tm AS SELECT type, sum(amt) AS totamt FROM mvtest_t GROUP BY type WITH NO DATA;
-SELECT relispopulated FROM pg_class WHERE oid = 'mvtest_tm'::regclass;
+SELECT pg_matview_is_populated('mvtest_tm'::regclass);
SELECT * FROM mvtest_tm ORDER BY type;
REFRESH MATERIALIZED VIEW mvtest_tm;
-SELECT relispopulated FROM pg_class WHERE oid = 'mvtest_tm'::regclass;
+SELECT pg_matview_is_populated('mvtest_tm'::regclass);
+-- ... but NULL for a relation that is not a materialized view, or nonexistent
+SELECT pg_matview_is_populated('mvtest_t'::regclass);
+SELECT pg_matview_is_populated(0);
CREATE UNIQUE INDEX mvtest_tm_type ON mvtest_tm (type);
SELECT * FROM mvtest_tm ORDER BY type;
@@ -122,7 +125,7 @@ CREATE VIEW mvtest_vt2 AS SELECT moo, 2*moo FROM mvtest_vt1 UNION ALL SELECT moo
CREATE MATERIALIZED VIEW mv_test2 AS SELECT moo, 2*moo FROM mvtest_vt2 UNION ALL SELECT moo, 3*moo FROM mvtest_vt2;
\d+ mv_test2
CREATE MATERIALIZED VIEW mv_test3 AS SELECT * FROM mv_test2 WHERE moo = 12345;
-SELECT relispopulated FROM pg_class WHERE oid = 'mv_test3'::regclass;
+SELECT pg_matview_is_populated('mv_test3'::regclass);
DROP VIEW mvtest_vt1 CASCADE;
--
2.56.1
From b2a369534381df050a2778b67194b4b72e22fca3 Mon Sep 17 00:00:00 2001
From: Zsolt Parragi <[email protected]>
Date: Sun, 6 Sep 2026 20:50:14 +0000
Subject: [PATCH v7 3/3] Add unlogged materialized views
Allow CREATE and ALTER UNLOGGED MATERIALIZED VIEW. Storage is unlogged,
so REFRESH populates the data without WAL-logging it. Stamp the
populated epoch on refresh and treat stale epochs (after a crash,
promotion, or PITR) as unpopulated. Support ALTER MATERIALIZED VIEW
SET LOGGED/UNLOGGED, teach psql to report an unlogged materialized view
as such and to tab-complete the new syntax. Add recovery tests for the
crash, standby and promotion cases, plus docs.
---
doc/src/sgml/func/func-info.sgml | 4 +-
doc/src/sgml/ref/alter_materialized_view.sgml | 24 ++
.../sgml/ref/create_materialized_view.sgml | 44 +++-
doc/src/sgml/storage.sgml | 10 +
src/backend/access/heap/heapam_handler.c | 3 +-
src/backend/commands/copyto.c | 5 +
src/backend/commands/matview.c | 41 ++-
src/backend/commands/repack.c | 23 ++
src/backend/commands/tablecmds.c | 3 +-
src/backend/parser/analyze.c | 12 -
src/bin/pg_dump/pg_dump.c | 9 +-
src/bin/pg_dump/t/002_pg_dump.pl | 36 +++
src/bin/psql/describe.c | 8 +-
src/bin/psql/tab-complete.in.c | 23 +-
src/test/recovery/meson.build | 2 +
src/test/recovery/t/062_unlogged_matview.pl | 150 +++++++++++
.../t/063_unlogged_matview_standby.pl | 192 ++++++++++++++
src/test/regress/expected/matview.out | 238 ++++++++++++++++++
src/test/regress/sql/matview.sql | 74 ++++++
19 files changed, 859 insertions(+), 42 deletions(-)
create mode 100644 src/test/recovery/t/062_unlogged_matview.pl
create mode 100644 src/test/recovery/t/063_unlogged_matview_standby.pl
diff --git a/doc/src/sgml/func/func-info.sgml b/doc/src/sgml/func/func-info.sgml
index 6370a0fbd70..ad8f60fa2d8 100644
--- a/doc/src/sgml/func/func-info.sgml
+++ b/doc/src/sgml/func/func-info.sgml
@@ -1879,7 +1879,9 @@ SELECT currval(pg_get_serial_sequence('sometable', 'id'));
Returns true if the materialized view currently holds valid data,
false if it must be refreshed before use. Returns
<literal>NULL</literal> for arguments that are not materialized
- views.
+ views. Unlike reading <structname>pg_class</structname> directly,
+ this accounts for unlogged materialized views whose contents were
+ removed by a crash or are unavailable during recovery.
</para></entry>
</row>
diff --git a/doc/src/sgml/ref/alter_materialized_view.sgml b/doc/src/sgml/ref/alter_materialized_view.sgml
index f81a7393f5d..9fc6e4a4b34 100644
--- a/doc/src/sgml/ref/alter_materialized_view.sgml
+++ b/doc/src/sgml/ref/alter_materialized_view.sgml
@@ -45,6 +45,7 @@ ALTER MATERIALIZED VIEW ALL IN TABLESPACE <replaceable class="parameter">name</r
SET WITHOUT CLUSTER
SET ACCESS METHOD <replaceable class="parameter">new_access_method</replaceable>
SET TABLESPACE <replaceable class="parameter">new_tablespace</replaceable>
+ SET { LOGGED | UNLOGGED }
SET ( <replaceable class="parameter">storage_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )
RESET ( <replaceable class="parameter">storage_parameter</replaceable> [, ... ] )
OWNER TO { <replaceable class="parameter">new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER }
@@ -152,6 +153,29 @@ ALTER MATERIALIZED VIEW ALL IN TABLESPACE <replaceable class="parameter">name</r
</para>
</listitem>
</varlistentry>
+
+ <varlistentry>
+ <term><literal>SET { LOGGED | UNLOGGED }</literal></term>
+ <listitem>
+ <para>
+ This form changes the materialized view from unlogged to logged or
+ vice-versa (see <literal>UNLOGGED</literal> in
+ <link linkend="sql-creatematerializedview-unlogged"><command>CREATE
+ MATERIALIZED VIEW</command></link>), the same as
+ <link linkend="sql-altertable-desc-set-logged-unlogged"><literal>SET
+ { LOGGED | UNLOGGED }</literal></link> does for
+ <command>ALTER TABLE</command>. The change takes effect immediately:
+ whatever the materialized view currently holds is preserved and remains
+ queryable, no crash or refresh is involved. Once set to
+ <literal>UNLOGGED</literal>, however, the contents will be lost after
+ a future crash or unclean shutdown, at which point the materialized
+ view reverts to the unpopulated state. Conversely, setting an unlogged
+ materialized view that has already reverted to the unpopulated state
+ back to <literal>LOGGED</literal> leaves it unpopulated; there is no
+ data left to make crash-safe.
+ </para>
+ </listitem>
+ </varlistentry>
</variablelist>
</refsect1>
diff --git a/doc/src/sgml/ref/create_materialized_view.sgml b/doc/src/sgml/ref/create_materialized_view.sgml
index 62d897931c3..320fcb62424 100644
--- a/doc/src/sgml/ref/create_materialized_view.sgml
+++ b/doc/src/sgml/ref/create_materialized_view.sgml
@@ -21,7 +21,7 @@ PostgreSQL documentation
<refsynopsisdiv>
<synopsis>
-CREATE MATERIALIZED VIEW [ IF NOT EXISTS ] <replaceable>table_name</replaceable>
+CREATE [ UNLOGGED ] MATERIALIZED VIEW [ IF NOT EXISTS ] <replaceable>table_name</replaceable>
[ (<replaceable>column_name</replaceable> [, ...] ) ]
[ USING <replaceable class="parameter">method</replaceable> ]
[ WITH ( <replaceable class="parameter">storage_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] ) ]
@@ -60,7 +60,33 @@ CREATE MATERIALIZED VIEW [ IF NOT EXISTS ] <replaceable>table_name</replaceable>
<title>Parameters</title>
<variablelist>
- <varlistentry>
+ <varlistentry id="sql-creatematerializedview-unlogged">
+ <term><literal>UNLOGGED</literal></term>
+ <listitem>
+ <para>
+ If specified, the materialized view is created as an unlogged
+ materialized view. Data written to an unlogged materialized view is
+ not written to the write-ahead log (see <xref linkend="wal"/>), which
+ makes populating it, whether by <command>CREATE MATERIALIZED
+ VIEW</command> or by a later <command>REFRESH MATERIALIZED
+ VIEW</command>, considerably faster. However, an unlogged materialized
+ view is not crash-safe: its contents are discarded after a crash or
+ unclean shutdown, at which point the materialized view reverts to the
+ unpopulated state and must be rebuilt with <command>REFRESH
+ MATERIALIZED VIEW</command> before it can be queried again, the same as
+ a materialized view created with <literal>WITH NO DATA</literal> (see
+ below). Unlike an unlogged table, which reads as empty after a crash,
+ an unlogged materialized view instead reports that it has not been
+ populated. Contents are preserved across a normal shutdown and
+ restart. The contents of an unlogged materialized view are also not
+ replicated to standby servers, so like an unlogged table it cannot be
+ queried on a standby, and is shown as not populated there even
+ immediately after the primary refreshes it.
+ </para>
+ </listitem>
+ </varlistentry>
+
+ <varlistentry id="sql-creatematerializedview-parms-if-not-exists">
<term><literal>IF NOT EXISTS</literal></term>
<listitem>
<para>
@@ -72,7 +98,7 @@ CREATE MATERIALIZED VIEW [ IF NOT EXISTS ] <replaceable>table_name</replaceable>
</listitem>
</varlistentry>
- <varlistentry>
+ <varlistentry id="sql-creatematerializedview-parms-table-name">
<term><replaceable>table_name</replaceable></term>
<listitem>
<para>
@@ -84,7 +110,7 @@ CREATE MATERIALIZED VIEW [ IF NOT EXISTS ] <replaceable>table_name</replaceable>
</listitem>
</varlistentry>
- <varlistentry>
+ <varlistentry id="sql-creatematerializedview-parms-column-name">
<term><replaceable>column_name</replaceable></term>
<listitem>
<para>
@@ -94,7 +120,7 @@ CREATE MATERIALIZED VIEW [ IF NOT EXISTS ] <replaceable>table_name</replaceable>
</listitem>
</varlistentry>
- <varlistentry>
+ <varlistentry id="sql-creatematerializedview-parms-using">
<term><literal>USING <replaceable class="parameter">method</replaceable></literal></term>
<listitem>
<para>
@@ -109,7 +135,7 @@ CREATE MATERIALIZED VIEW [ IF NOT EXISTS ] <replaceable>table_name</replaceable>
</listitem>
</varlistentry>
- <varlistentry>
+ <varlistentry id="sql-creatematerializedview-parms-with">
<term><literal>WITH ( <replaceable class="parameter">storage_parameter</replaceable> [= <replaceable class="parameter">value</replaceable>] [, ... ] )</literal></term>
<listitem>
<para>
@@ -125,7 +151,7 @@ CREATE MATERIALIZED VIEW [ IF NOT EXISTS ] <replaceable>table_name</replaceable>
</listitem>
</varlistentry>
- <varlistentry>
+ <varlistentry id="sql-creatematerializedview-parms-tablespace">
<term><literal>TABLESPACE <replaceable class="parameter">tablespace_name</replaceable></literal></term>
<listitem>
<para>
@@ -136,7 +162,7 @@ CREATE MATERIALIZED VIEW [ IF NOT EXISTS ] <replaceable>table_name</replaceable>
</listitem>
</varlistentry>
- <varlistentry>
+ <varlistentry id="sql-creatematerializedview-parms-query">
<term><replaceable>query</replaceable></term>
<listitem>
<para>
@@ -150,7 +176,7 @@ CREATE MATERIALIZED VIEW [ IF NOT EXISTS ] <replaceable>table_name</replaceable>
</listitem>
</varlistentry>
- <varlistentry>
+ <varlistentry id="sql-creatematerializedview-parms-with-data">
<term><literal>WITH [ NO ] DATA</literal></term>
<listitem>
<para>
diff --git a/doc/src/sgml/storage.sgml b/doc/src/sgml/storage.sgml
index 58f997d5da0..07be8aea0af 100644
--- a/doc/src/sgml/storage.sgml
+++ b/doc/src/sgml/storage.sgml
@@ -704,6 +704,16 @@ initialization fork is copied over the main fork, and any other forks are
erased (they will be recreated automatically as needed).
</para>
+<para>
+An unlogged materialized view has an initialization fork too, and its
+storage is reset the same way after a crash. Because a materialized view
+additionally tracks whether it is populated, resetting its storage also
+makes it read as unpopulated rather than as empty; a subsequent
+<command>REFRESH MATERIALIZED VIEW</command> repopulates it. This check
+happens whenever the materialized view is accessed, so no explicit repair
+step or new session is required after the crash.
+</para>
+
</sect1>
<sect1 id="storage-page-layout">
diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index 1437274b0c6..fc6bedeecba 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -518,7 +518,8 @@ heapam_relation_set_new_filelocator(Relation rel,
if (persistence == RELPERSISTENCE_UNLOGGED)
{
Assert(rel->rd_rel->relkind == RELKIND_RELATION ||
- rel->rd_rel->relkind == RELKIND_TOASTVALUE);
+ rel->rd_rel->relkind == RELKIND_TOASTVALUE ||
+ rel->rd_rel->relkind == RELKIND_MATVIEW);
smgrcreate(srel, INIT_FORKNUM, false);
log_smgrcreate(newrlocator, INIT_FORKNUM);
}
diff --git a/src/backend/commands/copyto.c b/src/backend/commands/copyto.c
index c6f7f6ed8d5..436311ce437 100644
--- a/src/backend/commands/copyto.c
+++ b/src/backend/commands/copyto.c
@@ -837,6 +837,11 @@ BeginCopyTo(ParseState *pstate,
errhint("Try the COPY (SELECT ...) TO variant.")));
else if (rel->rd_rel->relkind == RELKIND_MATVIEW)
{
+ /* Unlogged matviews have no data during recovery. */
+ if (!RelationIsPermanent(rel) && RecoveryInProgress())
+ ereport(ERROR,
+ errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("cannot access temporary or unlogged relations during recovery"));
if (!RelationIsPopulated(rel))
ereport(ERROR,
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
diff --git a/src/backend/commands/matview.c b/src/backend/commands/matview.c
index f8c18720e99..8573876e4be 100644
--- a/src/backend/commands/matview.c
+++ b/src/backend/commands/matview.c
@@ -120,14 +120,25 @@ SetMatViewPopulatedState(Relation relation, bool newstate)
/*
* MatViewPopulatedValueIsValid
* Does this pg_class.relpopulated value denote currently valid data?
- *
- * This only distinguishes RELPOPULATED_NONE from everything else; any other
- * value, whether RELPOPULATED_ETERNAL or an epoch stamp, counts as valid.
*/
bool
MatViewPopulatedValueIsValid(int64 value)
{
- return value != RELPOPULATED_NONE;
+ if (value == RELPOPULATED_NONE)
+ return false;
+ if (value == RELPOPULATED_ETERNAL)
+ return true;
+
+ /*
+ * Epoch stamp: valid only if it matches the current epoch. During
+ * recovery always treat it as invalid -- a standby never has the unlogged
+ * data, and its epoch is still the one its base backup came with, which
+ * may well be the primary's current one.
+ */
+ if (RecoveryInProgress())
+ return false;
+
+ return (uint64) value == GetUnloggedPopulatedEpoch();
}
/*
@@ -138,6 +149,12 @@ MatViewPopulatedValueIsValid(int64 value)
bool
RelationIsPopulated(Relation relation)
{
+ /* Only unlogged matviews may carry an epoch stamp. */
+ Assert(relation->rd_rel->relpopulated == RELPOPULATED_NONE ||
+ relation->rd_rel->relpopulated == RELPOPULATED_ETERNAL ||
+ (relation->rd_rel->relkind == RELKIND_MATVIEW &&
+ relation->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED));
+
return MatViewPopulatedValueIsValid(relation->rd_rel->relpopulated);
}
@@ -356,10 +373,20 @@ RefreshMatViewByOid(Oid matviewOid, bool is_create, bool skipData,
/*
* Tentatively mark the matview as populated or not, if its state is
- * changing (this will roll back if we fail later).
+ * changing (this will roll back if we fail later). WITH NO DATA must
+ * also clear a stale epoch stamp, which reads as not populated but still
+ * records that the matview is meant to hold data.
*/
- if (RelationIsPopulated(matviewRel) != !skipData)
- SetMatViewPopulatedState(matviewRel, !skipData);
+ if (skipData)
+ {
+ if (matviewRel->rd_rel->relpopulated != RELPOPULATED_NONE)
+ SetMatViewPopulatedState(matviewRel, false);
+ }
+ else
+ {
+ if (!RelationIsPopulated(matviewRel))
+ SetMatViewPopulatedState(matviewRel, true);
+ }
/* Concurrent refresh builds new data in temp tablespace, and does diff. */
if (concurrent)
diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 7b511c5153a..14ad34a9ac4 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -1718,6 +1718,29 @@ swap_relation_files(Oid r1, Oid r2, bool target_is_pg_class,
relform1->relpersistence = relform2->relpersistence;
relform2->relpersistence = swptmpchr;
+ /*
+ * A matview's relpopulated value encodes its persistence class:
+ * permanent matviews use RELPOPULATED_ETERNAL, unlogged matviews
+ * carry an epoch stamp. Convert the value alongside the persistence
+ * change (relform1 is the surviving relation's own pg_class row; the
+ * relkind check skips it in the recursive call for TOAST). A stale
+ * stamp (populated before the last crash or promotion) means the
+ * storage is empty, so converting it to LOGGED must yield "not
+ * populated" rather than eternally-populated garbage.
+ */
+ if (relform1->relkind == RELKIND_MATVIEW &&
+ relform1->relpopulated != RELPOPULATED_NONE)
+ {
+ if (relform1->relpersistence == RELPERSISTENCE_UNLOGGED &&
+ relform1->relpopulated == RELPOPULATED_ETERNAL)
+ relform1->relpopulated = (int64) GetUnloggedPopulatedEpoch();
+ else if (relform1->relpersistence == RELPERSISTENCE_PERMANENT &&
+ relform1->relpopulated != RELPOPULATED_ETERNAL)
+ relform1->relpopulated =
+ MatViewPopulatedValueIsValid(relform1->relpopulated)
+ ? RELPOPULATED_ETERNAL : RELPOPULATED_NONE;
+ }
+
/* Also swap toast links, if we're swapping by links */
if (!swap_toast_by_content)
{
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 9786a5af58a..c0c72f1c5a1 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -5217,7 +5217,8 @@ ATPrepCmd(List **wqueue, Relation rel, AlterTableCmd *cmd,
break;
case AT_SetLogged: /* SET LOGGED */
case AT_SetUnLogged: /* SET UNLOGGED */
- ATSimplePermissions(cmd->subtype, rel, ATT_TABLE | ATT_SEQUENCE);
+ ATSimplePermissions(cmd->subtype, rel,
+ ATT_TABLE | ATT_SEQUENCE | ATT_MATVIEW);
if (tab->chgPersistence)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c
index c980d65c743..05b073bdf96 100644
--- a/src/backend/parser/analyze.c
+++ b/src/backend/parser/analyze.c
@@ -3216,18 +3216,6 @@ transformCreateTableAsStmt(ParseState *pstate, CreateTableAsStmt *stmt)
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("materialized views may not be defined using bound parameters")));
- /*
- * For now, we disallow unlogged materialized views, because it seems
- * like a bad idea for them to just go to empty after a crash. (If we
- * could mark them as unpopulated, that would be better, but that
- * requires catalog changes which crash recovery can't presently
- * handle.)
- */
- if (stmt->into->rel->relpersistence == RELPERSISTENCE_UNLOGGED)
- ereport(ERROR,
- (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
- errmsg("materialized views cannot be unlogged")));
-
/*
* At runtime, we'll need a copy of the parsed-but-not-rewritten Query
* for purposes of creating the view's ON SELECT rule. We stash that
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index d9d69dae944..343399e160b 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -3028,8 +3028,15 @@ makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo)
if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
return;
- /* Don't dump data in unlogged tables, if so requested */
+ /*
+ * Don't dump data in unlogged tables, if so requested. This does not
+ * apply to unlogged materialized views: their REFRESH carries no data,
+ * and skipping it would break the REFRESH of any matview built on top.
+ * XXX Whether the option should also cover them (and mark dependent
+ * matviews unpopulated instead) is an open question.
+ */
if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
+ tbinfo->relkind != RELKIND_MATVIEW &&
dopt->no_unlogged_table_data)
return;
diff --git a/src/bin/pg_dump/t/002_pg_dump.pl b/src/bin/pg_dump/t/002_pg_dump.pl
index ec73c4d5be9..b199ca6926b 100644
--- a/src/bin/pg_dump/t/002_pg_dump.pl
+++ b/src/bin/pg_dump/t/002_pg_dump.pl
@@ -3095,6 +3095,25 @@ my %tests = (
},
},
+ 'CREATE UNLOGGED MATERIALIZED VIEW matview_unlogged' => {
+ create_order => 21,
+ create_sql => 'CREATE UNLOGGED MATERIALIZED VIEW
+ dump_test.matview_unlogged (col1) AS
+ SELECT * FROM dump_test.matview;',
+ regexp => qr/^
+ \QCREATE UNLOGGED MATERIALIZED VIEW dump_test.matview_unlogged AS\E
+ \n\s+\QSELECT col1\E
+ \n\s+\QFROM dump_test.matview\E
+ \n\s+\QWITH NO DATA;\E
+ /xm,
+ like =>
+ { %full_runs, %dump_test_schema_runs, section_pre_data => 1, },
+ unlike => {
+ exclude_dump_test_schema => 1,
+ only_dump_measurement => 1,
+ },
+ },
+
'CREATE MATERIALIZED VIEW matview_third' => {
create_order => 58,
create_sql => 'CREATE MATERIALIZED VIEW
@@ -4815,6 +4834,23 @@ my %tests = (
},
},
+ # not affected by --no-unlogged-table-data
+ 'REFRESH MATERIALIZED VIEW matview_unlogged' => {
+ regexp => qr/^
+ \QREFRESH MATERIALIZED VIEW dump_test.matview;\E
+ \n.*
+ \QREFRESH MATERIALIZED VIEW dump_test.matview_unlogged;\E
+ /xms,
+ like =>
+ { %full_runs, %dump_test_schema_runs, section_post_data => 1, },
+ unlike => {
+ binary_upgrade => 1,
+ exclude_dump_test_schema => 1,
+ schema_only => 1,
+ only_dump_measurement => 1,
+ },
+ },
+
'REFRESH MATERIALIZED VIEW matview_second' => {
regexp => qr/^
\QREFRESH MATERIALIZED VIEW dump_test.matview;\E
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index 23e2b3c51df..803c73a8e83 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -1930,8 +1930,12 @@ describeOneTableDetails(const char *schemaname,
schemaname, relationname);
break;
case RELKIND_MATVIEW:
- printfPQExpBuffer(&title, _("Materialized view \"%s.%s\""),
- schemaname, relationname);
+ if (tableinfo.relpersistence == RELPERSISTENCE_UNLOGGED)
+ printfPQExpBuffer(&title, _("Unlogged materialized view \"%s.%s\""),
+ schemaname, relationname);
+ else
+ printfPQExpBuffer(&title, _("Materialized view \"%s.%s\""),
+ schemaname, relationname);
break;
case RELKIND_INDEX:
if (tableinfo.relpersistence == RELPERSISTENCE_UNLOGGED)
diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c
index 96de78cd087..9db8c59d4eb 100644
--- a/src/bin/psql/tab-complete.in.c
+++ b/src/bin/psql/tab-complete.in.c
@@ -2724,7 +2724,8 @@ match_previous_words(int pattern_id,
COMPLETE_WITH("TO");
/* ALTER MATERIALIZED VIEW xxx SET */
else if (Matches("ALTER", "MATERIALIZED", "VIEW", MatchAny, "SET"))
- COMPLETE_WITH("(", "ACCESS METHOD", "SCHEMA", "TABLESPACE", "WITHOUT CLUSTER");
+ COMPLETE_WITH("(", "ACCESS METHOD", "LOGGED", "SCHEMA", "TABLESPACE",
+ "UNLOGGED", "WITHOUT CLUSTER");
/* ALTER MATERIALIZED VIEW xxx SET ACCESS METHOD */
else if (Matches("ALTER", "MATERIALIZED", "VIEW", MatchAny, "SET", "ACCESS", "METHOD"))
COMPLETE_WITH_QUERY(Query_for_list_of_table_access_methods);
@@ -3796,9 +3797,9 @@ match_previous_words(int pattern_id,
/* Complete "CREATE TEMP/TEMPORARY" with the possible temp objects */
else if (TailMatches("CREATE", "TEMP|TEMPORARY"))
COMPLETE_WITH("SEQUENCE", "TABLE", "VIEW");
- /* Complete "CREATE UNLOGGED" with TABLE or SEQUENCE */
+ /* Complete "CREATE UNLOGGED" with the possible unlogged objects */
else if (TailMatches("CREATE", "UNLOGGED"))
- COMPLETE_WITH("TABLE", "SEQUENCE");
+ COMPLETE_WITH("MATERIALIZED VIEW", "SEQUENCE", "TABLE");
/* Complete PARTITION BY with RANGE ( or LIST ( or ... */
else if (TailMatches("PARTITION", "BY"))
COMPLETE_WITH("RANGE (", "LIST (", "HASH (");
@@ -4190,20 +4191,24 @@ match_previous_words(int pattern_id,
COMPLETE_WITH("SELECT");
/* CREATE MATERIALIZED VIEW */
- else if (Matches("CREATE", "MATERIALIZED"))
+ else if (Matches("CREATE", "MATERIALIZED") ||
+ Matches("CREATE", "UNLOGGED", "MATERIALIZED"))
COMPLETE_WITH("VIEW");
/* Complete CREATE MATERIALIZED VIEW <name> with AS or USING */
- else if (Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny))
+ else if (Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny) ||
+ Matches("CREATE", "UNLOGGED", "MATERIALIZED", "VIEW", MatchAny))
COMPLETE_WITH("AS", "USING");
/*
* Complete CREATE MATERIALIZED VIEW <name> USING with list of access
* methods
*/
- else if (Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny, "USING"))
+ else if (Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny, "USING") ||
+ Matches("CREATE", "UNLOGGED", "MATERIALIZED", "VIEW", MatchAny, "USING"))
COMPLETE_WITH_QUERY(Query_for_list_of_table_access_methods);
/* Complete CREATE MATERIALIZED VIEW <name> USING <access method> with AS */
- else if (Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny, "USING", MatchAny))
+ else if (Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny, "USING", MatchAny) ||
+ Matches("CREATE", "UNLOGGED", "MATERIALIZED", "VIEW", MatchAny, "USING", MatchAny))
COMPLETE_WITH("AS");
/*
@@ -4211,7 +4216,9 @@ match_previous_words(int pattern_id,
* with "SELECT"
*/
else if (Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny, "AS") ||
- Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny, "USING", MatchAny, "AS"))
+ Matches("CREATE", "MATERIALIZED", "VIEW", MatchAny, "USING", MatchAny, "AS") ||
+ Matches("CREATE", "UNLOGGED", "MATERIALIZED", "VIEW", MatchAny, "AS") ||
+ Matches("CREATE", "UNLOGGED", "MATERIALIZED", "VIEW", MatchAny, "USING", MatchAny, "AS"))
COMPLETE_WITH("SELECT");
/* CREATE EVENT TRIGGER */
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index cb3df6ed895..1c4a3bc5d9c 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -70,6 +70,8 @@ tests += {
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
't/061_recovery_target_prefetch.pl',
+ 't/062_unlogged_matview.pl',
+ 't/063_unlogged_matview_standby.pl',
],
},
}
diff --git a/src/test/recovery/t/062_unlogged_matview.pl b/src/test/recovery/t/062_unlogged_matview.pl
new file mode 100644
index 00000000000..7714e709aeb
--- /dev/null
+++ b/src/test/recovery/t/062_unlogged_matview.pl
@@ -0,0 +1,150 @@
+# Copyright (c) 2021-2026, PostgreSQL Global Development Group
+
+# Tests the crash-recovery contract for UNLOGGED MATERIALIZED VIEWs.
+#
+# An unlogged matview's pg_class.relpopulated carries an epoch stamp: the end
+# of WAL at the last reset of unlogged relations before it was populated.
+# Crash recovery starts a new epoch at its own end of WAL, so after a crash
+# the stale stamp reads as unpopulated at scan time, with no catalog repair
+# needed. A clean restart leaves the epoch unchanged, so contents survive.
+# A logged matview is unaffected by a crash. REFRESH stamps the current
+# epoch and restores the contents.
+
+use strict;
+use warnings FATAL => 'all';
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+my $node = PostgreSQL::Test::Cluster->new('umv');
+$node->init;
+$node->start;
+
+# mv_conv is converted to LOGGED after the crash below.
+$node->safe_psql('postgres', <<'SQL');
+CREATE UNLOGGED MATERIALIZED VIEW mv_u AS SELECT 42 AS x;
+CREATE UNLOGGED MATERIALIZED VIEW mv_conv AS SELECT 7 AS x;
+CREATE MATERIALIZED VIEW mv_p AS SELECT 43 AS x;
+SQL
+
+is($node->safe_psql('postgres', 'SELECT count(*) FROM mv_u'),
+ '1', 'unlogged matview is scannable after creation');
+is( $node->safe_psql(
+ 'postgres', q{SELECT pg_matview_is_populated('mv_u'::regclass)}),
+ 't',
+ 'unlogged matview reports populated after creation');
+
+# --- Clean restart preserves contents -----------------------------------------
+#
+# A clean shutdown does not reset unlogged relations or start a new epoch, so
+# the epoch stamp is still current and the data survives.
+
+$node->restart;
+
+is($node->safe_psql('postgres', 'SELECT count(*) FROM mv_u'),
+ '1', 'unlogged matview contents preserved across a clean restart');
+
+# --- Crash makes the epoch stamp stale ----------------------------------------
+#
+# Crash recovery starts a new epoch, so the stamp written at population time
+# no longer matches the current epoch. Reads treat the matview as
+# unpopulated without any catalog write.
+
+$node->stop('immediate');
+$node->start;
+
+my ($rc, $out, $err) =
+ $node->psql('postgres', 'SELECT count(*) FROM mv_u');
+isnt($rc, 0, 'SELECT on crash-stale unlogged matview fails');
+like(
+ $err,
+ qr/has not been populated/,
+ 'crash-stale unlogged matview reports "has not been populated"');
+is( $node->safe_psql(
+ 'postgres', q{SELECT pg_matview_is_populated('mv_u'::regclass)}),
+ 'f',
+ 'pg_matview_is_populated is false for crash-stale unlogged matview');
+is( $node->safe_psql(
+ 'postgres',
+ q{SELECT ispopulated FROM pg_matviews WHERE matviewname = 'mv_u'}),
+ 'f',
+ 'pg_matviews.ispopulated is false for crash-stale unlogged matview');
+
+# The logged matview is unaffected by the crash.
+is($node->safe_psql('postgres', 'SELECT count(*) FROM mv_p'),
+ '1', 'logged matview still returns rows after crash');
+
+# ALTER MATERIALIZED VIEW ... SET LOGGED must not launder a stale epoch stamp
+# into an eternally-populated state: the unlogged storage was reset by the
+# crash, so the converted matview must read as unpopulated until REFRESH.
+$node->safe_psql('postgres', 'ALTER MATERIALIZED VIEW mv_conv SET LOGGED');
+is( $node->safe_psql(
+ 'postgres',
+ q{SELECT relpersistence FROM pg_class WHERE oid = 'mv_conv'::regclass}
+ ),
+ 'p',
+ 'crash-stale unlogged matview converted to LOGGED');
+($rc, $out, $err) = $node->psql('postgres', 'SELECT count(*) FROM mv_conv');
+like(
+ $err,
+ qr/has not been populated/,
+ 'stale stamp converted to "not populated", not to eternally-populated');
+
+# WITH NO DATA clears the stale stamp, so pg_dump no longer sees it as
+# meant to be populated.
+$node->safe_psql('postgres', 'REFRESH MATERIALIZED VIEW mv_u WITH NO DATA');
+is( $node->safe_psql(
+ 'postgres',
+ q{SELECT relpopulated FROM pg_class WHERE oid = 'mv_u'::regclass}),
+ '0',
+ 'REFRESH WITH NO DATA clears a stale stamp');
+
+# REFRESH stamps the current epoch and restores the contents.
+$node->safe_psql('postgres', 'REFRESH MATERIALIZED VIEW mv_u');
+$node->safe_psql('postgres', 'REFRESH MATERIALIZED VIEW mv_conv');
+is($node->safe_psql('postgres', 'SELECT count(*) FROM mv_u'),
+ '1', 'REFRESH restores the unlogged matview after crash');
+is( $node->safe_psql(
+ 'postgres', q{SELECT pg_matview_is_populated('mv_u'::regclass)}),
+ 't',
+ 'unlogged matview reports populated again after REFRESH');
+is($node->safe_psql('postgres', 'SELECT count(*) FROM mv_conv'),
+ '1', 'REFRESH restores the converted matview');
+
+# --- pg_resetwal after a clean shutdown keeps the contents --------------------
+#
+# Resetting the WAL of a cleanly shut down cluster does not touch unlogged
+# storage, and the next startup does not run crash recovery, so the epoch
+# stamp must stay current. pg_upgrade relies on this: it resets the WAL of
+# the new cluster after restoring the schema, and the transferred unlogged
+# matview heaps have to remain usable.
+
+$node->stop;
+
+$node->command_ok([ 'pg_resetwal', '-D', $node->data_dir ],
+ 'pg_resetwal on a cleanly shut down cluster');
+
+$node->start;
+
+is($node->safe_psql('postgres', 'SELECT count(*) FROM mv_u'),
+ '1', 'unlogged matview survives pg_resetwal after a clean shutdown');
+
+# --- pg_resetwal after an unclean shutdown discards the contents --------------
+#
+# Here the unlogged storage is torn and nothing will reset it later, so the
+# epoch has to move and the matview must read as unpopulated.
+
+$node->stop('immediate');
+
+$node->command_ok([ 'pg_resetwal', '-f', '-D', $node->data_dir ],
+ 'pg_resetwal -f on an uncleanly shut down cluster');
+
+$node->start;
+
+($rc, $out, $err) = $node->psql('postgres', 'SELECT count(*) FROM mv_u');
+like(
+ $err,
+ qr/has not been populated/,
+ 'unlogged matview unpopulated after pg_resetwal -f on a dirty cluster');
+
+done_testing();
diff --git a/src/test/recovery/t/063_unlogged_matview_standby.pl b/src/test/recovery/t/063_unlogged_matview_standby.pl
new file mode 100644
index 00000000000..c9db8530a91
--- /dev/null
+++ b/src/test/recovery/t/063_unlogged_matview_standby.pl
@@ -0,0 +1,192 @@
+# Copyright (c) 2021-2026, PostgreSQL Global Development Group
+
+# Tests UNLOGGED MATERIALIZED VIEWs on a standby, and when it leaves
+# recovery.
+#
+# A standby never has unlogged storage, so an unlogged matview must read as
+# unpopulated there, whatever epoch stamp the primary replicated. Once the
+# standby leaves recovery, its own epoch is past every replicated stamp, so
+# the matview stays unpopulated without any catalog write. Two standbys
+# from one backup leave recovery differently: promotion (new timeline) and
+# restart without standby.signal (same timeline). A session kept open
+# across the promotion must see the change at its next scan.
+
+use strict;
+use warnings FATAL => 'all';
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+# Extract "Unlogged relations reset at" from pg_controldata output.
+sub unlogged_reset_lsn
+{
+ my ($node) = @_;
+ my ($stdout, $stderr) = run_command([ 'pg_controldata', $node->data_dir ]);
+ $stdout =~ /^Unlogged relations reset at:\s+(\S+)\r?$/m
+ or die "no unlogged reset LSN in pg_controldata output";
+ return $1;
+}
+
+# relpopulated of mv_u compared with an LSN: returns "<", "=" or ">".
+sub stamp_vs_lsn
+{
+ my ($node, $lsn) = @_;
+ return $node->safe_psql(
+ 'postgres', qq{
+ SELECT CASE sign(relpopulated - ('$lsn'::pg_lsn - '0/0'))
+ WHEN -1 THEN '<' WHEN 0 THEN '=' ELSE '>' END
+ FROM pg_class WHERE relname = 'mv_u'});
+}
+
+my $node_primary = PostgreSQL::Test::Cluster->new('primary');
+$node_primary->init(allows_streaming => 1);
+$node_primary->start;
+
+$node_primary->safe_psql('postgres', <<'SQL');
+CREATE UNLOGGED MATERIALIZED VIEW mv_u AS SELECT 42 AS x;
+CREATE MATERIALIZED VIEW mv_p AS SELECT 42 AS x;
+SQL
+
+# --- Two standbys from the same backup --------------------------------------
+
+$node_primary->backup('bkp');
+
+my $node_standby = PostgreSQL::Test::Cluster->new('standby');
+$node_standby->init_from_backup($node_primary, 'bkp', has_streaming => 1);
+$node_standby->start;
+
+my $node_standby2 = PostgreSQL::Test::Cluster->new('standby2');
+$node_standby2->init_from_backup($node_primary, 'bkp', has_streaming => 1);
+$node_standby2->start;
+
+# --- Primary crash and a fresh stamp ------------------------------------------
+
+$node_primary->stop('immediate');
+$node_primary->start;
+
+my $reset_primary = unlogged_reset_lsn($node_primary);
+
+# Repopulate, and let the new stamp replicate to both standbys, whose own
+# pg_control still carries the epoch from the backup.
+$node_primary->safe_psql('postgres', 'REFRESH MATERIALIZED VIEW mv_u');
+$node_primary->wait_for_catchup($node_standby);
+$node_primary->wait_for_catchup($node_standby2);
+
+is(stamp_vs_lsn($node_standby, $reset_primary),
+ '=', 'standby replicated the primary\'s post-crash epoch stamp');
+
+# --- In recovery, the unlogged matview is unpopulated -------------------------
+
+is($node_standby->safe_psql('postgres', 'SELECT count(*) FROM mv_p'),
+ '1', 'logged matview is scannable on the standby');
+
+my ($rc, $out, $err) =
+ $node_standby->psql('postgres', 'SELECT count(*) FROM mv_u');
+isnt($rc, 0, 'SELECT on unlogged matview fails on standby');
+like(
+ $err,
+ qr/cannot access temporary or unlogged relations during recovery/,
+ 'unlogged matview reports the generic unlogged-relation error on standby'
+);
+
+($rc, $out, $err) = $node_standby->psql('postgres', 'COPY mv_u TO stdout');
+like(
+ $err,
+ qr/cannot access temporary or unlogged relations during recovery/,
+ 'COPY from unlogged matview reports the generic error on standby');
+
+# pg_matview_is_populated() is per node: false on the standby while the very
+# same stamp reads true on the primary.
+is( $node_standby->safe_psql(
+ 'postgres', q{SELECT pg_matview_is_populated('mv_u'::regclass)}),
+ 'f',
+ 'pg_matview_is_populated is false for unlogged matview on standby');
+is( $node_primary->safe_psql(
+ 'postgres', q{SELECT pg_matview_is_populated('mv_u'::regclass)}),
+ 't',
+ 'pg_matview_is_populated is true for unlogged matview on primary');
+is( $node_standby->safe_psql(
+ 'postgres',
+ q{SELECT ispopulated FROM pg_matviews WHERE matviewname = 'mv_u'}),
+ 'f',
+ 'pg_matviews.ispopulated is false for unlogged matview on standby');
+
+# --- A session that will survive the promotion --------------------------------
+
+my $bg = $node_standby->background_psql('postgres', on_error_stop => 0);
+
+my ($bg_out, $bg_err) = $bg->query('SELECT count(*) FROM mv_u');
+is($bg_err, 1, 'surviving session: unlogged matview errors on the standby');
+$bg->{stderr} = '';
+
+# --- Promote ------------------------------------------------------------------
+
+$node_standby->promote;
+$node_standby->poll_query_until('postgres', 'SELECT NOT pg_is_in_recovery()')
+ or die "standby never left recovery after promotion";
+
+# The session predates the promotion, so no connect-time repair could have
+# run for it. If the epoch check were not recomputed at scan time, the
+# SELECT would silently return a zero count over the empty, never-replicated
+# storage.
+is($bg->query_safe('SELECT pg_is_in_recovery()'),
+ 'f', 'surviving session survived the promotion');
+
+($bg_out, $bg_err) = $bg->query('SELECT count(*) FROM mv_u');
+is($bg_err, 1,
+ 'surviving session: SELECT on unlogged matview errors after promotion');
+is($bg_out, '', 'surviving session: SELECT returned no rows at all');
+like(
+ $bg->{stderr},
+ qr/has not been populated/,
+ 'surviving session: promoted node reports "has not been populated"');
+$bg->{stderr} = '';
+
+# A new connection agrees, and the promoted node reset unlogged relations
+# past the replicated stamp.
+is( $node_standby->safe_psql(
+ 'postgres', q{SELECT pg_matview_is_populated('mv_u'::regclass)}),
+ 'f',
+ 'pg_matview_is_populated is false on the promoted node');
+my $reset_promoted = unlogged_reset_lsn($node_standby);
+is(stamp_vs_lsn($node_standby, $reset_promoted),
+ '<', 'replicated stamp is below the promoted node\'s epoch');
+
+# REFRESH on the promoted node restores the matview.
+$bg->query_safe('REFRESH MATERIALIZED VIEW mv_u');
+is($bg->query_safe('SELECT count(*) FROM mv_u'),
+ '1', 'surviving session: REFRESH restored the matview');
+is(stamp_vs_lsn($node_standby, $reset_promoted),
+ '=', 'post-promotion REFRESH stamped the promoted node\'s epoch');
+
+$bg->quit;
+
+# --- Leaving recovery without promotion ---------------------------------------
+#
+# Restart the second standby without standby.signal. That runs plain crash
+# recovery, which keeps timeline 1, yet the stamp it replicated from the
+# primary must still read as unpopulated: the standby has no data for it.
+
+$node_standby2->stop;
+unlink($node_standby2->data_dir . '/standby.signal')
+ or die "could not remove standby.signal: $!";
+$node_standby2->start;
+
+is( $node_standby2->safe_psql(
+ 'postgres', 'SELECT timeline_id FROM pg_control_checkpoint()'),
+ '1', 'second standby left recovery on timeline 1');
+is(stamp_vs_lsn($node_standby2, unlogged_reset_lsn($node_standby2)),
+ '<', 'replicated stamp is below the second standby\'s epoch');
+
+($rc, $out, $err) =
+ $node_standby2->psql('postgres', 'SELECT count(*) FROM mv_u');
+like(
+ $err,
+ qr/has not been populated/,
+ 'second standby reports "has not been populated"');
+
+$node_standby2->stop;
+$node_standby->stop;
+$node_primary->stop;
+
+done_testing();
diff --git a/src/test/regress/expected/matview.out b/src/test/regress/expected/matview.out
index 7500bf027da..f9c6c8ea56d 100644
--- a/src/test/regress/expected/matview.out
+++ b/src/test/regress/expected/matview.out
@@ -325,6 +325,244 @@ SELECT type, m.totamt AS mtot, v.totamt AS vtot FROM mvtest_tm m LEFT JOIN mvtes
z | 24 | 24
(3 rows)
+-- unlogged materialized view: storage is unlogged, REFRESH/SELECT work.
+-- The data is not WAL-logged (relpersistence 'u'); crash semantics that mark
+-- the matview unpopulated after a crash are handled separately.
+CREATE UNLOGGED MATERIALIZED VIEW mvtest_unlogged AS
+ SELECT type, sum(amt) AS totamt FROM mvtest_t GROUP BY type;
+SELECT relpersistence FROM pg_class WHERE oid = 'mvtest_unlogged'::regclass;
+ relpersistence
+----------------
+ u
+(1 row)
+
+SELECT pg_matview_is_populated('mvtest_unlogged'::regclass);
+ pg_matview_is_populated
+-------------------------
+ t
+(1 row)
+
+\d mvtest_unlogged
+Unlogged materialized view "public.mvtest_unlogged"
+ Column | Type | Collation | Nullable | Default
+--------+---------+-----------+----------+---------
+ type | text | | |
+ totamt | numeric | | |
+
+-- the matview's toast table is unlogged too
+SELECT t.relpersistence FROM pg_class c JOIN pg_class t ON c.reltoastrelid = t.oid
+ WHERE c.oid = 'mvtest_unlogged'::regclass;
+ relpersistence
+----------------
+ u
+(1 row)
+
+SELECT * FROM mvtest_unlogged ORDER BY type;
+ type | totamt
+------+--------
+ x | 5
+ y | 12
+ z | 24
+(3 rows)
+
+-- an index on an unlogged matview is unlogged as well
+CREATE UNIQUE INDEX mvtest_unlogged_type ON mvtest_unlogged (type);
+SELECT relpersistence FROM pg_class WHERE oid = 'mvtest_unlogged_type'::regclass;
+ relpersistence
+----------------
+ u
+(1 row)
+
+-- REFRESH still works and leaves the data intact
+REFRESH MATERIALIZED VIEW mvtest_unlogged;
+SELECT * FROM mvtest_unlogged ORDER BY type;
+ type | totamt
+------+--------
+ x | 5
+ y | 12
+ z | 24
+(3 rows)
+
+-- REFRESH CONCURRENTLY works too, and keeps the existing epoch stamp
+SELECT relpopulated AS mvtest_unlogged_stamp FROM pg_class
+ WHERE oid = 'mvtest_unlogged'::regclass \gset
+REFRESH MATERIALIZED VIEW CONCURRENTLY mvtest_unlogged;
+SELECT relpopulated = :mvtest_unlogged_stamp AS stamp_kept FROM pg_class
+ WHERE oid = 'mvtest_unlogged'::regclass;
+ stamp_kept
+------------
+ t
+(1 row)
+
+SELECT pg_matview_is_populated('mvtest_unlogged'::regclass);
+ pg_matview_is_populated
+-------------------------
+ t
+(1 row)
+
+SELECT * FROM mvtest_unlogged ORDER BY type;
+ type | totamt
+------+--------
+ x | 5
+ y | 12
+ z | 24
+(3 rows)
+
+DROP MATERIALIZED VIEW mvtest_unlogged;
+-- ALTER MATERIALIZED VIEW ... SET {LOGGED|UNLOGGED} rewrites persistence
+-- of the matview, its toast table and its indexes, preserving data.
+CREATE MATERIALIZED VIEW mvtest_setlog AS
+ SELECT type, sum(amt) AS totamt FROM mvtest_t GROUP BY type;
+CREATE UNIQUE INDEX mvtest_setlog_type ON mvtest_setlog (type);
+SELECT relpersistence FROM pg_class WHERE oid = 'mvtest_setlog'::regclass; -- p
+ relpersistence
+----------------
+ p
+(1 row)
+
+SELECT count(*) FROM mvtest_setlog;
+ count
+-------
+ 3
+(1 row)
+
+ALTER MATERIALIZED VIEW mvtest_setlog SET UNLOGGED;
+SELECT relpersistence FROM pg_class WHERE oid = 'mvtest_setlog'::regclass; -- u
+ relpersistence
+----------------
+ u
+(1 row)
+
+SELECT relpersistence FROM pg_class
+ WHERE oid = (SELECT reltoastrelid FROM pg_class WHERE oid = 'mvtest_setlog'::regclass); -- u
+ relpersistence
+----------------
+ u
+(1 row)
+
+SELECT relpersistence FROM pg_class WHERE oid = 'mvtest_setlog_type'::regclass; -- u
+ relpersistence
+----------------
+ u
+(1 row)
+
+SELECT pg_matview_is_populated('mvtest_setlog'::regclass); -- t
+ pg_matview_is_populated
+-------------------------
+ t
+(1 row)
+
+SELECT count(*) FROM mvtest_setlog;
+ count
+-------
+ 3
+(1 row)
+
+ALTER MATERIALIZED VIEW mvtest_setlog SET LOGGED;
+SELECT relpersistence FROM pg_class WHERE oid = 'mvtest_setlog'::regclass; -- p
+ relpersistence
+----------------
+ p
+(1 row)
+
+SELECT relpersistence FROM pg_class WHERE oid = 'mvtest_setlog_type'::regclass; -- p
+ relpersistence
+----------------
+ p
+(1 row)
+
+SELECT pg_matview_is_populated('mvtest_setlog'::regclass); -- t
+ pg_matview_is_populated
+-------------------------
+ t
+(1 row)
+
+SELECT count(*) FROM mvtest_setlog;
+ count
+-------
+ 3
+(1 row)
+
+-- cannot change persistence setting twice in one ALTER
+ALTER MATERIALIZED VIEW mvtest_setlog SET UNLOGGED, SET LOGGED;
+ERROR: cannot change persistence setting twice
+DROP MATERIALIZED VIEW mvtest_setlog;
+-- ALTER MATERIALIZED VIEW SET LOGGED / SET UNLOGGED converts the populated state
+CREATE UNLOGGED MATERIALIZED VIEW mvtest_persist AS SELECT 1 AS a;
+SELECT pg_matview_is_populated('mvtest_persist'::regclass);
+ pg_matview_is_populated
+-------------------------
+ t
+(1 row)
+
+ALTER MATERIALIZED VIEW mvtest_persist SET LOGGED;
+SELECT relpersistence FROM pg_class WHERE oid = 'mvtest_persist'::regclass;
+ relpersistence
+----------------
+ p
+(1 row)
+
+SELECT relpopulated FROM pg_class WHERE oid = 'mvtest_persist'::regclass; -- 1: eternal
+ relpopulated
+--------------
+ 1
+(1 row)
+
+SELECT * FROM mvtest_persist;
+ a
+---
+ 1
+(1 row)
+
+ALTER MATERIALIZED VIEW mvtest_persist SET UNLOGGED;
+SELECT relpersistence FROM pg_class WHERE oid = 'mvtest_persist'::regclass;
+ relpersistence
+----------------
+ u
+(1 row)
+
+SELECT relpopulated > 1 OR relpopulated < 0 AS is_epoch_stamp FROM pg_class WHERE oid = 'mvtest_persist'::regclass;
+ is_epoch_stamp
+----------------
+ t
+(1 row)
+
+SELECT pg_matview_is_populated('mvtest_persist'::regclass);
+ pg_matview_is_populated
+-------------------------
+ t
+(1 row)
+
+SELECT * FROM mvtest_persist;
+ a
+---
+ 1
+(1 row)
+
+DROP MATERIALIZED VIEW mvtest_persist;
+-- SET UNLOGGED on an unpopulated matview keeps it unpopulated
+CREATE MATERIALIZED VIEW mvtest_nodata AS SELECT 1 AS a WITH NO DATA;
+ALTER MATERIALIZED VIEW mvtest_nodata SET UNLOGGED;
+SELECT relpopulated FROM pg_class WHERE oid = 'mvtest_nodata'::regclass; -- 0: none
+ relpopulated
+--------------
+ 0
+(1 row)
+
+SELECT pg_matview_is_populated('mvtest_nodata'::regclass);
+ pg_matview_is_populated
+-------------------------
+ f
+(1 row)
+
+REFRESH MATERIALIZED VIEW mvtest_nodata;
+SELECT pg_matview_is_populated('mvtest_nodata'::regclass);
+ pg_matview_is_populated
+-------------------------
+ t
+(1 row)
+
+DROP MATERIALIZED VIEW mvtest_nodata;
-- make sure that dependencies are reported properly when they block the drop
DROP TABLE mvtest_t;
ERROR: cannot drop table mvtest_t because other objects depend on it
diff --git a/src/test/regress/sql/matview.sql b/src/test/regress/sql/matview.sql
index 8890a2f7932..11b1cd52a1b 100644
--- a/src/test/regress/sql/matview.sql
+++ b/src/test/regress/sql/matview.sql
@@ -108,6 +108,80 @@ CREATE MATERIALIZED VIEW mvtest_temp_tm AS SELECT * FROM mvtest_temp_t;
-- test join of mv and view
SELECT type, m.totamt AS mtot, v.totamt AS vtot FROM mvtest_tm m LEFT JOIN mvtest_tv v USING (type) ORDER BY type;
+-- unlogged materialized view: storage is unlogged, REFRESH/SELECT work.
+-- The data is not WAL-logged (relpersistence 'u'); crash semantics that mark
+-- the matview unpopulated after a crash are handled separately.
+CREATE UNLOGGED MATERIALIZED VIEW mvtest_unlogged AS
+ SELECT type, sum(amt) AS totamt FROM mvtest_t GROUP BY type;
+SELECT relpersistence FROM pg_class WHERE oid = 'mvtest_unlogged'::regclass;
+SELECT pg_matview_is_populated('mvtest_unlogged'::regclass);
+\d mvtest_unlogged
+-- the matview's toast table is unlogged too
+SELECT t.relpersistence FROM pg_class c JOIN pg_class t ON c.reltoastrelid = t.oid
+ WHERE c.oid = 'mvtest_unlogged'::regclass;
+SELECT * FROM mvtest_unlogged ORDER BY type;
+-- an index on an unlogged matview is unlogged as well
+CREATE UNIQUE INDEX mvtest_unlogged_type ON mvtest_unlogged (type);
+SELECT relpersistence FROM pg_class WHERE oid = 'mvtest_unlogged_type'::regclass;
+-- REFRESH still works and leaves the data intact
+REFRESH MATERIALIZED VIEW mvtest_unlogged;
+SELECT * FROM mvtest_unlogged ORDER BY type;
+-- REFRESH CONCURRENTLY works too, and keeps the existing epoch stamp
+SELECT relpopulated AS mvtest_unlogged_stamp FROM pg_class
+ WHERE oid = 'mvtest_unlogged'::regclass \gset
+REFRESH MATERIALIZED VIEW CONCURRENTLY mvtest_unlogged;
+SELECT relpopulated = :mvtest_unlogged_stamp AS stamp_kept FROM pg_class
+ WHERE oid = 'mvtest_unlogged'::regclass;
+SELECT pg_matview_is_populated('mvtest_unlogged'::regclass);
+SELECT * FROM mvtest_unlogged ORDER BY type;
+DROP MATERIALIZED VIEW mvtest_unlogged;
+
+-- ALTER MATERIALIZED VIEW ... SET {LOGGED|UNLOGGED} rewrites persistence
+-- of the matview, its toast table and its indexes, preserving data.
+CREATE MATERIALIZED VIEW mvtest_setlog AS
+ SELECT type, sum(amt) AS totamt FROM mvtest_t GROUP BY type;
+CREATE UNIQUE INDEX mvtest_setlog_type ON mvtest_setlog (type);
+SELECT relpersistence FROM pg_class WHERE oid = 'mvtest_setlog'::regclass; -- p
+SELECT count(*) FROM mvtest_setlog;
+ALTER MATERIALIZED VIEW mvtest_setlog SET UNLOGGED;
+SELECT relpersistence FROM pg_class WHERE oid = 'mvtest_setlog'::regclass; -- u
+SELECT relpersistence FROM pg_class
+ WHERE oid = (SELECT reltoastrelid FROM pg_class WHERE oid = 'mvtest_setlog'::regclass); -- u
+SELECT relpersistence FROM pg_class WHERE oid = 'mvtest_setlog_type'::regclass; -- u
+SELECT pg_matview_is_populated('mvtest_setlog'::regclass); -- t
+SELECT count(*) FROM mvtest_setlog;
+ALTER MATERIALIZED VIEW mvtest_setlog SET LOGGED;
+SELECT relpersistence FROM pg_class WHERE oid = 'mvtest_setlog'::regclass; -- p
+SELECT relpersistence FROM pg_class WHERE oid = 'mvtest_setlog_type'::regclass; -- p
+SELECT pg_matview_is_populated('mvtest_setlog'::regclass); -- t
+SELECT count(*) FROM mvtest_setlog;
+-- cannot change persistence setting twice in one ALTER
+ALTER MATERIALIZED VIEW mvtest_setlog SET UNLOGGED, SET LOGGED;
+DROP MATERIALIZED VIEW mvtest_setlog;
+
+-- ALTER MATERIALIZED VIEW SET LOGGED / SET UNLOGGED converts the populated state
+CREATE UNLOGGED MATERIALIZED VIEW mvtest_persist AS SELECT 1 AS a;
+SELECT pg_matview_is_populated('mvtest_persist'::regclass);
+ALTER MATERIALIZED VIEW mvtest_persist SET LOGGED;
+SELECT relpersistence FROM pg_class WHERE oid = 'mvtest_persist'::regclass;
+SELECT relpopulated FROM pg_class WHERE oid = 'mvtest_persist'::regclass; -- 1: eternal
+SELECT * FROM mvtest_persist;
+ALTER MATERIALIZED VIEW mvtest_persist SET UNLOGGED;
+SELECT relpersistence FROM pg_class WHERE oid = 'mvtest_persist'::regclass;
+SELECT relpopulated > 1 OR relpopulated < 0 AS is_epoch_stamp FROM pg_class WHERE oid = 'mvtest_persist'::regclass;
+SELECT pg_matview_is_populated('mvtest_persist'::regclass);
+SELECT * FROM mvtest_persist;
+DROP MATERIALIZED VIEW mvtest_persist;
+
+-- SET UNLOGGED on an unpopulated matview keeps it unpopulated
+CREATE MATERIALIZED VIEW mvtest_nodata AS SELECT 1 AS a WITH NO DATA;
+ALTER MATERIALIZED VIEW mvtest_nodata SET UNLOGGED;
+SELECT relpopulated FROM pg_class WHERE oid = 'mvtest_nodata'::regclass; -- 0: none
+SELECT pg_matview_is_populated('mvtest_nodata'::regclass);
+REFRESH MATERIALIZED VIEW mvtest_nodata;
+SELECT pg_matview_is_populated('mvtest_nodata'::regclass);
+DROP MATERIALIZED VIEW mvtest_nodata;
+
-- make sure that dependencies are reported properly when they block the drop
DROP TABLE mvtest_t;
--
2.56.1