Исходный код СУБД 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
/*
 * DBMS_VECTOR shared index mapping (see dbms_vector_index_map.hpp).
 */
 
#include "dbms_vector_index_map.hpp"
#include "dbms_vector_common.hpp"
 
#include <cstring>
#include <string>
 
extern "C"
{
 
#include "catalog/pg_type.h"
#include "executor/spi.h"
#include "fmgr.h"
#include "utils/builtins.h"
 
} // extern "C"
 
/*
 * Extract an integer idx_parameters key; a present non-numeric or
 * non-integer value is the ORA-20003 parity error (the access method
 * validates the value ranges through its reloptions).
 */
static int32_t
dbms_vector_index_int_param(Jsonb *idx_parameters, const char *key,
                            const char *param_name, bool &present)
{
    present = false;
 
    if (idx_parameters == nullptr)
        return 0;
 
    JsonbValue buffer;
    JsonbValue *found = dbms_vector_getobjectfield(&idx_parameters->root,
                                                   key, &buffer);
    if (found == nullptr || found->type == jbvNull)
        return 0;
 
    if (found->type != jbvNumeric)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("invalid value for %s parameter", param_name),
                 errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR).")));
 
    int32_t value;
 
    PG_TRY();
    {
        value = DatumGetInt32(DirectFunctionCall1(
            numeric_int4, NumericGetDatum(found->val.numeric)));
    }
    PG_CATCH();
    {
        FlushErrorState();
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("invalid value for %s parameter", param_name),
                 errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR).")));
    }
    PG_END_TRY();
 
    present = true;
    return value;
}
 
/*
 * Distance metric (case-insensitive) to the vector operator class of the
 * chosen access method (pls:584-589).  HAMMING exists only for bit vectors
 * and L2_SQUARED/EUCLIDEAN_SQUARED only for exact scans, so neither can
 * back an index; MANHATTAN has an operator class for hnsw only.
 */
static std::string
dbms_vector_index_opclass(const std::string &metric,
                          const std::string &am)
{
    if (metric == "HAMMING")
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("Distance metric - HAMMING - is supported only for "
                        "bit vectors"),
                 errhint("Bit vector distances are outside the scope of "
                         "this port.")));
 
    if (metric == "L2_SQUARED" || metric == "EUCLIDEAN_SQUARED")
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("Distance metric - %s - is an exact-scan metric "
                        "and cannot be used for a vector index",
                        metric.c_str()),
                 errhint("Use EUCLIDEAN; the engine applies the squared "
                         "form internally.")));
 
    if (metric != "EUCLIDEAN" && metric != "COSINE" && metric != "DOT" &&
        metric != "MANHATTAN")
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("Distance metric - %s - is not a valid option",
                        metric.c_str()),
                 errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR).")));
 
    std::string opclass;
 
    if (metric == "EUCLIDEAN")
        opclass = "vector_l2_ops";
    else if (metric == "COSINE")
        opclass = "vector_cosine_ops";
    else if (metric == "DOT")
        opclass = "vector_ip_ops";
    else
        opclass = "vector_l1_ops";
 
    if (opclass == "vector_l1_ops" && am != "hnsw")
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("Distance metric - MANHATTAN - is not supported by "
                        "the %s access method",
                        am.c_str()),
                 errhint("The MANHATTAN operator class exists for hnsw "
                         "indexes only.")));
 
    return opclass;
}
 
DbmsVectorIndexMapping
dbms_vector_index_map(const char *idx_organization,
                      const char *idx_distance_metric, Jsonb *idx_parameters)
{
    std::string organization = dbms_vector_ascii_upper(
        idx_organization == nullptr ? "" : idx_organization);
 
    DbmsVectorIndexMapping mapping;
 
    if (organization == DBMS_VECTOR_IDX_ORG_HNSW)
        mapping.am = "hnsw";
    else if (organization == DBMS_VECTOR_IDX_ORG_IVF)
        mapping.am = "ivfflat";
    else
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("Organization - %s - is not a valid option",
                        organization.c_str()),
                 errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR).")));
 
    std::string metric = dbms_vector_ascii_upper(
        idx_distance_metric == nullptr || idx_distance_metric[0] == '\0'
            ? "EUCLIDEAN" : idx_distance_metric);
 
    mapping.opclass = dbms_vector_index_opclass(metric, mapping.am);
 
    if (idx_parameters != nullptr &&
        !JsonContainerIsObject(&idx_parameters->root))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("idx_parameters must be a JSON object"),
                 errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR).")));
 
    std::string idx_type;
 
    if (idx_parameters != nullptr)
    {
        if (!dbms_vector_param_string(&idx_parameters->root, "type", "TYPE",
                                      idx_type))
            idx_type.clear();
        idx_type = dbms_vector_ascii_upper(idx_type);
    }
 
    if (idx_type == "HNSW")
    {
        bool present = false;
        int32_t value;
 
        value = dbms_vector_index_int_param(idx_parameters, "neighbors",
                                            "NEIGHBORS", present);
        if (present)
            mapping.m = value;
 
        value = dbms_vector_index_int_param(idx_parameters,
                                            "efConstruction",
                                            "EFCONSTRUCTION", present);
        if (present)
            mapping.ef_construction = value;
    }
    else if (idx_type == "IVF")
    {
        bool present = false;
        int32_t value;
 
        value = dbms_vector_index_int_param(idx_parameters, "partitions",
                                            "PARTITIONS", present);
        if (present)
            mapping.lists = value;
    }
    else
    {
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("Index type - %s - is not a valid option",
                        idx_type.c_str()),
                 errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR).")));
    }
 
    /*
     * The organization and the idx_parameters type must name the same
     * engine: a NEIGHBOR PARTITIONS organization with type HNSW (or the
     * other way round) is a contradiction Oracle never builds.
     */
    if (mapping.am == "hnsw" && idx_type == "IVF")
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("Index type - IVF - does not match the "
                        "organization %s",
                        organization.c_str()),
                 errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR).")));
 
    if (mapping.am == "ivfflat" && idx_type == "HNSW")
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("Index type - HNSW - does not match the "
                        "organization %s",
                        organization.c_str()),
                 errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR).")));
 
    return mapping;
}
 
std::string
dbms_vector_index_reloptions_clause(const DbmsVectorIndexMapping &mapping)
{
    std::string clause;
 
    if (mapping.am == "hnsw")
    {
        if (mapping.m != 0)
        {
            if (!clause.empty())
                clause += ", ";
            clause += "m=" + std::to_string(mapping.m);
        }
        if (mapping.ef_construction != 0)
        {
            if (!clause.empty())
                clause += ", ";
            clause += "ef_construction=" +
                std::to_string(mapping.ef_construction);
        }
    }
    else if (mapping.am == "ivfflat" && mapping.lists != 0)
        clause = "lists=" + std::to_string(mapping.lists);
 
    return clause;
}
 
void
dbms_vector_index_check_partitioning(const char *idx_partitioning_scheme)
{
    if (idx_partitioning_scheme == nullptr ||
        idx_partitioning_scheme[0] == '\0')
        return;
 
    std::string scheme = dbms_vector_ascii_upper(idx_partitioning_scheme);
 
    if (scheme == "GLOBAL")
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("Partitioning scheme - GLOBAL - is not a valid "
                        "option"),
                 errdetail("RuDB has no Oracle index partitioning; only "
                           "LOCAL (the default) is supported.")));
 
    if (scheme != "LOCAL")
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("Partitioning scheme - %s - is not a valid option",
                        scheme.c_str()),
                 errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR).")));
}
 
bool
dbms_vector_index_lookup(const char *idx_name, DbmsVectorIndexRef &ref)
{
    if (idx_name == nullptr || idx_name[0] == '\0')
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_NAME),
                 errmsg("index name must be specified")));
 
    static const char *sql =
        "SELECT c.oid, i.indrelid, a.amname::text, i.indisvalid, "
        "COALESCE(c.reloptions, '{}'::text[]), "
        "t.relname::text, att.attname::text, oc.opcname::text "
        "FROM pg_index i "
        "JOIN pg_class c ON c.oid = i.indexrelid "
        "JOIN pg_am a ON a.oid = c.relam "
        "JOIN pg_class t ON t.oid = i.indrelid "
        "JOIN pg_attribute att ON att.attrelid = i.indrelid "
        "                    AND att.attnum = i.indkey[0] "
        "JOIN pg_opclass oc ON oc.oid = i.indclass[0] "
        "WHERE c.oid = to_regclass($1)";
    Oid argtypes[1] = {TEXTOID};
    Datum values[1];
    char nulls[1] = {' '};
 
    values[0] = CStringGetTextDatum(idx_name);
 
    SPI_connect();
 
    bool found = false;
 
    PG_TRY();
    {
        int rc = SPI_execute_with_args(sql, 1, argtypes, values, nulls,
                                       true, 1);
        if (rc != SPI_OK_SELECT)
            ereport(ERROR,
                    (errmsg("SPI_execute_with_args failed: %s (rc=%d)",
                            SPI_result_code_string(rc), rc)));
 
        if (SPI_processed == 0)
        {
            /*
             * Distinguish "nothing by that name" from "the name resolves to
             * a non-index object" so the caller sees an honest error.
             */
            static const char *probe =
                "SELECT to_regclass($1) IS NOT NULL";
            int prc = SPI_execute_with_args(probe, 1, argtypes, values,
                                            nulls, true, 1);
            if (prc != SPI_OK_SELECT)
                ereport(ERROR,
                        (errmsg("SPI_execute_with_args failed: %s (rc=%d)",
                                SPI_result_code_string(prc), prc)));
 
            bool resolves_isnull = false;
            Datum resolves = SPI_getbinval(SPI_tuptable->vals[0],
                                           SPI_tuptable->tupdesc, 1,
                                           &resolves_isnull);
 
            if (!resolves_isnull && DatumGetBool(resolves))
                ereport(ERROR,
                        (errcode(ERRCODE_UNDEFINED_OBJECT),
                         errmsg("%s is not an index", idx_name),
                         errdetail("Oracle error: ORA-20003 "
                                   "(EXCP_GU_ERR).")));
        }
        else
        {
            bool isnull = false;
 
            ref.indexrelid = DatumGetObjectId(
                SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc,
                              1, &isnull));
            ref.indrelid = DatumGetObjectId(
                SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc,
                              2, &isnull));
 
            const char *amname = TextDatumGetCString(
                SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc,
                              3, &isnull));
            ref.am = amname;
 
            ref.indisvalid = DatumGetBool(
                SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc,
                              4, &isnull));
 
            Datum reloptions = SPI_getbinval(SPI_tuptable->vals[0],
                                             SPI_tuptable->tupdesc, 5,
                                             &isnull);
            ref.reloptions.clear();
            if (!isnull)
            {
                ArrayType *array = DatumGetArrayTypeP(reloptions);
                Datum *elements = nullptr;
                bool *element_nulls = nullptr;
                int nelems = 0;
 
                deconstruct_array(array, TEXTOID, -1, false, TYPALIGN_INT,
                                  &elements, &element_nulls, &nelems);
 
                for (int i = 0; i < nelems; i++)
                    if (!element_nulls[i])
                        ref.reloptions.push_back(
                            text_to_cstring((text *) elements[i]));
            }
 
            if (ref.am != "hnsw" && ref.am != "ivfflat")
                ereport(ERROR,
                        (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                         errmsg("index %s is not a vector index", idx_name),
                         errdetail("Oracle error: ORA-20003 "
                                   "(EXCP_GU_ERR).")));
 
            const char *table_name = TextDatumGetCString(
                SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc,
                              6, &isnull));
            ref.table_name = table_name;
 
            const char *column_name = TextDatumGetCString(
                SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc,
                              7, &isnull));
            ref.column_name = column_name;
 
            const char *opclass = TextDatumGetCString(
                SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc,
                              8, &isnull));
            ref.opclass = opclass;
 
            found = true;
        }
    }
    PG_FINALLY();
    {
        SPI_finish();
    }
    PG_END_TRY();
 
    return found;
}