Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
/*-------------------------------------------------------------------------
 * 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_<oid>"
 *      (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_<oid>", 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_<other oid>" 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;
}