/*-------------------------------------------------------------------------
|
* cfs_sql.c
|
* Compressed File Store (CFS) — SQL interface functions.
|
*
|
* Implements the user-facing observability and administration functions
|
* declared in cfs_sql.h:
|
*
|
* * pg_cfs_relation_info, pg_cfs_relation_size, pg_cfs_check,
|
* pg_cfs_reset_stats, pg_cfs_estimate_compression — diagnostics.
|
* * pg_stat_get_cfs / pg_get_cfs_settings — SRFs backing the views.
|
* * pg_cfs_bgworker_pause / _resume / _status — bgworker control.
|
*
|
* Design notes
|
* ------------
|
* * Every function compiles even with USE_CFS undefined; the !USE_CFS path
|
* raises ERRCODE_FEATURE_NOT_SUPPORTED so that pg_proc.dat always resolves
|
* the symbol.
|
* * Informational functions on non-CFS relations never ERROR: they return
|
* is_cfs=false with zeroed CFS-specific fields.
|
* * Sizes are computed from the on-disk sidecar files; logical_size comes
|
* from the relation's current block count.
|
*
|
* Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group
|
*
|
* IDENTIFICATION
|
* src/backend/storage/cfs/cfs_sql.c
|
*
|
*-------------------------------------------------------------------------
|
*/
|
#include "postgres.h"
|
|
#include <math.h>
|
#include <sys/stat.h>
|
|
#include "access/heapam.h"
|
#include "access/relation.h"
|
#include "access/table.h"
|
#include "catalog/pg_class.h"
|
#include "catalog/pg_tablespace_d.h"
|
#include "common/relpath.h"
|
#include "funcapi.h"
|
#include "miscadmin.h"
|
#include "storage/bufmgr.h"
|
#include "storage/bufpage.h"
|
#include "storage/cfs/cfs_sql.h"
|
#include "storage/cfs/cfs_smgr.h"
|
#include "utils/builtins.h"
|
#include "utils/lsyscache.h"
|
#include "utils/rel.h"
|
#include "utils/snapmgr.h"
|
#include "utils/syscache.h"
|
|
#include "storage/cfs/cfs.h"
|
#include "storage/cfs/cfs_compress.h"
|
#include "storage/cfs/cfs_fsck.h"
|
#include "storage/cfs/cfs_guc.h"
|
#include "storage/cfs/cfs_path.h"
|
#include "storage/cfs/cfs_rel.h"
|
#include "storage/cfs/cfs_shmem.h"
|
#include "utils/timestamp.h"
|
#include "utils/tuplestore.h"
|
|
/* ----------------------------------------------------------------
|
* Helpers shared by several functions
|
* ---------------------------------------------------------------- */
|
|
#ifdef USE_CFS
|
|
/*
|
* cfs_sql_supported_relation
|
* Decide whether a relation is *eligible* for CFS at all. This is used
|
* by the views to flag is_supported and by estimate_compression to
|
* reject TEMP / UNLOGGED / non-stored relations.
|
*
|
* A relation is supported when it is permanent and either has physical
|
* storage or is a partitioned table (which can hold a default policy).
|
*/
|
static bool
|
cfs_sql_supported_relation(Form_pg_class classform)
|
{
|
if (classform->relpersistence != RELPERSISTENCE_PERMANENT)
|
return false;
|
if (RELKIND_HAS_STORAGE(classform->relkind))
|
return true;
|
if (classform->relkind == RELKIND_PARTITIONED_TABLE)
|
return true;
|
return false;
|
}
|
|
/*
|
* cfs_sql_relkind_flags
|
* Fill the boolean classification flags (is_toast, is_index,
|
* is_partitioned_root) from a pg_class tuple.
|
*/
|
static void
|
cfs_sql_relkind_flags(Form_pg_class classform,
|
bool *is_toast, bool *is_index,
|
bool *is_partitioned_root)
|
{
|
*is_toast = (classform->relkind == RELKIND_TOASTVALUE);
|
*is_index = (classform->relkind == RELKIND_INDEX ||
|
classform->relkind == RELKIND_PARTITIONED_INDEX);
|
*is_partitioned_root = (classform->relkind == RELKIND_PARTITIONED_TABLE);
|
}
|
|
/*
|
* cfs_sql_physical_size
|
* Sum of the three sidecar files (.cfp + .cfsmap + .cfsjrn) for a
|
* relation, including every .cfp segment. Returns 0 for relations
|
* without CFS sidecars.
|
*/
|
static int64
|
cfs_sql_physical_size(RelFileLocatorBackend rlocator)
|
{
|
int64 total = 0;
|
|
total += cfs_segmented_sidecar_size(rlocator, MAIN_FORKNUM, CFS_FILE_DATA);
|
total += cfs_segmented_sidecar_size(rlocator, MAIN_FORKNUM, CFS_FILE_MAP);
|
total += cfs_segmented_sidecar_size(rlocator, MAIN_FORKNUM, CFS_FILE_JOURNAL);
|
|
return total;
|
}
|
|
/* Text form of an algorithm value (NULL for RAW / "not CFS"). */
|
static Datum
|
cfs_sql_algorithm_text(CfsAlgorithm algo)
|
{
|
if (algo == CFS_ALGORITHM_RAW)
|
return (Datum) 0; /* NULL via the caller's nulls[] entry */
|
return CStringGetTextDatum(CfsAlgorithmGetName(algo));
|
}
|
|
#endif /* USE_CFS */
|
|
/* ================================================================
|
* pg_cfs_relation_info(regclass)
|
*
|
* Returns a single row describing the effective CFS policy and the
|
* relation classification.
|
* ================================================================ */
|
Datum
|
pg_cfs_relation_info(PG_FUNCTION_ARGS)
|
{
|
#ifdef USE_CFS
|
Oid reloid = PG_GETARG_OID(0);
|
Relation rel;
|
CfsEffectiveOptions opts;
|
Oid nspoid;
|
NameData relname_buf;
|
char relkind;
|
bool is_toast,
|
is_index,
|
is_partitioned_root,
|
is_supported;
|
bool has_default_policy = false;
|
Datum values[14];
|
bool nulls[14];
|
TupleDesc tupdesc;
|
HeapTuple htup;
|
|
/* A NULL or invalid regclass is a user error. */
|
if (reloid == InvalidOid)
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("relation OID must not be zero")));
|
|
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
|
elog(ERROR, "return type must be a row type");
|
|
rel = relation_open(reloid, AccessShareLock);
|
|
/*
|
* Snapshot the scalar fields we need BEFORE any later call that could
|
* invalidate the relcache entry (CfsEffectiveOptionsFromRelation for a
|
* TOAST relation opens its owning table; get_namespace_name does a
|
* syscache lookup that may flush the relcache). Reading rel->rd_rel
|
* after such a call would touch freed memory.
|
*/
|
nspoid = rel->rd_rel->relnamespace;
|
relname_buf = rel->rd_rel->relname;
|
relkind = rel->rd_rel->relkind;
|
cfs_sql_relkind_flags(rel->rd_rel, &is_toast, &is_index, &is_partitioned_root);
|
is_supported = cfs_sql_supported_relation(rel->rd_rel);
|
|
/*
|
* Only resolve effective options for relations that are CFS-eligible
|
* (permanent heap / matview / TOAST / partitioned table). For anything
|
* else (views, composite types, foreign tables, sequences) rd_options is
|
* not a StdRdOptions struct, so the resolver must not interpret it as
|
* one; return is_cfs=false with zeroed fields instead.
|
*/
|
if (is_supported)
|
{
|
CfsEffectiveOptionsFromRelation(rel, &opts);
|
|
/*
|
* A partitioned root never stores data itself, but the default policy
|
* configured for its partitions is a first-class configuration
|
* object: read it from the catalog and show its triple. is_cfs in
|
* the row stays false - the root has no storage to compress.
|
*/
|
if (is_partitioned_root)
|
{
|
has_default_policy = CfsPartitionedDefaultPolicy(reloid, &opts);
|
opts.is_cfs = false;
|
}
|
}
|
else
|
{
|
memset(&opts, 0, sizeof(opts));
|
opts.algorithm = CFS_ALGORITHM_RAW;
|
}
|
|
relation_close(rel, AccessShareLock);
|
|
MemSet(nulls, 0, sizeof(nulls));
|
|
{
|
bool show_policy = opts.is_cfs || has_default_policy;
|
|
values[0] = ObjectIdGetDatum(reloid);
|
values[1] = CStringGetTextDatum(get_namespace_name(nspoid));
|
values[2] = CStringGetTextDatum(NameStr(relname_buf));
|
values[3] = CharGetDatum(relkind);
|
values[4] = BoolGetDatum(opts.is_cfs);
|
if (show_policy)
|
values[5] = cfs_sql_algorithm_text(opts.algorithm);
|
else
|
nulls[5] = true;
|
|
/*
|
* Unset policy fields read as NULL: the stored policy is exactly what
|
* was spelled out. The *_effective columns resolve the unset fields
|
* from the session GUCs the same way the write path does; explicitly
|
* set fields show their stored value and do not follow the GUC.
|
*/
|
if (show_policy && opts.level_set)
|
values[6] = Int32GetDatum(opts.level);
|
else
|
nulls[6] = true;
|
if (show_policy && opts.min_gain_bytes_set)
|
values[7] = Int32GetDatum(opts.min_gain_bytes);
|
else
|
nulls[7] = true;
|
if (show_policy)
|
{
|
values[12] = Int32GetDatum(opts.level_set ? opts.level :
|
cfs_default_level_for(opts.algorithm));
|
values[13] = Int32GetDatum(opts.min_gain_bytes_set ? opts.min_gain_bytes :
|
cfs_default_min_gain_bytes);
|
}
|
else
|
{
|
nulls[12] = true;
|
nulls[13] = true;
|
}
|
values[8] = BoolGetDatum(is_toast);
|
values[9] = BoolGetDatum(is_index);
|
values[10] = BoolGetDatum(is_partitioned_root);
|
values[11] = BoolGetDatum(is_supported);
|
}
|
|
htup = heap_form_tuple(tupdesc, values, nulls);
|
PG_RETURN_DATUM(HeapTupleGetDatum(htup));
|
#else
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("unsupported CFS feature"),
|
errdetail("This functionality requires the server to be built with cfs support.")));
|
PG_RETURN_NULL();
|
#endif
|
}
|
|
/* ================================================================
|
* pg_cfs_relation_size(regclass)
|
*
|
* Returns logical_size (bytes the relation represents logically), the
|
* total physical_size of the CFS sidecars, and the per-file sizes.
|
* ================================================================ */
|
Datum
|
pg_cfs_relation_size(PG_FUNCTION_ARGS)
|
{
|
#ifdef USE_CFS
|
Oid reloid = PG_GETARG_OID(0);
|
Relation rel;
|
RelFileLocatorBackend rlocator;
|
Datum values[5];
|
bool nulls[5];
|
TupleDesc tupdesc;
|
HeapTuple htup;
|
int64 logical_size = 0;
|
int64 cfp_size,
|
map_size,
|
jrn_size;
|
|
if (reloid == InvalidOid)
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("relation OID must not be zero")));
|
|
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
|
elog(ERROR, "return type must be a row type");
|
|
rel = relation_open(reloid, AccessShareLock);
|
|
if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
|
{
|
BlockNumber nblocks = RelationGetNumberOfBlocksInFork(rel,
|
MAIN_FORKNUM);
|
|
logical_size = (int64) nblocks * BLCKSZ;
|
}
|
|
rlocator = RelationGetSmgr(rel)->smgr_rlocator;
|
|
cfp_size = cfs_segmented_sidecar_size(rlocator, MAIN_FORKNUM,
|
CFS_FILE_DATA);
|
map_size = cfs_segmented_sidecar_size(rlocator, MAIN_FORKNUM,
|
CFS_FILE_MAP);
|
jrn_size = cfs_segmented_sidecar_size(rlocator, MAIN_FORKNUM,
|
CFS_FILE_JOURNAL);
|
|
relation_close(rel, AccessShareLock);
|
|
MemSet(nulls, 0, sizeof(nulls));
|
values[0] = Int64GetDatum(logical_size);
|
values[1] = Int64GetDatum(cfp_size + map_size + jrn_size);
|
values[2] = Int64GetDatum(cfp_size);
|
values[3] = Int64GetDatum(map_size);
|
values[4] = Int64GetDatum(jrn_size);
|
|
htup = heap_form_tuple(tupdesc, values, nulls);
|
PG_RETURN_DATUM(HeapTupleGetDatum(htup));
|
#else
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("unsupported CFS feature"),
|
errdetail("This functionality requires the server to be built with cfs support.")));
|
PG_RETURN_NULL();
|
#endif
|
}
|
|
/* ================================================================
|
* pg_cfs_check(regclass, deep boolean DEFAULT false)
|
*
|
* Runs the structural integrity checker over the relation's sidecars and
|
* reports whether the relation is OK. A non-CFS relation returns
|
* ok=true, is_cfs=false without ERROR.
|
*
|
* The check takes no write locks, so torn tails left by a concurrent or
|
* crashed writer are reported as a soft status rather than an error; run it
|
* on a quiescent system for a definitive verdict.
|
* ================================================================ */
|
Datum
|
pg_cfs_check(PG_FUNCTION_ARGS)
|
{
|
#ifdef USE_CFS
|
Oid reloid = PG_GETARG_OID(0);
|
bool deep = PG_GETARG_BOOL(1);
|
Relation rel;
|
RelFileLocatorBackend rlocator;
|
CfsEffectiveOptions opts;
|
Datum values[5];
|
bool nulls[5];
|
TupleDesc tupdesc;
|
HeapTuple htup;
|
bool is_cfs;
|
bool has_storage;
|
int errors = 0;
|
StringInfoData msg;
|
|
if (reloid == InvalidOid)
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("relation OID must not be zero")));
|
|
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
|
elog(ERROR, "return type must be a row type");
|
|
rel = relation_open(reloid, AccessShareLock);
|
has_storage = RELKIND_HAS_STORAGE(rel->rd_rel->relkind);
|
|
/*
|
* Resolve the effective CFS policy. For relations without physical
|
* storage (views, composite types, ...) this returns is_cfs=false without
|
* touching rd_options as a StdRdOptions struct. The storage locator is
|
* only needed for the fsck pass below and is fetched there, guarded by
|
* has_storage, because RelationGetSmgr() on a relation without storage
|
* trips an assertion.
|
*/
|
CfsEffectiveOptionsFromRelation(rel, &opts);
|
is_cfs = opts.is_cfs;
|
|
initStringInfo(&msg);
|
|
if (is_cfs && has_storage)
|
{
|
CfsFsckOptions fopts;
|
CfsFsckResult fresult;
|
|
rlocator = RelationGetSmgr(rel)->smgr_rlocator;
|
|
cfs_fsck_result_init(&fresult);
|
|
/*
|
* deep = true reads the .cfp block headers, validates every live
|
* entry's fields, and cross-checks each live map entry against the
|
* record header it points at; deep = false only checks the map and
|
* journal headers and entry CRCs.
|
*/
|
fopts.check_fields = true;
|
fopts.verify_block_headers = deep;
|
fopts.require_files = false;
|
|
errors = cfs_fsck_relation(rlocator, MAIN_FORKNUM, &fopts, &fresult);
|
|
if (errors == 0)
|
{
|
if (fresult.generation_check_degraded)
|
appendStringInfoString(&msg, "ok, generation_check_degraded");
|
else if (fresult.torn_tails > 0)
|
appendStringInfo(&msg,
|
"ok, torn_tails=%llu (expected after crash; verify on a quiescent system)",
|
(unsigned long long) fresult.torn_tails);
|
else if (fresult.generation_violations > 0)
|
appendStringInfo(&msg, "ok, generation_anomalies=%llu",
|
(unsigned long long) fresult.generation_violations);
|
else
|
appendStringInfoString(&msg, "ok");
|
|
/*
|
* A corrupt map row the journal still covers is the expected
|
* artifact of a torn fold pwrite, not damage; report how many the
|
* check healed instead of hiding the artifact entirely.
|
*/
|
if (fresult.healed_entries > 0)
|
appendStringInfo(&msg, ", healed_entries=%llu",
|
(unsigned long long) fresult.healed_entries);
|
}
|
else
|
appendStringInfo(&msg,
|
"crc_failures=%llu, field_failures=%llu, truncated=%llu, out_of_range=%llu, missing=%llu, generation=%llu, cross_check=%llu, healed_entries=%llu",
|
(unsigned long long) fresult.crc_failures,
|
(unsigned long long) fresult.field_failures,
|
(unsigned long long) fresult.truncated_records,
|
(unsigned long long) fresult.offset_out_of_range,
|
(unsigned long long) fresult.missing_files,
|
(unsigned long long) fresult.generation_violations,
|
(unsigned long long) fresult.cross_check_failures,
|
(unsigned long long) fresult.healed_entries);
|
}
|
else
|
{
|
appendStringInfoString(&msg, "relation is not CFS");
|
}
|
|
relation_close(rel, AccessShareLock);
|
|
MemSet(nulls, 0, sizeof(nulls));
|
values[0] = ObjectIdGetDatum(reloid);
|
values[1] = BoolGetDatum(errors == 0);
|
values[2] = BoolGetDatum(is_cfs);
|
values[3] = Int64GetDatum((int64) errors);
|
values[4] = CStringGetTextDatum(msg.data);
|
|
pfree(msg.data);
|
|
htup = heap_form_tuple(tupdesc, values, nulls);
|
PG_RETURN_DATUM(HeapTupleGetDatum(htup));
|
#else
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("unsupported CFS feature"),
|
errdetail("This functionality requires the server to be built with cfs support.")));
|
PG_RETURN_NULL();
|
#endif
|
}
|
|
/* ================================================================
|
* pg_cfs_reset_stats(regclass DEFAULT NULL)
|
*
|
* Resets statistics for one relation (when a regclass is given) or for
|
* every relation (when NULL). Returns void.
|
* ================================================================ */
|
Datum
|
pg_cfs_reset_stats(PG_FUNCTION_ARGS)
|
{
|
#ifdef USE_CFS
|
if (!PG_ARGISNULL(0))
|
{
|
Oid reloid = PG_GETARG_OID(0);
|
Relation rel;
|
RelFileLocatorBackend rlocator;
|
|
if (reloid == InvalidOid)
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("relation OID must not be zero")));
|
|
rel = relation_open(reloid, AccessShareLock);
|
if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
|
{
|
rlocator = RelationGetSmgr(rel)->smgr_rlocator;
|
cfs_stats_reset(rlocator, MAIN_FORKNUM);
|
}
|
relation_close(rel, AccessShareLock);
|
}
|
else
|
{
|
cfs_stats_reset_all();
|
}
|
|
PG_RETURN_VOID();
|
#else
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("unsupported CFS feature"),
|
errdetail("This functionality requires the server to be built with cfs support.")));
|
PG_RETURN_VOID();
|
#endif
|
}
|
|
/* ================================================================
|
* pg_cfs_estimate_compression(regclass, algorithm text,
|
* level integer DEFAULT NULL,
|
* sample_pct real DEFAULT 10)
|
*
|
* Reads a random sample of the relation's pages, compresses each one
|
* in-memory with the requested algorithm/level (without writing anything
|
* to disk or changing reloptions) and reports the estimated compression
|
* ratio and the space that would be saved.
|
*
|
* Returns one row of (sampled_pages, estimated_compression_ratio,
|
* estimated_space_saved).
|
* ================================================================ */
|
Datum
|
pg_cfs_estimate_compression(PG_FUNCTION_ARGS)
|
{
|
#ifdef USE_CFS
|
Oid reloid;
|
char *algo_name;
|
int level;
|
float4 sample_pct;
|
Relation rel;
|
CfsAlgorithm algo;
|
CfsCompressOptions copts;
|
BlockNumber nblocks;
|
BlockNumber sampled = 0;
|
uint64 raw_total = 0;
|
uint64 compressed_total = 0;
|
size_t scratch_sz;
|
void *scratch;
|
char *pagebuf;
|
Datum values[3];
|
bool nulls[3];
|
TupleDesc tupdesc;
|
HeapTuple htup;
|
|
/*
|
* The function is deliberately not strict so that the DEFAULT values of
|
* the trailing arguments work; the required arguments therefore have to
|
* be validated by hand before any PG_GETARG_* use.
|
*/
|
if (PG_ARGISNULL(0))
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("argument \"%s\" must not be null", "relation")));
|
if (PG_ARGISNULL(1))
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("argument \"%s\" must not be null", "algorithm")));
|
if (PG_ARGISNULL(3))
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("argument \"%s\" must not be null", "sample_pct")));
|
|
reloid = PG_GETARG_OID(0);
|
algo_name = text_to_cstring(PG_GETARG_TEXT_PP(1));
|
sample_pct = PG_GETARG_FLOAT4(3);
|
|
/* A NULL or invalid regclass is a user error. */
|
if (reloid == InvalidOid)
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("relation OID must not be zero")));
|
|
/* Validate the algorithm. */
|
algo = CfsAlgorithmFromName(algo_name);
|
if (algo != CFS_ALGORITHM_LZ4 && algo != CFS_ALGORITHM_ZSTD)
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("invalid compression algorithm \"%s\"", algo_name),
|
errdetail("Valid algorithms are: \"lz4\", \"zstd\".")));
|
if (!CfsCodecAvailable(algo))
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("compression algorithm \"%s\" is not available in this build",
|
algo_name),
|
errhint("Rebuild the server with the corresponding compression library to enable it.")));
|
|
/* A NULL level defaults to the per-algorithm session GUC value. */
|
level = PG_ARGISNULL(2) ? cfs_default_level_for(algo) : PG_GETARG_INT32(2);
|
|
/* NaN fails both comparisons, so test for it explicitly. */
|
if (isnan(sample_pct) || sample_pct <= 0 || sample_pct > 100)
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("sample_pct must be between 0 (exclusive) and 100")));
|
|
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
|
elog(ERROR, "return type must be a row type");
|
|
rel = relation_open(reloid, AccessShareLock);
|
|
if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
|
ereport(ERROR,
|
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
|
errmsg("relation \"%s\" does not have physical storage",
|
RelationGetRelationName(rel))));
|
|
if (rel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT)
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("CFS is not supported for relation \"%s\"",
|
RelationGetRelationName(rel)),
|
errdetail("Temporary and unlogged relations cannot use CFS.")));
|
|
/* Resolve level to the codec's range. */
|
{
|
int max_level = (algo == CFS_ALGORITHM_LZ4) ?
|
CFS_LZ4_LEVEL_MAX : CFS_ZSTD_LEVEL_MAX;
|
|
if (level < CFS_COMPRESS_LEVEL_MIN)
|
level = CFS_COMPRESS_LEVEL_MIN;
|
if (level > max_level)
|
level = max_level;
|
}
|
|
MemSet(&copts, 0, sizeof(copts));
|
copts.algorithm = algo;
|
copts.level = level;
|
copts.explicit_algorithm = true;
|
copts.allow_raw_fallback = true;
|
copts.min_gain_bytes = 0;
|
|
scratch_sz = CfsCompressScratchSize(BLCKSZ);
|
scratch = palloc(scratch_sz);
|
pagebuf = palloc(BLCKSZ);
|
|
nblocks = RelationGetNumberOfBlocksInFork(rel, MAIN_FORKNUM);
|
|
if (nblocks > 0)
|
{
|
/* Number of pages to sample. */
|
uint64 target = (uint64) ((sample_pct / 100.0) * (float4) nblocks);
|
|
if (target < 1)
|
target = 1;
|
if (target > nblocks)
|
target = nblocks;
|
|
/*
|
* ponytail: deterministic strided sampling rather than a full random
|
* permutation keeps this O(target) and reproducible. Ceiling: for
|
* very small relations we read every page.
|
*/
|
{
|
uint64 stride = nblocks / target;
|
BlockNumber start;
|
BlockNumber b;
|
uint64 count = 0;
|
|
if (stride == 0)
|
stride = 1;
|
start = (BlockNumber) (random() % stride);
|
|
for (b = start; b < nblocks && count < target; b += stride)
|
{
|
Buffer buf;
|
Page page;
|
CfsCompressResult cres;
|
|
CHECK_FOR_INTERRUPTS();
|
|
buf = ReadBuffer(rel, b);
|
LockBuffer(buf, BUFFER_LOCK_SHARE);
|
page = BufferGetPage(buf);
|
memcpy(pagebuf, page, BLCKSZ);
|
LockBuffer(buf, BUFFER_LOCK_UNLOCK);
|
ReleaseBuffer(buf);
|
|
CfsCompressPage(pagebuf, BLCKSZ, &copts,
|
scratch, scratch_sz,
|
&cres);
|
raw_total += BLCKSZ;
|
/* Account for the per-record header + alignment. */
|
compressed_total += cres.total_size;
|
sampled++;
|
count++;
|
}
|
}
|
}
|
|
relation_close(rel, AccessShareLock);
|
|
pfree(scratch);
|
pfree(pagebuf);
|
|
MemSet(nulls, 0, sizeof(nulls));
|
values[0] = Int64GetDatum((int64) sampled);
|
if (sampled == 0 || compressed_total == 0)
|
{
|
values[1] = Float4GetDatum(0.0);
|
values[2] = Int64GetDatum(0);
|
}
|
else
|
{
|
float4 ratio = (float4) raw_total / (float4) compressed_total;
|
int64 saved = (int64) raw_total - (int64) compressed_total;
|
|
values[1] = Float4GetDatum(ratio);
|
values[2] = Int64GetDatum(saved);
|
}
|
|
htup = heap_form_tuple(tupdesc, values, nulls);
|
PG_RETURN_DATUM(HeapTupleGetDatum(htup));
|
#else
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("unsupported CFS feature"),
|
errdetail("This functionality requires the server to be built with cfs support.")));
|
PG_RETURN_NULL();
|
#endif
|
}
|
|
/* ================================================================
|
* Set-returning functions backing the monitoring views
|
*
|
* Both scan pg_class once and emit one row per relation. pg_stat_get_cfs
|
* emits only CFS relations; pg_get_cfs_settings emits every supported
|
* relation (including non-CFS, with is_cfs=false).
|
* ================================================================ */
|
|
#ifdef USE_CFS
|
|
/*
|
* Common scan context. 'cfs_only' selects whether non-CFS relations are
|
* emitted (settings view) or skipped (stat view).
|
*/
|
typedef struct CfsSqlScanCtx
|
{
|
ReturnSetInfo *rsinfo;
|
bool cfs_only;
|
} CfsSqlScanCtx;
|
|
/*
|
* cfs_sql_emit_settings_row
|
* Build and append one pg_cfs_settings row.
|
*
|
* algorithm / level / min_gain_bytes are shown when the relation
|
* stores compressed (opts->is_cfs) or when the row is a partitioned
|
* root carrying a default policy for its partitions
|
* (has_default_policy); a partitioned root never stores data itself,
|
* so its is_cfs stays false either way.
|
*/
|
static void
|
cfs_sql_emit_settings_row(const ReturnSetInfo *rsinfo, Oid reloid,
|
Oid nspoid, const char *relname, char relkind,
|
const CfsEffectiveOptions *opts,
|
bool has_default_policy,
|
bool is_toast, bool is_index,
|
bool is_partitioned_root, bool is_supported)
|
{
|
Datum values[12];
|
bool nulls[12];
|
bool show_policy = opts->is_cfs || has_default_policy;
|
|
MemSet(nulls, 0, sizeof(nulls));
|
|
values[0] = ObjectIdGetDatum(reloid);
|
values[1] = CStringGetTextDatum(get_namespace_name(nspoid));
|
values[2] = CStringGetTextDatum(relname);
|
values[3] = CharGetDatum(relkind);
|
values[4] = BoolGetDatum(opts->is_cfs);
|
if (show_policy)
|
values[5] = cfs_sql_algorithm_text(opts->algorithm);
|
else
|
nulls[5] = true;
|
values[6] = Int32GetDatum(show_policy ? opts->level : 0);
|
values[7] = Int32GetDatum(show_policy ? opts->min_gain_bytes : 0);
|
values[8] = BoolGetDatum(is_toast);
|
values[9] = BoolGetDatum(is_index);
|
values[10] = BoolGetDatum(is_partitioned_root);
|
values[11] = BoolGetDatum(is_supported);
|
|
tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
|
}
|
|
#endif /* USE_CFS */
|
|
Datum
|
pg_get_cfs_settings(PG_FUNCTION_ARGS)
|
{
|
#ifdef USE_CFS
|
ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
|
Relation rel;
|
TableScanDesc scan;
|
HeapTuple tuple;
|
Snapshot snapshot;
|
|
InitMaterializedSRF(fcinfo, 0);
|
|
rel = table_open(RelationRelationId, AccessShareLock);
|
snapshot = RegisterSnapshot(GetTransactionSnapshot());
|
scan = table_beginscan(rel, snapshot, 0, NULL, 0);
|
|
while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
|
{
|
Form_pg_class classform = (Form_pg_class) GETSTRUCT(tuple);
|
Oid reloid = classform->oid;
|
Oid nspoid = classform->relnamespace;
|
NameData relname_buf = classform->relname;
|
char relkind = classform->relkind;
|
bool is_toast,
|
is_index,
|
is_partitioned_root,
|
is_supported;
|
bool has_default_policy = false;
|
CfsEffectiveOptions opts;
|
Relation target;
|
|
is_supported = cfs_sql_supported_relation(classform);
|
if (!is_supported)
|
continue;
|
|
cfs_sql_relkind_flags(classform, &is_toast, &is_index,
|
&is_partitioned_root);
|
|
/*
|
* Resolve the effective policy through the relcache so a TOAST
|
* relation follows its owning table
|
* (CfsEffectiveOptionsFromRelation; an index resolves through its
|
* own stored policy). The pg_class fields are already copied
|
* above, so a relcache flush triggered by opening the relation
|
* cannot corrupt them.
|
*
|
* The scan works on an MVCC snapshot, but the open resolves against
|
* the live catalog: a concurrent DROP may make it fail. As
|
* pg_relation_size (dbsize.c), we prefer skipping the row to aborting
|
* the whole query.
|
*/
|
target = try_relation_open(reloid, AccessShareLock);
|
if (target == NULL)
|
continue;
|
CfsEffectiveOptionsFromRelation(target, &opts);
|
relation_close(target, AccessShareLock);
|
|
/*
|
* A partitioned root never stores data itself, but the default policy
|
* configured for its partitions is a first-class configuration
|
* object: read it from the catalog and show its triple. is_cfs in
|
* the row stays false - the root has no storage to compress.
|
*/
|
if (is_partitioned_root)
|
{
|
has_default_policy = CfsPartitionedDefaultPolicy(reloid, &opts);
|
opts.is_cfs = false;
|
}
|
|
cfs_sql_emit_settings_row(rsinfo, reloid, nspoid,
|
NameStr(relname_buf), relkind, &opts,
|
has_default_policy,
|
is_toast, is_index,
|
is_partitioned_root, is_supported);
|
}
|
|
table_endscan(scan);
|
UnregisterSnapshot(snapshot);
|
table_close(rel, AccessShareLock);
|
|
return (Datum) 0;
|
#else
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("unsupported CFS feature"),
|
errdetail("This functionality requires the server to be built with cfs support.")));
|
PG_RETURN_NULL();
|
#endif
|
}
|
|
Datum
|
pg_stat_get_cfs(PG_FUNCTION_ARGS)
|
{
|
#ifdef USE_CFS
|
ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
|
Relation rel;
|
TableScanDesc scan;
|
HeapTuple tuple;
|
Snapshot snapshot;
|
|
InitMaterializedSRF(fcinfo, 0);
|
|
rel = table_open(RelationRelationId, AccessShareLock);
|
snapshot = RegisterSnapshot(GetTransactionSnapshot());
|
scan = table_beginscan(rel, snapshot, 0, NULL, 0);
|
|
while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
|
{
|
Form_pg_class classform = (Form_pg_class) GETSTRUCT(tuple);
|
Oid reloid = classform->oid;
|
Oid nspoid = classform->relnamespace;
|
NameData relname_buf = classform->relname;
|
char relkind = classform->relkind;
|
char relpersistence = classform->relpersistence;
|
bool relisshared = classform->relisshared;
|
Oid reltablespace = classform->reltablespace;
|
RelFileNumber relfilenode = classform->relfilenode;
|
RelFileLocatorBackend rlocator;
|
CfsStatsSnapshot stats;
|
CfsEffectiveOptions opts;
|
Relation target;
|
int64 logical_size;
|
int64 physical_size;
|
Datum values[23];
|
bool nulls[23];
|
|
/* Only relations with physical storage can be CFS. */
|
if (!RELKIND_HAS_STORAGE(relkind))
|
continue;
|
if (relkind == RELKIND_PARTITIONED_TABLE)
|
continue;
|
|
/*
|
* Skip relations that cannot have CFS storage at all: CFS exists only
|
* for permanent relations (this also filters TEMP and UNLOGGED), and
|
* mapped catalogs (relfilenumber 0) have no file of their own.
|
* Filtering here avoids reconstructing a bogus rlocator and the
|
* stat() calls that RelFileLocatorUsesCfs() would then make for it.
|
*/
|
if (relpersistence != RELPERSISTENCE_PERMANENT)
|
continue;
|
if (!RelFileNumberIsValid(relfilenode))
|
continue;
|
|
/* Reconstruct the rlocator from the copied fields. */
|
rlocator.locator.spcOid = reltablespace ?
|
reltablespace : MyDatabaseTableSpace;
|
if (rlocator.locator.spcOid == GLOBALTABLESPACE_OID || relisshared)
|
rlocator.locator.dbOid = InvalidOid;
|
else
|
rlocator.locator.dbOid = MyDatabaseId;
|
rlocator.locator.relNumber = relfilenode;
|
rlocator.backend = INVALID_PROC_NUMBER;
|
|
if (!RelFileLocatorUsesCfs(rlocator, MAIN_FORKNUM))
|
continue;
|
|
/*
|
* Resolve the effective policy through the relcache so a TOAST
|
* relation follows its owning table
|
* (CfsEffectiveOptionsFromRelation; an index resolves through its
|
* own stored policy). The pg_class fields are already copied
|
* above, so a relcache flush triggered by opening the relation
|
* cannot corrupt them.
|
*
|
* As in pg_get_cfs_settings above: a concurrent DROP may make the
|
* open fail against the live catalog; skip the row instead of
|
* aborting the whole query (pg_relation_size, dbsize.c).
|
*/
|
target = try_relation_open(reloid, AccessShareLock);
|
if (target == NULL)
|
continue;
|
CfsEffectiveOptionsFromRelation(target, &opts);
|
relation_close(target, AccessShareLock);
|
|
if (!cfs_stats_snapshot(rlocator, MAIN_FORKNUM, &stats))
|
MemSet(&stats, 0, sizeof(stats));
|
|
logical_size = (int64) stats.logical_pages * BLCKSZ;
|
physical_size = cfs_sql_physical_size(rlocator);
|
|
MemSet(nulls, 0, sizeof(nulls));
|
|
values[0] = ObjectIdGetDatum(reloid);
|
values[1] = CStringGetTextDatum(get_namespace_name(nspoid));
|
values[2] = CStringGetTextDatum(NameStr(relname_buf));
|
values[3] = cfs_sql_algorithm_text(opts.algorithm);
|
if (!opts.is_cfs)
|
nulls[3] = true;
|
values[4] = Int64GetDatum(logical_size);
|
values[5] = Int64GetDatum(physical_size);
|
values[6] = Int64GetDatum((int64) stats.compressed_pages);
|
values[7] = Int64GetDatum((int64) stats.uncompressed_pages);
|
values[8] = Int64GetDatum((int64) stats.dead_pages);
|
values[9] = Int64GetDatum((int64) stats.dead_bytes);
|
if (physical_size == 0)
|
nulls[10] = true; /* compression_ratio undefined */
|
else
|
values[10] = Float4GetDatum((float4) logical_size /
|
(float4) physical_size);
|
values[11] = Int64GetDatum(logical_size - physical_size);
|
values[12] = Int64GetDatum((int64) stats.read_count);
|
values[13] = Int64GetDatum((int64) stats.read_batch_count);
|
values[14] = Int64GetDatum((int64) stats.read_batched_pages);
|
values[15] = Int64GetDatum((int64) stats.read_fallback_pages);
|
values[16] = Int64GetDatum((int64) stats.write_count);
|
values[17] = Int64GetDatum((int64) stats.compress_count);
|
values[18] = Int64GetDatum((int64) stats.decompress_count);
|
values[19] = Int64GetDatum((int64) stats.crc_failures);
|
if (stats.last_reset == 0)
|
nulls[20] = true;
|
else
|
values[20] = TimestampTzGetDatum(stats.last_reset);
|
if (stats.last_compaction == 0)
|
nulls[21] = true;
|
else
|
values[21] = TimestampTzGetDatum(stats.last_compaction);
|
values[22] = Int64GetDatum((int64) stats.checkpoint_map_rows_written);
|
|
tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
|
}
|
|
table_endscan(scan);
|
UnregisterSnapshot(snapshot);
|
table_close(rel, AccessShareLock);
|
|
return (Datum) 0;
|
#else
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("unsupported CFS feature"),
|
errdetail("This functionality requires the server to be built with cfs support.")));
|
PG_RETURN_NULL();
|
#endif
|
}
|
|
/* ================================================================
|
* Background worker control: pause / resume / status
|
* ================================================================ */
|
|
Datum
|
pg_cfs_bgworker_pause(PG_FUNCTION_ARGS)
|
{
|
#ifdef USE_CFS
|
int64 paused_until = 0;
|
|
if (!PG_ARGISNULL(0))
|
{
|
Interval *iv = PG_GETARG_INTERVAL_P(0);
|
TimestampTz now = GetCurrentTimestamp();
|
|
/* paused_until = now() + interval, via the built-in operator. */
|
paused_until = DatumGetTimestampTz(DirectFunctionCall2(
|
timestamptz_pl_interval,
|
TimestampTzGetDatum(now),
|
IntervalPGetDatum(iv)));
|
|
/*
|
* A non-positive duration (checked on the sum, so any negative
|
* combination of months/days/seconds is caught) would put the
|
* deadline in the past: the pause would instantly expire while the
|
* call reported success. Lifting a pause is a separate, explicit
|
* operation - see pg_cfs_bgworker_resume().
|
*/
|
if (paused_until <= now)
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("pause duration must be positive"),
|
errhint("Use pg_cfs_bgworker_resume() to lift an existing pause.")));
|
}
|
|
cfs_bg_pause(paused_until);
|
PG_RETURN_VOID();
|
#else
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("unsupported CFS feature"),
|
errdetail("This functionality requires the server to be built with cfs support.")));
|
PG_RETURN_VOID();
|
#endif
|
}
|
|
Datum
|
pg_cfs_bgworker_resume(PG_FUNCTION_ARGS)
|
{
|
#ifdef USE_CFS
|
cfs_bg_resume();
|
PG_RETURN_VOID();
|
#else
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("unsupported CFS feature"),
|
errdetail("This functionality requires the server to be built with cfs support.")));
|
PG_RETURN_VOID();
|
#endif
|
}
|
|
Datum
|
pg_cfs_bgworker_status(PG_FUNCTION_ARGS)
|
{
|
#ifdef USE_CFS
|
Datum values[4];
|
bool nulls[4];
|
TupleDesc tupdesc;
|
HeapTuple htup;
|
CfsBgStatus st;
|
|
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
|
elog(ERROR, "return type must be a row type");
|
|
cfs_bg_get_status(&st);
|
|
MemSet(nulls, 0, sizeof(nulls));
|
values[0] = BoolGetDatum(st.paused);
|
if (st.paused_until == 0)
|
nulls[1] = true;
|
else
|
values[1] = TimestampTzGetDatum(st.paused_until);
|
if (st.last_cycle_started_at == 0)
|
nulls[2] = true;
|
else
|
values[2] = TimestampTzGetDatum(st.last_cycle_started_at);
|
if (st.last_cycle_finished_at == 0)
|
nulls[3] = true;
|
else
|
values[3] = TimestampTzGetDatum(st.last_cycle_finished_at);
|
|
htup = heap_form_tuple(tupdesc, values, nulls);
|
PG_RETURN_DATUM(HeapTupleGetDatum(htup));
|
#else
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("unsupported CFS feature"),
|
errdetail("This functionality requires the server to be built with cfs support.")));
|
PG_RETURN_NULL();
|
#endif
|
}
|
|
Datum
|
pg_cfs_map_pool(PG_FUNCTION_ARGS)
|
{
|
#ifdef USE_CFS
|
Datum values[5];
|
bool nulls[5];
|
TupleDesc tupdesc;
|
HeapTuple htup;
|
uint64 in_use = 0;
|
uint64 loads = 0;
|
uint64 evictions = 0;
|
uint64 pool_segments = 0;
|
|
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
|
elog(ERROR, "return type must be a row type");
|
|
cfs_shared_map_stats(&in_use, &loads, &evictions, &pool_segments);
|
|
MemSet(nulls, 0, sizeof(nulls));
|
values[0] = Int64GetDatum((int64) in_use);
|
values[1] = Int64GetDatum((int64) loads);
|
values[2] = Int64GetDatum((int64) evictions);
|
values[3] = Int64GetDatum((int64) pool_segments);
|
values[4] = Int64GetDatum((int64) cfs_shared_map_fallback_reads());
|
|
htup = heap_form_tuple(tupdesc, values, nulls);
|
PG_RETURN_DATUM(HeapTupleGetDatum(htup));
|
#else
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("unsupported CFS feature"),
|
errdetail("This functionality requires the server to be built with cfs support.")));
|
PG_RETURN_NULL();
|
#endif
|
}
|