/*------------------------------------------------------------------------- * cfs_rel.c * Compressed File Store (CFS) — relation-level policy layer. * * Implements the public SQL contract for enabling CFS: * * - A relation is a CFS relation iff the "algorithm" reloption is set; * - "level" / "min_gain_bytes" are optional: the catalog stores only the * explicitly spelled-out keys (a partial set is valid), and unset * fields are resolved from the session's cfs_default_* GUCs at write * time (the vanilla default_toast_compression pattern — nothing is * frozen at DDL time); * - TEMP / UNLOGGED relations are rejected; * - TOAST relations carry no CFS reloptions of their own: their policy * resolves through the owning table at runtime; * - indexes acquire their policy once, at CREATE INDEX time: an index * without an explicit policy inherits the parent table's stored * algorithm plus only the auxiliary keys the parent stores explicitly, * and its own unset fields resolve at runtime; an index with no * stored policy of its own is never a CFS relation at runtime; * - partitioned tables only hold a *default* policy (explicit keys only) * and are never physical CFS relations. * * This module deliberately keeps compression/decompression and I/O out of * scope: it only answers "is this fork compressed?" and "with what options?". * * Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group * * IDENTIFICATION * src/backend/storage/cfs/cfs_rel.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "access/amapi.h" #include "access/genam.h" #include "access/htup_details.h" #include "access/reloptions.h" #include "access/table.h" #include "catalog/pg_am_d.h" #include "catalog/pg_class.h" #include "commands/defrem.h" #include "nodes/makefuncs.h" #include "utils/fmgroids.h" #include "utils/rel.h" #include "utils/relcache.h" #include "utils/syscache.h" #include "storage/cfs/cfs.h" #include "storage/cfs/cfs_codec.h" #include "storage/cfs/cfs_compress.h" #include "storage/cfs/cfs_guc.h" #include "storage/cfs/cfs_rel.h" #ifdef USE_CFS #include "access/nbtree.h" #include "access/hash.h" #include "access/gin_private.h" #include "access/gist_private.h" #include "access/brin.h" #include "access/spgist_private.h" #endif /* ---------------------------------------------------------------- * Validation helpers * ---------------------------------------------------------------- */ /* * cfs_check_effective_level * Reject an explicitly stored compression level outside the * algorithm's native range. Called from DDL-time reloption validation * (cfs_validate_fields) — only explicit values are checked there; a * GUC value is never validated against an algorithm, because each * per-algorithm GUC applies only to its own algorithm — and from the * effective-options resolvers, where the stored level was already * validated at DDL time: there the check exists so a corrupted catalog * errors loudly instead of being silently clamped by the codec. */ static void cfs_check_effective_level(CfsAlgorithm algo, int level) { int max_level = CfsCodecMaxLevel(algo); if (level >= CFS_COMPRESS_LEVEL_MIN && level <= max_level) return; ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("CFS compression level %d is out of range for algorithm \"%s\"", level, CfsAlgorithmGetName(algo)), errdetail("Valid levels for algorithm \"%s\" are %d..%d.", CfsAlgorithmGetName(algo), CFS_COMPRESS_LEVEL_MIN, max_level))); } #ifdef USE_CFS /* * cfs_validate_fields * Cross-field validation of freshly-parsed CFS reloptions. Shared by * the heap (StdRdOptions) and every index AM options struct so that * tables and indexes enforce exactly the same rules. No-op when * algorithm == CFS_ALGORITHM_RAW and no auxiliary option was * specified. */ static void cfs_validate_fields(const CfsRelPolicyOptions *pol) { CfsAlgorithm algo = (CfsAlgorithm) pol->algorithm; if (algo == CFS_ALGORITHM_RAW) { /* * CFS is not enabled, so the auxiliary parameters make no sense and * must be rejected to avoid silently ignored options. */ if (pol->level_set) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("CFS compression algorithm must be specified"), errdetail("Option \"level\" requires option \"algorithm\"."))); if (pol->min_gain_bytes_set) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("CFS compression algorithm must be specified"), errdetail("Option \"min_gain_bytes\" requires option \"algorithm\"."))); return; } /* * CFS is enabled: the requested algorithm must be known and its backing * codec library must be compiled into this server build. */ if (!CFS_ALGORITHM_VALID(algo) || !CfsCodecAvailable(algo)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("CFS compression algorithm \"%s\" is not available in this build", CfsAlgorithmGetName(algo)), errhint("Rebuild the server with the corresponding compression library to enable it."))); /* * Per-algorithm level range validation: an explicitly specified level * must fit the algorithm's native range. Unset fields are not checked * here — they resolve from the per-algorithm GUC at write time, and * each GUC's own range applies only to its own algorithm. */ if (pol->level_set) cfs_check_effective_level(algo, pol->level); ereport(DEBUG1, (errmsg_internal("CFS policy enabled: algorithm=\"%s\", level=%s, " "min_gain_bytes=%s", CfsAlgorithmGetName(algo), pol->level_set ? psprintf("%d", pol->level) : "(runtime)", pol->min_gain_bytes_set ? psprintf("%d", pol->min_gain_bytes) : "(runtime)"))); } /* * cfs_check_no_toast_policy * Reject CFS reloptions (algorithm / level / min_gain_bytes) specified * in the "toast" namespace, on CREATE TABLE / CREATE TABLE AS / * CREATE MATERIALIZED VIEW and on ALTER TABLE. A TOAST relation has no * independent CFS policy: it follows the owning table's policy, which * is resolved from the parent at runtime (see * CfsEffectiveOptionsFromRelation), so any toast.* CFS option is * rejected unconditionally. */ void cfs_check_no_toast_policy(const List *options) { ListCell *lc; foreach(lc, options) { DefElem *def = lfirst_node(DefElem, lc); if (def->defnamespace != NULL && strcmp(def->defnamespace, "toast") == 0 && (strcmp(def->defname, "algorithm") == 0 || strcmp(def->defname, "level") == 0 || strcmp(def->defname, "min_gain_bytes") == 0)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("CFS compression options cannot be specified for the TOAST table"), errdetail("The TOAST table compression policy is inherited from the main table."))); } } /* * cfs_index_extract * Pull the CFS policy out of an index's parsed options struct * (BTOptions / HashOptions / ...), each of which embeds it as its * "cfs" member (CfsRelPolicyOptions). Returns true when the index * carries an explicit algorithm (its own policy); false when it does * not. What a missing policy means is up to the caller: * policy-definition time (CREATE INDEX) may inherit one from the * parent table, while the runtime resolver answers "not CFS". * Returns false with a zeroed *out for NULL options or an unknown AM. */ static bool cfs_index_extract(const void *rdopts, Oid relam, CfsRelPolicyOptions *out) { const CfsRelPolicyOptions *pol = NULL; if (rdopts != NULL) { switch (relam) { case BTREE_AM_OID: pol = &((const BTOptions *) rdopts)->cfs; break; case HASH_AM_OID: pol = &((const HashOptions *) rdopts)->cfs; break; case GIN_AM_OID: pol = &((const GinOptions *) rdopts)->cfs; break; case GIST_AM_OID: pol = &((const GiSTOptions *) rdopts)->cfs; break; case SPGIST_AM_OID: pol = &((const SpGistOptions *) rdopts)->cfs; break; case BRIN_AM_OID: pol = &((const BrinOptions *) rdopts)->cfs; break; default: /* * Unknown AM (e.g. a custom index AM) or no typed options: * leave the zeroed (RAW) defaults in place; the index cannot * carry its own CFS policy. */ break; } } if (pol == NULL) MemSet(out, 0, sizeof(*out)); else *out = *pol; return out->algorithm != CFS_ALGORITHM_RAW; } #endif /* * cfs_validate_std_reloptions * Cross-field validation performed right after reloptions are parsed. * Called only when validate == true (fresh input from CREATE/ALTER). */ void cfs_validate_std_reloptions(const StdRdOptions *opts) { #ifdef USE_CFS if (opts == NULL) return; cfs_validate_fields(&opts->cfs); #else if (opts == NULL) return; #endif } /* * cfs_check_persistence * Reject CFS for non-permanent relations. Called from the DDL paths * (DefineRelation / ATExecSetRelOptions) where the persistence of the * target relation is known. */ void cfs_check_persistence(const StdRdOptions *opts, char relpersistence) { #ifdef USE_CFS if (opts == NULL || opts->cfs.algorithm == CFS_ALGORITHM_RAW) return; if (relpersistence == RELPERSISTENCE_TEMP) ereport(ERROR, (errcode(ERRCODE_INVALID_TABLE_DEFINITION), errmsg("CFS is not supported for temporary tables"))); if (relpersistence == RELPERSISTENCE_UNLOGGED) ereport(ERROR, (errcode(ERRCODE_INVALID_TABLE_DEFINITION), errmsg("CFS is not supported for unlogged tables"))); #else /* no CFS: nothing to check */ (void) opts; (void) relpersistence; #endif } /* * cfs_validate_index_reloptions * Validate the CFS policy stored in an index's freshly-parsed AM * options struct (the bytea returned by the AM's amoptions). Applies * the same rules as cfs_validate_std_reloptions plus the persistence * check, so CREATE INDEX / ALTER INDEX WITH (algorithm=...) enforce * identical semantics to tables. No-op for a non-CFS index. * * 'idxopts' is the parsed options struct (e.g. BTOptions *); 'relam' * tells us how to interpret it. */ void cfs_validate_index_reloptions(const bytea *idxopts, Oid relam, char relpersistence) { #ifdef USE_CFS CfsRelPolicyOptions pol; bool has_own; /* * Nothing was parsed (no WITH clause produced options): nothing to * validate. */ if (idxopts == NULL) return; has_own = cfs_index_extract(idxopts, relam, &pol); /* * Enforce the same cross-field rules as for heaps: level / min_gain_bytes * are only valid together with algorithm, codec must be available, level * must be in range. When the AM is unknown, cfs_index_extract leaves the * RAW defaults and this is a no-op. */ cfs_validate_fields(&pol); if (has_own) { if (relpersistence == RELPERSISTENCE_TEMP) ereport(ERROR, (errcode(ERRCODE_INVALID_TABLE_DEFINITION), errmsg("CFS is not supported for temporary tables"))); if (relpersistence == RELPERSISTENCE_UNLOGGED) ereport(ERROR, (errcode(ERRCODE_INVALID_TABLE_DEFINITION), errmsg("CFS is not supported for unlogged tables"))); } #else (void) idxopts; (void) relam; (void) relpersistence; #endif } /* ---------------------------------------------------------------- * Effective option resolution * ---------------------------------------------------------------- */ /* * RelkindUsesStdRdOptions * True when a relation of this relkind stores its reloptions in a * StdRdOptions struct (heap_reloptions / partitioned_table_reloptions). * Views, composite types, foreign tables and sequences use different, * narrower structs (ViewOptions / ...) with no CFS fields, so casting * their rd_options to StdRdOptions would read unrelated memory. * * Callers must consult this helper before interpreting rd_options as a * StdRdOptions; keep all such sites on this single predicate so they * cannot drift apart and reintroduce the unsafe cast in one path. */ bool RelkindUsesStdRdOptions(char relkind) { return relkind == RELKIND_RELATION || relkind == RELKIND_MATVIEW || relkind == RELKIND_TOASTVALUE || relkind == RELKIND_PARTITIONED_TABLE; } /* * CfsEffectiveOptionsFromStdRdOptions * Resolve the CFS policy stored in parsed StdRdOptions: only the * explicitly stored fields are carried (with their set-flags); unset * fields keep the 0 sentinel and are resolved by the write path from * the session's cfs_default_* GUCs at the moment of the write. */ void CfsEffectiveOptionsFromStdRdOptions(const StdRdOptions *opts, CfsEffectiveOptions *out) { memset(out, 0, sizeof(CfsEffectiveOptions)); if (opts == NULL || opts->cfs.algorithm == CFS_ALGORITHM_RAW) { out->algorithm = CFS_ALGORITHM_RAW; out->is_cfs = false; return; } out->algorithm = (CfsAlgorithm) opts->cfs.algorithm; out->is_cfs = true; /* * Normalize unset fields to the 0 sentinel: the reloption parser fills in * the placeholder defaults (3 / 512) for options the user did not spell * out, and those must never leak into the effective options, the * shared-memory slot, the WAL policy record or the SQL surface — only * the set-flags plus zero travel with the policy. */ out->level = opts->cfs.level_set ? opts->cfs.level : 0; out->min_gain_bytes = opts->cfs.min_gain_bytes_set ? opts->cfs.min_gain_bytes : 0; out->level_set = opts->cfs.level_set; out->min_gain_bytes_set = opts->cfs.min_gain_bytes_set; /* * Defense-in-depth: the stored level was validated at DDL time, but * re-check it so a corrupted catalog fails loudly here instead of being * silently clamped by the codec. Unset fields have nothing to check — * their range is the GUC's own range. */ if (out->level_set) cfs_check_effective_level(out->algorithm, out->level); } /* * cfs_resolve_index_own * Resolve effective options from the fields extracted by * cfs_index_extract(). Index AM options store the same explicit-only * policy as the heap: unset fields keep the 0 sentinel with their * set-flags false, exactly like CfsEffectiveOptionsFromStdRdOptions(). */ static void cfs_resolve_index_own(const CfsRelPolicyOptions *pol, CfsEffectiveOptions *out) { out->algorithm = (CfsAlgorithm) pol->algorithm; out->is_cfs = true; /* Same 0-sentinel normalization as CfsEffectiveOptionsFromStdRdOptions. */ out->level = pol->level_set ? pol->level : 0; out->min_gain_bytes = pol->min_gain_bytes_set ? pol->min_gain_bytes : 0; out->level_set = pol->level_set; out->min_gain_bytes_set = pol->min_gain_bytes_set; /* * Defense-in-depth: re-check the stored level so a corrupted catalog * fails loudly instead of being silently clamped by the codec. Unset * fields have nothing to check. */ if (out->level_set) cfs_check_effective_level(out->algorithm, out->level); } /* * toast_parent_reloid * Recover the owning table's OID from a TOAST relation name. Toast * relation names follow the hard catalog convention "pg_toast_" * (toasting.c; the same pattern is used in every toast namespace), so * the parent OID is the segment after the last underscore. Returns * InvalidOid when the name does not follow the convention; callers * treat such a relation as non-CFS (fail-safe). */ static Oid toast_parent_reloid(const char *relname) { const char *last = strrchr(relname, '_'); char *endptr; unsigned long oid; if (last == NULL || last[1] == '\0') return InvalidOid; oid = strtoul(last + 1, &endptr, 10); if (*endptr != '\0' || oid == 0 || oid > PG_UINT32_MAX) return InvalidOid; return (Oid) oid; } /* * cfs_toast_parent_oid * Catalog path: recover the table owning a TOAST relation by scanning * pg_class for the heap whose reltoastrelid points at it. Used when * the TOAST relation was renamed or its name is misleading. Returns * InvalidOid when no owning table exists; the caller treats that as * non-CFS. */ static Oid cfs_toast_parent_oid(Oid toastrelid) { Relation pgclass; ScanKeyData key[1]; SysScanDesc scan; HeapTuple tuple; Oid parent = InvalidOid; pgclass = table_open(RelationRelationId, AccessShareLock); ScanKeyInit(&key[0], Anum_pg_class_reltoastrelid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(toastrelid)); scan = systable_beginscan(pgclass, InvalidOid, false, NULL, 1, key); if (HeapTupleIsValid(tuple = systable_getnext(scan))) parent = ((Form_pg_class) GETSTRUCT(tuple))->oid; systable_endscan(scan); table_close(pgclass, AccessShareLock); return parent; } /* * cfs_toast_owner_relation * Open and return the table owning the given TOAST relation, or NULL * when no owning table can be recovered. * * The common case is the hard catalog naming convention * "pg_toast_", which needs no catalog access. That name is only * trusted together with the back-link: the table it names must point * back at this TOAST relation via reltoastrelid. Without the check a * TOAST relation renamed to "pg_toast_" would silently * borrow another table's policy. When the name is unusable or the * back-link does not match, fall back to the catalog scan. */ static Relation cfs_toast_owner_relation(Relation toastrel) { Oid toastrelid = RelationGetRelid(toastrel); Oid parentOid; Relation parent; parentOid = toast_parent_reloid(RelationGetRelationName(toastrel)); if (OidIsValid(parentOid)) { parent = RelationIdGetRelation(parentOid); if (RelationIsValid(parent)) { if (parent->rd_rel->reltoastrelid == toastrelid) return parent; RelationClose(parent); } } parentOid = cfs_toast_parent_oid(toastrelid); if (!OidIsValid(parentOid)) return NULL; return RelationIdGetRelation(parentOid); } /* * CfsEffectiveOptionsFromRelation * Resolve the CFS policy of an arbitrary relation. Heaps, * materialized views and partitioned tables carry their own stored * policy; a TOAST relation has none and follows its owning table * (recovered from the relation name verified against the catalog * back-link, or from the back-link alone); an index is a CFS relation * only through its own stored policy and never follows its table at * runtime. */ void CfsEffectiveOptionsFromRelation(Relation rel, CfsEffectiveOptions *out) { char relkind = rel->rd_rel->relkind; memset(out, 0, sizeof(CfsEffectiveOptions)); /* * A temp relation is never a CFS relation: temp relations cannot carry * sidecar files. The guard must precede any reloptions parsing, * because a transient temp table may carry CFS reloptions copied * internally - make_new_heap() copies the matview's reloptions onto * the temp transient table of REFRESH MATERIALIZED VIEW CONCURRENTLY, * where the DDL persistence check never runs. */ if (rel->rd_backend != INVALID_PROC_NUMBER) { out->algorithm = CFS_ALGORITHM_RAW; out->is_cfs = false; return; } /* * A TOAST relation has no CFS policy of its own: it always follows the * owning table's policy, resolved at runtime (the table's unset fields * resolve from the session GUCs exactly as for a direct write to the * table). A parent that cannot be recovered or opened fails safe to "not * CFS". */ if (relkind == RELKIND_TOASTVALUE) { Relation parent; bool use_cfs; parent = cfs_toast_owner_relation(rel); if (!RelationIsValid(parent)) { out->algorithm = CFS_ALGORITHM_RAW; out->is_cfs = false; return; } use_cfs = RelationUsesCfs(parent, MAIN_FORKNUM); if (use_cfs) CfsEffectiveOptionsFromRelation(parent, out); else { out->algorithm = CFS_ALGORITHM_RAW; out->is_cfs = false; } RelationClose(parent); return; } /* * Indexes carry their own CFS policy in the AM options struct (BTOptions * / HashOptions / ...). The policy is defined exactly once: at CREATE * INDEX time an index without an explicit policy inherits the parent * table's stored algorithm and explicitly stored auxiliary keys into * its own reloptions (the policy freeze, see CfsIndexInheritReloptions), * and WITH (algorithm = ...) / ALTER INDEX ... SET store one * explicitly. At runtime an index without its own stored policy is * never CFS: it does not follow the table it is on, so ALTER TABLE ... * SET (algorithm) cannot silently compress an existing plain index, * and ALTER INDEX ... RESET (algorithm) disables index compression for * good. Resolution from the physical sidecar files (the smgr * ensure_state fallback) applies to processes without a relcache * (recovery, auxiliary processes); in a regular backend the state * "compressed sidecars without a policy" is no longer reachable * through supported paths: CREATE INDEX freezes a policy into the * reloptions, ALTER INDEX SET/RESET rebuild the storage, and * dump/restore carries the reloptions along. */ if ((relkind == RELKIND_INDEX || relkind == RELKIND_PARTITIONED_INDEX) && rel->rd_index != NULL) { #ifdef USE_CFS CfsRelPolicyOptions pol; if (cfs_index_extract(rel->rd_options, rel->rd_rel->relam, &pol)) { /* * The index has its own algorithm: resolve effective options from * its stored policy, exactly like a heap. */ cfs_resolve_index_own(&pol, out); return; } #endif /* * No policy of its own: plain storage -- the runtime fallback to * the table's effective options is gone (QDB-1507). */ out->algorithm = CFS_ALGORITHM_RAW; out->is_cfs = false; return; } /* * Heap, materialized view, TOAST and partitioned tables all use * StdRdOptions. In the current code a partitioned table's rd_options is * always NULL (partitioned_table_reloptions() returns NULL when validate * is false, which is how the relcache reload path calls it), so the * RELKIND_PARTITIONED_TABLE branch below is unreachable. Keep it only as * a cheap safeguard in case vanilla PostgreSQL ever starts storing * options for partitioned tables; is_cfs must then stay false, because a * partitioned root is not a physical CFS relation. The root's default * policy is available only by parsing pg_class.reloptions directly (see * CfsPartitionedDefaultPolicy), never through this resolver. * * Only these relkinds carry rd_options as a StdRdOptions struct: views, * composite types, foreign tables and sequences use different, narrower * reloptions structs (ViewOptions / ...) with no CFS fields, so casting * their rd_options to StdRdOptions would read unrelated memory. Treat * any other relkind as "not CFS" without touching rd_options. */ if (RelkindUsesStdRdOptions(relkind)) { if (rel->rd_options != NULL) { CfsEffectiveOptionsFromStdRdOptions((const StdRdOptions *) rel->rd_options, out); if (relkind == RELKIND_PARTITIONED_TABLE) out->is_cfs = false; } else { out->algorithm = CFS_ALGORITHM_RAW; out->is_cfs = false; } } else { out->algorithm = CFS_ALGORITHM_RAW; out->is_cfs = false; } } /* * CfsPartitionedDefaultPolicy * Read the default CFS policy recorded in a partitioned parent's * pg_class.reloptions. * * A partitioned table's relcache entry deliberately carries no * rd_options (partitioned_table_reloptions() runs with validate=false), * so the triple has to be parsed straight from the catalog. Returns * false when the parent carries no CFS triple; otherwise fills *opts * with the stored default (only the explicitly stored keys carry * values; unset fields keep their set-flags false and are resolved * from the session GUCs by consumers that need a value). When the * parent is not a CFS relation the remaining fields are zeroed, as * documented for CfsEffectiveOptions. */ bool CfsPartitionedDefaultPolicy(Oid reloid, CfsEffectiveOptions *opts) { HeapTuple parentTup; bool isnull; Datum reloptions; List *defs; ListCell *lc; bool have_level = false; bool have_min_gain = false; opts->is_cfs = false; opts->algorithm = CFS_ALGORITHM_RAW; opts->level = 0; opts->min_gain_bytes = 0; opts->level_set = false; opts->min_gain_bytes_set = false; parentTup = SearchSysCache1(RELOID, ObjectIdGetDatum(reloid)); if (!HeapTupleIsValid(parentTup)) return false; reloptions = SysCacheGetAttr(RELOID, parentTup, Anum_pg_class_reloptions, &isnull); if (!isnull) { defs = untransformRelOptions(reloptions); foreach(lc, defs) { DefElem *def = lfirst_node(DefElem, lc); if (def->defnamespace != NULL) continue; if (strcmp(def->defname, "algorithm") == 0) { opts->algorithm = (int) CfsAlgorithmFromName(defGetString(def)); opts->is_cfs = opts->algorithm != CFS_ALGORITHM_RAW; } else if (strcmp(def->defname, "level") == 0) { opts->level = atoi(defGetString(def)); have_level = true; } else if (strcmp(def->defname, "min_gain_bytes") == 0) { opts->min_gain_bytes = atoi(defGetString(def)); have_min_gain = true; } } } ReleaseSysCache(parentTup); /* * Only the explicitly stored keys are reported: the parent's unset fields * keep their set-flags false, and consumers that need a value resolve it * from the session GUCs (exactly like the write path does for a partition * created without explicit options). A non-CFS parent keeps the fields * zeroed per the CfsEffectiveOptions contract. */ opts->level_set = have_level; opts->min_gain_bytes_set = have_min_gain; return opts->is_cfs; } /* * CfsEffectiveOptionsFromIndexReloptions * Resolve the effective CFS policy for a freshly created index from its * raw reloptions datum, before the index's relcache entry exists (the * local Relation built by heap_create() has neither rd_options nor * rd_index). The reloptions datum is the only source: an explicit * "algorithm" in the index's AM options wins, and a datum without one * resolves plain. The honest CREATE INDEX paths freeze the table's * policy into the reloptions beforehand (CfsIndexInheritReloptions in * indexcmds.c), so nothing is inherited from 'heapRel' here — rebuild * copies (REINDEX CONCURRENTLY bypasses DefineIndex) carry the original * index's reloptions and must not re-inherit from the table (QDB-1507). */ void CfsEffectiveOptionsFromIndexReloptions(Relation heapRel, Oid relam, Datum reloptions, CfsEffectiveOptions *out) { const IndexAmRoutine *amroutine; bytea *idxopts; CfsRelPolicyOptions pol; memset(out, 0, sizeof(CfsEffectiveOptions)); /* * A temp heap is never a CFS relation, so an index built on it stays * plain whatever its reloptions say: defense-in-depth for CREATE * INDEX / REINDEX on a temp table (the DDL persistence check may be * bypassed when reloptions are copied internally). The guard * precedes the explicit-policy branch below. */ if (RelationIsValid(heapRel) && heapRel->rd_backend != INVALID_PROC_NUMBER) { out->algorithm = CFS_ALGORITHM_RAW; out->is_cfs = false; return; } amroutine = GetIndexAmRoutineByAmId(relam, false); idxopts = index_reloptions(amroutine->amoptions, reloptions, false); if (cfs_index_extract(idxopts, relam, &pol)) { cfs_resolve_index_own(&pol, out); return; } /* * No explicit policy: plain storage (QDB-1507, review F1). The * reloptions datum is the only source of an index's policy: honest * CREATE INDEX paths freeze the table's policy into the reloptions * at the operator level (CfsIndexInheritReloptions in indexcmds.c), * and rebuild copies (REINDEX CONCURRENTLY) carry the original * index's reloptions verbatim and must not re-inherit from the table. */ out->algorithm = CFS_ALGORITHM_RAW; out->is_cfs = false; } #ifdef USE_CFS /* * cfs_append_num_option * Append a numeric reloption DefElem to a list of DefElems. */ static List * cfs_append_num_option(List *defs, char *name, int value) { char numbuf[16]; snprintf(numbuf, sizeof(numbuf), "%d", value); return lappend(defs, makeDefElem(name, (Node *) makeString(pstrdup(numbuf)), -1)); } #endif /* * CfsIndexInheritReloptions * Compute the stored reloptions of an index at policy-definition time * (CREATE INDEX, or ALTER INDEX ... SET/RESET touching CFS options). * * An index with its own explicit "algorithm" keeps its stored options * verbatim — its unset auxiliary fields resolve from the session GUCs * at write time, exactly like a table's. An index without an explicit * "algorithm" inherits the parent table's *physical fact*: the * algorithm and only the parent's explicitly stored level / * min_gain_bytes (nothing the parent itself resolves at runtime is * copied into the index). After that the index is independent: later * changes of the table's policy do not affect it. * * 'heapRel' may be NULL/invalid (ALTER INDEX path): then no * inheritance happens and an index without its own algorithm stays * without a policy (e.g. after ALTER INDEX ... RESET (algorithm)). */ Datum CfsIndexInheritReloptions(Relation heapRel, Oid relam, Datum indexOptions) { #ifdef USE_CFS const IndexAmRoutine *amroutine; bytea *idxopts; List *defs; CfsRelPolicyOptions pol; bool has_own; StdRdOptions *hopts; amroutine = GetIndexAmRoutineByAmId(relam, false); idxopts = index_reloptions(amroutine->amoptions, indexOptions, false); has_own = cfs_index_extract(idxopts, relam, &pol); /* Own policy: stored verbatim, unset fields resolve at runtime. */ if (has_own) return indexOptions; /* * No own policy: inherit the parent's algorithm and its explicitly stored * auxiliary keys, if any. */ /* * A temp heap never carries a valid CFS policy: nothing is inherited * into the stored reloptions of an index built on it (defense * against internally copied reloptions, e.g. onto the transient * table of REFRESH MATERIALIZED VIEW CONCURRENTLY). */ if (!RelationIsValid(heapRel) || heapRel->rd_backend != INVALID_PROC_NUMBER) return indexOptions; hopts = (heapRel->rd_options != NULL) ? (StdRdOptions *) heapRel->rd_options : NULL; if (hopts == NULL || hopts->cfs.algorithm == CFS_ALGORITHM_RAW) return indexOptions; ereport(DEBUG1, (errmsg_internal("CFS: inheriting parent table policy into index " "reloptions"))); if (indexOptions != (Datum) 0) defs = untransformRelOptions(indexOptions); else defs = NIL; defs = lappend(defs, makeDefElem("algorithm", (Node *) makeString(pstrdup(CfsAlgorithmGetName((CfsAlgorithm) hopts->cfs.algorithm))), -1)); if (hopts->cfs.level_set) defs = cfs_append_num_option(defs, "level", hopts->cfs.level); if (hopts->cfs.min_gain_bytes_set) defs = cfs_append_num_option(defs, "min_gain_bytes", hopts->cfs.min_gain_bytes); return transformRelOptions((Datum) 0, defs, NULL, NULL, false, false); #else return indexOptions; #endif } /* ---------------------------------------------------------------- * Predicates * ---------------------------------------------------------------- */ /* * RelationUsesCfs * True if the given fork is stored compressed by CFS. */ bool RelationUsesCfs(Relation rel, ForkNumber forknum) { CfsEffectiveOptions opts; /* Only the main fork is ever compressed. */ if (forknum != MAIN_FORKNUM) return false; /* TEMP and UNLOGGED relations never use CFS. */ if (rel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT) return false; /* A partitioned table is never a physical CFS relation. */ if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) return false; /* * An index is CFS only through its own stored policy: the resolver * never falls back to the table (see CfsEffectiveOptionsFromRelation). */ if (rel->rd_rel->relkind == RELKIND_INDEX || rel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX) { CfsEffectiveOptionsFromRelation(rel, &opts); return opts.is_cfs; } /* * Heap / materialized view / TOAST: read the typed reloptions. Only * relkinds whose rd_options is a StdRdOptions struct are safe to cast * (see RelkindUsesStdRdOptions); for views and other relkinds the cast * would read unrelated memory, so treat them as non-CFS. Partitioned * tables are already excluded above. */ if (!RelkindUsesStdRdOptions(rel->rd_rel->relkind)) return false; if (rel->rd_options == NULL) return false; return ((const StdRdOptions *) rel->rd_options)->cfs.algorithm != CFS_ALGORITHM_RAW; }