Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 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
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
/*-------------------------------------------------------------------------
 * 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
}