/* * DBMS_VECTOR shared index mapping (see dbms_vector_index_map.hpp). */ #include "dbms_vector_index_map.hpp" #include "dbms_vector_common.hpp" #include #include 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; }