Исходный код СУБД 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
#include "postgres.h"
 
#include <float.h>
 
#include "access/amapi.h"
#include "access/reloptions.h"
#include "commands/progress.h"
#include "commands/vacuum.h"
#include "vector/ivfflat.h"
#include "utils/float.h"
#include "utils/guc.h"
#include "utils/selfuncs.h"
#include "utils/spccache.h"
 
#if PG_VERSION_NUM < 150000
#define MarkGUCPrefixReserved(x) EmitWarningsOnPlaceholders(x)
#endif
 
int         ivfflat_probes;
int         ivfflat_iterative_scan;
int         ivfflat_max_probes;
static relopt_kind ivfflat_relopt_kind;
 
const struct config_enum_entry ivfflat_iterative_scan_options[] = {
    {"off", IVFFLAT_ITERATIVE_SCAN_OFF, false},
    {"relaxed_order", IVFFLAT_ITERATIVE_SCAN_RELAXED, false},
    {NULL, 0, false}
};
 
/*
 * Initialize index options and variables
 */
void
IvfflatInit(void)
{
    ivfflat_relopt_kind = add_reloption_kind();
    add_int_reloption(ivfflat_relopt_kind, "lists", "Number of inverted lists",
                      IVFFLAT_DEFAULT_LISTS, IVFFLAT_MIN_LISTS, IVFFLAT_MAX_LISTS, AccessExclusiveLock);
    /* [PG_CUSTOM: RUDB_DBMS_VECTOR] Stage-1 checkpointing state flag; read by the DBMS_VECTOR checkpoint API only. */
    add_bool_reloption(ivfflat_relopt_kind, "checkpointing", "Enable periodic checkpointing of in-progress builds",
                       true, AccessExclusiveLock);
}
 
/*
 * Get the name of index build phase
 */
static char *
ivfflatbuildphasename(int64 phasenum)
{
    switch (phasenum)
    {
        case PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE:
            return "initializing";
        case PROGRESS_IVFFLAT_PHASE_KMEANS:
            return "performing k-means";
        case PROGRESS_IVFFLAT_PHASE_ASSIGN:
            return "assigning tuples";
        case PROGRESS_IVFFLAT_PHASE_LOAD:
            return "loading tuples";
        default:
            return NULL;
    }
}
 
/*
 * Estimate the cost of an index scan
 */
static void
ivfflatcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
                    Cost *indexStartupCost, Cost *indexTotalCost,
                    Selectivity *indexSelectivity, double *indexCorrelation,
                    double *indexPages)
{
    GenericCosts costs;
    int         lists;
    double      ratio;
    double      sequentialRatio = 0.5;
    double      startupPages;
    double      spc_seq_page_cost;
    Relation    index;
 
    /* Never use index without order */
    if (path->indexorderbys == NULL)
    {
        *indexStartupCost = get_float8_infinity();
        *indexTotalCost = get_float8_infinity();
        *indexSelectivity = 0;
        *indexCorrelation = 0;
        *indexPages = 0;
#if PG_VERSION_NUM >= 180000
        /* See "On disable_cost" thread on pgsql-hackers */
        path->path.disabled_nodes = 2;
#endif
        return;
    }
 
    MemSet(&costs, 0, sizeof(costs));
 
    genericcostestimate(root, path, loop_count, &costs);
 
    index = index_open(path->indexinfo->indexoid, NoLock);
    IvfflatGetMetaPageInfo(index, &lists, NULL);
    index_close(index, NoLock);
 
    /* Get the ratio of lists that we need to visit */
    ratio = ((double) ivfflat_probes) / lists;
    if (ratio > 1.0)
        ratio = 1.0;
 
    get_tablespace_page_costs(path->indexinfo->reltablespace, NULL, &spc_seq_page_cost);
 
    /* Change some page cost from random to sequential */
    costs.indexTotalCost -= sequentialRatio * costs.numIndexPages * (costs.spc_random_page_cost - spc_seq_page_cost);
 
    /* Startup cost is cost before returning the first row */
    costs.indexStartupCost = costs.indexTotalCost * ratio;
 
    /* Adjust cost if needed since TOAST not included in seq scan cost */
    startupPages = costs.numIndexPages * ratio;
    if (startupPages > path->indexinfo->rel->pages && ratio < 0.5)
    {
        /* Change rest of page cost from random to sequential */
        costs.indexStartupCost -= (1 - sequentialRatio) * startupPages * (costs.spc_random_page_cost - spc_seq_page_cost);
 
        /* Remove cost of extra pages */
        costs.indexStartupCost -= (startupPages - path->indexinfo->rel->pages) * spc_seq_page_cost;
    }
 
    *indexStartupCost = costs.indexStartupCost;
    *indexTotalCost = costs.indexTotalCost;
    *indexSelectivity = costs.indexSelectivity;
    *indexCorrelation = costs.indexCorrelation;
    *indexPages = costs.numIndexPages;
}
 
/*
 * Parse and validate the reloptions
 */
static bytea *
ivfflatoptions(Datum reloptions, bool validate)
{
    static const relopt_parse_elt tab[] = {
        {"lists", RELOPT_TYPE_INT, offsetof(IvfflatOptions, lists)},
        /* [PG_CUSTOM: RUDB_DBMS_VECTOR] stage-1 checkpointing state flag */
        {"checkpointing", RELOPT_TYPE_BOOL, offsetof(IvfflatOptions, checkpointing)},
    };
 
    return (bytea *) build_reloptions(reloptions, validate,
                                      ivfflat_relopt_kind,
                                      sizeof(IvfflatOptions),
                                      tab, lengthof(tab));
}
 
/*
 * Validate catalog entries for the specified operator class
 */
static bool
ivfflatvalidate(Oid opclassoid)
{
    return true;
}
 
/*
 * Define index handler
 *
 * See https://www.postgresql.org/docs/current/index-api.html
 */
FUNCTION_PREFIX PG_FUNCTION_INFO_V1(ivfflathandler);
Datum
ivfflathandler(PG_FUNCTION_ARGS)
{
    static const IndexAmRoutine amroutine = {
        .type = T_IndexAmRoutine,
        .amstrategies = 0,
        .amsupport = 5,
        .amoptsprocnum = 0,
        .amcanorder = false,
        .amcanorderbyop = true,
        .amcanhash = false,
        .amconsistentequality = false,
        .amconsistentordering = false,
        .amcanbackward = false, /* can change direction mid-scan */
        .amcanunique = false,
        .amcanmulticol = false,
        .amoptionalkey = true,
        .amsearcharray = false,
        .amsearchnulls = false,
        .amstorage = false,
        .amclusterable = false,
        .ampredlocks = false,
        .amcanparallel = false,
        .amcanbuildparallel = true,
        .amcaninclude = false,
        .amusemaintenanceworkmem = false, /* not used during VACUUM */
        .amsummarizing = false,
        .amparallelvacuumoptions = VACUUM_OPTION_PARALLEL_BULKDEL,
        .amkeytype = InvalidOid,
        .ambuild = ivfflatbuild,
        .ambuildempty = ivfflatbuildempty,
        .aminsert = ivfflatinsert,
        .aminsertcleanup = NULL,
        .ambulkdelete = ivfflatbulkdelete,
        .amvacuumcleanup = ivfflatvacuumcleanup,
        .amcanreturn = NULL,    /* tuple not included in heapsort */
        .amcostestimate = ivfflatcostestimate,
        .amgettreeheight = NULL,
        .amoptions = ivfflatoptions,
        .amproperty = NULL, /* TODO AMPROP_DISTANCE_ORDERABLE */
        .ambuildphasename = ivfflatbuildphasename,
        .amvalidate = ivfflatvalidate,
        .amadjustmembers = NULL,
        .ambeginscan = ivfflatbeginscan,
        .amrescan = ivfflatrescan,
        .amgettuple = ivfflatgettuple,
        .amgetbitmap = NULL,
        .amendscan = ivfflatendscan,
        .ammarkpos = NULL,
        .amrestrpos = NULL,
        .amestimateparallelscan = NULL,
        .aminitparallelscan = NULL,
        .amparallelrescan = NULL,
        .amtranslatestrategy = NULL,
        .amtranslatecmptype = NULL,
    };
 
    PG_RETURN_POINTER(&amroutine);
}