#include "dbms_vector.hpp" #include "dbms_vector_onnx.hpp" #include "dbms_vector_common.hpp" #include "dbms_vector_index_map.hpp" #include "dbms_vector_rest.hpp" #include "dbms_vector_text.hpp" #include "dbms_lob/dbms_lob_bfile.hpp" #include #include #include #include /* * DBMS_VECTOR: CREATE_CREDENTIAL / DROP_CREDENTIAL, * LOAD_ONNX_MODEL / DROP_ONNX_MODEL, the REST embedding core with * UTL_TO_EMBEDDING and UTL_TO_EMBEDDINGS, and QUERY. * * Port of the Oracle 23ai SYS.DBMS_VECTOR subset to RuDB. This file owns the * C entry points for the whole package; the catalog storage it relies on is * created by rudb_vector.sql (SYS.vector_models / SYS.vector_credentials). * * Port notes (credentials): params are stored verbatim, secrets included, * exactly like Oracle DBMS_CREDENTIAL (form precedence of the non-cloud * CREATE_CREDENTIAL branch, pls:1290-1362: username+password, then * access_token, then the OCI user_ocid/tenancy_ocid/private_key/fingerprint * form). Documented deviations: secrets rest in plaintext in the restricted * SYS.vector_credentials table, and the SQL boundary (GET_CREDENTIAL, * SYS.all_vector_credentials) redacts password/access_token/private_key * values to "***" where Oracle never exposes credentials at all. * * LOAD_ONNX_MODEL / DROP_ONNX_MODEL manage catalog storage. On servers built * with --with-onnxruntime the model bytes are validated at LOAD time through * the runtime (protobuf parse + embedding contract: a string input, i.e. the * tokenizer fused into the graph, and a float output - Oracle IMPORT_ONNX_MODEL * parity); without the runtime the storage-only behavior remains. * * The REST core speaks the OpenAI embeddings protocol only (covers OpenAI, * Azure OpenAI, vLLM, Ollama gateways via `url`). Unrecognized params keys * are passed through into the request body (REMOVE_ORACLE_KEYS analog). * provider:'database' runs local ONNX inference over the model named by the * `model` param (dbms_vector_onnx.cpp) when the server is built with * --with-onnxruntime, and raises the deferred-inference error otherwise. * Inference creates a session per call (no session cache - documented, * accepted cost; models are re-read from the catalog, so LOAD/DROP behave * correctly across backends). * * UTL_TO_EMBEDDINGS wraps the REST core. The CLOB overload is wrapped as a * single chunk (exact Oracle parity, pls:1882-1928); the array overload splits * the chunks into batches of batch_size (default 50) and zips the provider * answers into {"embed_id":...,"embed_data":...,"embed_vector":"[...]"} * elements (pls:1930-1986). embed_vector keeps the vector text form so * callers can cast it with ::vector. * * QUERY is dynamic SQL over the in-core vector distance operators (<->, <=>, * <#>, <+> and vector_l2_squared_distance()), with all values bound through * SPI (pls:827-995). use_index=false forces an exact scan (SET LOCAL * enable_indexscan/indexonlyscan = off); efsearch and "neighbor partition * probes" from idx_parameters map to hnsw.ef_search / ivfflat.probes around * the query (approximation of the Oracle WITH TARGET ACCURACY clauses); * accuracy is logged and otherwise ignored (documented deviation: the engine * has no target-accuracy equivalent). */ extern "C" { #include "catalog/pg_type.h" #include "utils/builtins.h" #include "utils/elog.h" #include "utils/memutils.h" #include "utils/resowner.h" #include "utils/jsonb.h" #include "utils/array.h" #include "utils/lsyscache.h" #include "executor/spi.h" #include "miscadmin.h" #include "storage/fd.h" #include "funcapi.h" PG_FUNCTION_INFO_V1(dbms_vector_utl_to_embedding); PG_FUNCTION_INFO_V1(dbms_vector_utl_to_embeddings); PG_FUNCTION_INFO_V1(dbms_vector_utl_to_embeddings_array); PG_FUNCTION_INFO_V1(dbms_vector_query); PG_FUNCTION_INFO_V1(dbms_vector_query_text); PG_FUNCTION_INFO_V1(dbms_vector_load_onnx_model_dir); PG_FUNCTION_INFO_V1(dbms_vector_load_onnx_model); PG_FUNCTION_INFO_V1(dbms_vector_drop_onnx_model); PG_FUNCTION_INFO_V1(dbms_vector_create_credential); PG_FUNCTION_INFO_V1(dbms_vector_drop_credential); PG_FUNCTION_INFO_V1(dbms_vector_get_credential); PG_FUNCTION_INFO_V1(dbms_vector_onnx_enabled); // Contract-phase stubs (see the stub bodies near the end of the file) PG_FUNCTION_INFO_V1(dbms_vector_utl_to_chunks); PG_FUNCTION_INFO_V1(dbms_vector_utl_to_chunks_1); PG_FUNCTION_INFO_V1(dbms_vector_utl_to_generate_text); PG_FUNCTION_INFO_V1(dbms_vector_create_index); PG_FUNCTION_INFO_V1(dbms_vector_rebuild_index); PG_FUNCTION_INFO_V1(dbms_vector_get_index_status); PG_FUNCTION_INFO_V1(dbms_vector_index_vector_memory_advisor); PG_FUNCTION_INFO_V1(dbms_vector_inmemory_onnx_model); PG_FUNCTION_INFO_V1(dbms_vector_enable_checkpoint); PG_FUNCTION_INFO_V1(dbms_vector_disable_checkpoint); /// Oracle DEFAULT_BATCH_SIZE := 50 (pls:274). #define DBMS_VECTOR_DEFAULT_BATCH_SIZE 50 /* * Максимальный размер загружаемой ONNX-модели (настраиваемая константа). * На сборках с onnxruntime protobuf-валидация выполняется при загрузке. */ #define DBMS_VECTOR_ONNX_MAX_BYTES (64 * 1024 * 1024) /// Метаданные ONNX-модели по умолчанию (паритет Oracle IMPORT_ONNX_MODEL). static const char *DBMS_VECTOR_ONNX_DEFAULT_METADATA = "{\"function\": \"embedding\", \"embeddingOutput\": \"embedding\", " "\"input\": {\"input\": [\"DATA\"]}}"; } // extern "C" /* * Cluster-wide default of the vector index build checkpointing (see * dbms_vector.hpp); the value lives in the * dbms_vector.vector_index_checkpointing GUC. */ bool dbms_vector_vector_index_checkpointing = true; // --------------------------------------------------------------------------- // Credential internals: jsonb params access (helpers mirror dbms_json.cpp usage) // --------------------------------------------------------------------------- /* * Split a possibly qualified "OWNER.NAME" reference: credentials, models * (helpers live in dbms_vector_common.hpp). */ // --------------------------------------------------------------------------- // LOAD_ONNX_MODEL / DROP_ONNX_MODEL internals (catalog storage + validation) // --------------------------------------------------------------------------- /* * Validate and resolve a model name, honoring OWNER.NAME qualification. * Only the current user (or a superuser) may act as the row owner. */ static void dbms_vector_resolve_model_name(const char *model_name, std::string &owner, std::string &name) { if (model_name == nullptr || model_name[0] == '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("model name must be specified"))); dbms_vector_parse_qualified_name(model_name, owner, name); dbms_vector_check_simple_name(name, "model name"); if (strchr(model_name, '.') != nullptr) dbms_vector_check_simple_name(owner, "model owner"); if (owner != GetUserNameFromId(GetUserId(), false) && !superuser()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("model owner must be the current user: %s", owner.c_str()))); } /* * Basic ONNX data checks (non-empty, size guard). The real validation - * protobuf parse + embedding contract - runs in dbms_vector_store_model via * dbms_vector_onnx_validate on --with-onnxruntime builds; without the * runtime these basic checks are all there is (approved deviation). */ static bytea * dbms_vector_check_model_data(bytea *model_data) { if (model_data == nullptr) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("ONNX model data must be specified"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); int32 size = VARSIZE_ANY_EXHDR(model_data); if (size == 0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("ONNX model data must not be empty"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); if (size > DBMS_VECTOR_ONNX_MAX_BYTES) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("ONNX model exceeds the maximum supported size of %d bytes", DBMS_VECTOR_ONNX_MAX_BYTES), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."), errhint("The limit is a tunable constant " "(DBMS_VECTOR_ONNX_MAX_BYTES) in this port."))); return model_data; } /* * Validate the metadata param; NULL falls back to the Oracle default * {"function":"embedding","embeddingOutput":"embedding", * "input":{"input":["DATA"]}}. */ static Jsonb * dbms_vector_check_model_metadata(Jsonb *metadata) { if (metadata == nullptr) return DatumGetJsonbP(DirectFunctionCall1( jsonb_in, CStringGetDatum(DBMS_VECTOR_ONNX_DEFAULT_METADATA))); if (!JsonContainerIsObject(&metadata->root)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("metadata must be a JSON object"))); return metadata; } /* * File-name safety checks mirroring bfile_filename_is_safe: non-empty, * no leading '/' and no '..' path component. */ static bool dbms_vector_filename_is_safe(const std::string &filename) { if (filename.empty() || filename[0] == '/') return false; size_t start = 0; while (start <= filename.size()) { size_t slash = filename.find('/', start); size_t len = (slash == std::string::npos) ? filename.size() - start : slash - start; if (len == 2 && filename.compare(start, 2, "..") == 0) return false; if (slash == std::string::npos) break; start = slash + 1; } return true; } /* * Check that the model file exists on the server as a regular readable * file and return its stat (same safety checks as the BFILE code: no '..'). */ static struct stat dbms_vector_stat_model_file(const std::string &path) { if (path.empty() || path.find("..") != std::string::npos) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("model file path must not be empty or contain '..': %s", path.empty() ? "(empty)" : path.c_str()))); struct stat st; if (stat(path.c_str(), &st) != 0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("model file not found on the server: %s", path.c_str()), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); if (!S_ISREG(st.st_mode)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("model file is not a regular file: %s", path.c_str()), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); return st; } /* * Read the whole model file into a bytea (size already validated against * DBMS_VECTOR_ONNX_MAX_BYTES via the stat). */ static bytea * dbms_vector_read_model_file(const std::string &path, const struct stat &st) { if (st.st_size == 0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("ONNX model data must not be empty"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); if (st.st_size > (off_t) DBMS_VECTOR_ONNX_MAX_BYTES) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("ONNX model exceeds the maximum supported size of %d bytes", DBMS_VECTOR_ONNX_MAX_BYTES), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."), errhint("The limit is a tunable constant " "(DBMS_VECTOR_ONNX_MAX_BYTES) in this port."))); FILE *file = AllocateFile(path.c_str(), PG_BINARY_R); if (file == nullptr) ereport(ERROR, (errcode_for_file_access(), errmsg("could not open model file \"%s\": %m", path.c_str()))); bytea *data = (bytea *) palloc(VARHDRSZ + st.st_size); if (fread(VARDATA(data), 1, st.st_size, file) != (size_t) st.st_size) { FreeFile(file); ereport(ERROR, (errcode_for_file_access(), errmsg("could not read model file \"%s\": %m", path.c_str()))); } FreeFile(file); SET_VARSIZE(data, VARHDRSZ + st.st_size); return data; } /* * Shared insert path of both LOAD_ONNX_MODEL overloads: validate the model * with the runtime (real protobuf parse + embedding contract on * --with-onnxruntime builds; a no-op otherwise), reject duplicates * (matching Oracle IMPORT_ONNX_MODEL) and insert the row. */ static void dbms_vector_store_model(const std::string &owner, const std::string &name, bytea *model_data, Jsonb *metadata) { dbms_vector_onnx_validate(model_data, metadata); SPI_connect(); PG_TRY(); { { static const char *sql = "SELECT 1 FROM \"SYS\".vector_models " "WHERE owner = $1 AND model_name = $2"; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner.c_str()); values[1] = CStringGetTextDatum(name.c_str()); int rc = SPI_execute_with_args(sql, 2, 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) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("model %s already exists", name.c_str()), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); } { static const char *sql = "INSERT INTO \"SYS\".vector_models " "(owner, model_name, model_data, metadata) " "VALUES ($1, $2, $3, $4)"; Oid argtypes[4] = {TEXTOID, TEXTOID, BYTEAOID, JSONBOID}; Datum values[4]; char nulls[4] = {' ', ' ', ' ', ' '}; values[0] = CStringGetTextDatum(owner.c_str()); values[1] = CStringGetTextDatum(name.c_str()); values[2] = PointerGetDatum(model_data); values[3] = JsonbPGetDatum(metadata); int rc = SPI_execute_with_args(sql, 4, argtypes, values, nulls, false, 1); if (rc != SPI_OK_INSERT) ereport(ERROR, (errmsg("SPI_execute_with_args failed: %s (rc=%d)", SPI_result_code_string(rc), rc))); } } PG_FINALLY(); { SPI_finish(); } PG_END_TRY(); } /* * Internal helper (static - not exposed in pg_proc): resolve a model * name, honoring the OWNER.NAME qualification rules and the * owner-or-superuser access rule, and return the stored model bytes and * metadata jsonb (copies allocated in the caller's memory context). * Consumed by the local ONNX inference path (provider 'database'). */ static void dbms_vector_lookup_model(const char *model_name, bytea *&model_data, Jsonb *&metadata, std::string *resolved_owner = nullptr, std::string *resolved_name = nullptr) { std::string owner; std::string name; dbms_vector_resolve_model_name(model_name, owner, name); SPI_connect(); model_data = nullptr; metadata = nullptr; PG_TRY(); { static const char *sql = "SELECT owner, model_data, metadata FROM \"SYS\".vector_models " "WHERE owner = $1 AND model_name = $2"; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner.c_str()); values[1] = CStringGetTextDatum(name.c_str()); int rc = SPI_execute_with_args(sql, 2, 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) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("model %s does not exist", name.c_str()), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); bool owner_isnull = false; bool data_isnull = false; bool metadata_isnull = false; Datum owner_datum = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &owner_isnull); Datum data_datum = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &data_isnull); Datum metadata_datum = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 3, &metadata_isnull); if (data_isnull) ereport(ERROR, (errmsg("model_data is NULL for model %s", name.c_str()))); if (metadata_isnull) ereport(ERROR, (errmsg("metadata is NULL for model %s", name.c_str()))); const char *row_owner = owner_isnull ? "" : TextDatumGetCString(owner_datum); if (strcmp(row_owner, GetUserNameFromId(GetUserId(), false)) != 0 && !superuser()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("permission denied for model %s", name.c_str()))); /* * Detoast before copying: values in heap tuples may use the short * 1-byte varlena header, which is unusable as bytea / Jsonb. */ bytea *data = DatumGetByteaP(data_datum); model_data = (bytea *) SPI_palloc(VARSIZE(data)); memcpy(model_data, data, VARSIZE(data)); Jsonb *stored_metadata = DatumGetJsonbP(metadata_datum); metadata = (Jsonb *) SPI_palloc(VARSIZE(stored_metadata)); memcpy(metadata, stored_metadata, VARSIZE(stored_metadata)); if (resolved_owner != nullptr) *resolved_owner = owner; if (resolved_name != nullptr) *resolved_name = name; } PG_FINALLY(); { SPI_finish(); } PG_END_TRY(); } /* * Fetch a secret field of the detected form: it must be a non-empty string * (Oracle '' IS NULL); anything else is the ORA-20003 parity error. */ static void dbms_vector_get_credential_string(JsonbContainer *container, const char *key, const char *param_name, std::string &out) { JsonbValue buffer; JsonbValue *found = dbms_vector_getobjectfield(container, key, &buffer); if (found == nullptr || found->type != jbvString || found->val.string.len == 0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value for %s parameter", param_name), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); out.assign(found->val.string.val, found->val.string.len); } /* * Validate the credential params of CREATE_CREDENTIAL: one of the Oracle * forms must be recognizable, with every secret field a non-empty string. * Unknown keys (provider, comment, compartment_ocid, ...) pass through * unvalidated and are stored as-is. */ static void dbms_vector_validate_credential_params(JsonbContainer *container) { std::string value; switch (dbms_vector_credential_form(container)) { case DBMS_VECTOR_CRED_USERPASS: dbms_vector_get_credential_string(container, "username", "USERNAME", value); dbms_vector_get_credential_string(container, "password", "PASSWORD", value); return; case DBMS_VECTOR_CRED_TOKEN: dbms_vector_get_credential_string(container, "access_token", "ACCESS_TOKEN", value); return; case DBMS_VECTOR_CRED_OCI: dbms_vector_get_credential_string(container, "user_ocid", "USER_OCID", value); dbms_vector_get_credential_string(container, "tenancy_ocid", "TENANCY_OCID", value); dbms_vector_get_credential_string(container, "private_key", "PRIVATE_KEY", value); dbms_vector_get_credential_string(container, "fingerprint", "FINGERPRINT", value); return; default: break; } if (dbms_vector_haskey(container, "username") || dbms_vector_haskey(container, "password")) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("username and password must be specified together"))); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("params must specify one of: username+password, " "access_token, or " "user_ocid+tenancy_ocid+private_key+fingerprint"))); } /* * Redact the secret values of the stored credential params for the SQL * boundary: password, access_token and private_key become "***" * (username/tenancy_ocid/compartment_ocid/fingerprint are identifiers and * stay visible; Oracle never exposes stored credentials at all). */ static Jsonb * dbms_vector_redact_credential_params(Jsonb *params) { static const char *secrets[] = {"password", "access_token", "private_key"}; JsonbInState state; JsonbValue key; JsonbValue value; JsonbValue redacted; memset(&state, 0, sizeof(state)); memset(&key, 0, sizeof(key)); memset(&value, 0, sizeof(value)); memset(&redacted, 0, sizeof(redacted)); pushJsonbValue(&state, WJB_BEGIN_OBJECT, nullptr); JsonbIterator *iterator = JsonbIteratorInit(¶ms->root); JsonbIteratorToken token; while ((token = JsonbIteratorNext(&iterator, &key, true)) != WJB_DONE) { if (token != WJB_KEY) continue; if (JsonbIteratorNext(&iterator, &value, true) != WJB_VALUE) break; /* malformed object; jsonb guarantees a value next */ bool is_secret = false; if (key.type == jbvString) for (const char *candidate : secrets) if ((int) strlen(candidate) == key.val.string.len && strncmp(candidate, key.val.string.val, key.val.string.len) == 0) is_secret = true; pushJsonbValue(&state, WJB_KEY, &key); if (is_secret) { redacted.type = jbvString; redacted.val.string.val = (char *) "***"; redacted.val.string.len = strlen("***"); pushJsonbValue(&state, WJB_VALUE, &redacted); } else pushJsonbValue(&state, WJB_VALUE, &value); } pushJsonbValue(&state, WJB_END_OBJECT, nullptr); return JsonbValueToJsonb(state.result); } /* * CREATE_CREDENTIAL core (public C++ API, see dbms_vector.hpp): validate the * qualified name and the params (Oracle forms, pls:1276-1367), then insert * the credential into SYS.vector_credentials with the params stored verbatim * (secrets included; the SQL boundary redacts them on output). params may * not be nullptr (SQL NULL). Duplicate names are rejected, matching Oracle * DBMS_CREDENTIAL. */ void dbms_vector_credential_create(const std::string &credential_name, Jsonb *params) { if (credential_name.empty()) ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("credential name must be specified"))); std::string owner; std::string name; dbms_vector_parse_qualified_name(credential_name.c_str(), owner, name); dbms_vector_check_simple_name(name, "credential name"); if (credential_name.find('.') != std::string::npos) dbms_vector_check_simple_name(owner, "credential owner"); /* * Oracle allows creating credentials only in the caller's own schema * (DBMS_CREDENTIAL.CREATE_CREDENTIAL uses the current user); reject an * explicit foreign owner early. */ if (owner != GetUserNameFromId(GetUserId(), false) && !superuser()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("credential owner must be the current user: %s", owner.c_str()))); if (params == nullptr) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("params must be a JSON object with authentication " "parameters"))); JsonbContainer *container = ¶ms->root; if (!JsonContainerIsObject(container)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("params must be a JSON object"))); dbms_vector_validate_credential_params(container); SPI_connect(); PG_TRY(); { { static const char *sql = "SELECT 1 FROM \"SYS\".vector_credentials " "WHERE owner = $1 AND credential_name = $2"; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner.c_str()); values[1] = CStringGetTextDatum(name.c_str()); int rc = SPI_execute_with_args(sql, 2, 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) ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("credential %s already exists", name.c_str()))); } { static const char *sql = "INSERT INTO \"SYS\".vector_credentials " "(owner, credential_name, params) VALUES ($1, $2, $3)"; Oid argtypes[3] = {TEXTOID, TEXTOID, JSONBOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; values[0] = CStringGetTextDatum(owner.c_str()); values[1] = CStringGetTextDatum(name.c_str()); values[2] = JsonbPGetDatum(params); int rc = SPI_execute_with_args(sql, 3, argtypes, values, nulls, false, 1); if (rc != SPI_OK_INSERT) ereport(ERROR, (errmsg("SPI_execute_with_args failed: %s (rc=%d)", SPI_result_code_string(rc), rc))); } } PG_FINALLY(); { SPI_finish(); } PG_END_TRY(); } /* * DROP_CREDENTIAL core (public C++ API, see dbms_vector.hpp): validate the * qualified name and delete the row from SYS.vector_credentials; a missing * credential raises the ORA-20001 (EXCP_CRED_NOT_EXIST) analog. */ void dbms_vector_credential_drop(const std::string &credential_name) { if (credential_name.empty()) ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("credential name must be specified"))); std::string owner; std::string name; dbms_vector_parse_qualified_name(credential_name.c_str(), owner, name); dbms_vector_check_simple_name(name, "credential name"); if (credential_name.find('.') != std::string::npos) dbms_vector_check_simple_name(owner, "credential owner"); if (owner != GetUserNameFromId(GetUserId(), false) && !superuser()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("credential owner must be the current user: %s", owner.c_str()))); SPI_connect(); PG_TRY(); { static const char *sql = "DELETE FROM \"SYS\".vector_credentials " "WHERE owner = $1 AND credential_name = $2"; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner.c_str()); values[1] = CStringGetTextDatum(name.c_str()); int rc = SPI_execute_with_args(sql, 2, argtypes, values, nulls, false, 1); if (rc != SPI_OK_DELETE) ereport(ERROR, (errmsg("SPI_execute_with_args failed: %s (rc=%d)", SPI_result_code_string(rc), rc))); if (SPI_processed == 0) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("credential %s does not exist", name.c_str()), errdetail("Oracle error: ORA-20001 (EXCP_CRED_NOT_EXIST)."))); } PG_FINALLY(); { SPI_finish(); } PG_END_TRY(); } // --------------------------------------------------------------------------- // REST core + UTL_TO_EMBEDDING internals (openai protocol); the transport // itself lives in dbms_vector_rest.cpp // --------------------------------------------------------------------------- /* * Build the openai-protocol request body * {"input":[...],"model":...,...passthrough} through the core jsonb C API. * Unrecognized params keys are forwarded verbatim (REMOVE_ORACLE_KEYS * analog); building via jsonb gives correct JSON escaping for free. */ static char * dbms_vector_build_openai_body(const std::vector &inputs, const std::string &model, Jsonb *params) { JsonbInState state; JsonbValue value; memset(&state, 0, sizeof(state)); memset(&value, 0, sizeof(value)); pushJsonbValue(&state, WJB_BEGIN_OBJECT, nullptr); value.type = jbvString; value.val.string.val = (char *) "input"; value.val.string.len = strlen("input"); pushJsonbValue(&state, WJB_KEY, &value); pushJsonbValue(&state, WJB_BEGIN_ARRAY, nullptr); for (const std::string &input : inputs) { value.type = jbvString; value.val.string.val = (char *) input.c_str(); value.val.string.len = input.size(); pushJsonbValue(&state, WJB_ELEM, &value); } pushJsonbValue(&state, WJB_END_ARRAY, nullptr); value.type = jbvString; value.val.string.val = (char *) "model"; value.val.string.len = strlen("model"); pushJsonbValue(&state, WJB_KEY, &value); value.type = jbvString; value.val.string.val = (char *) model.c_str(); value.val.string.len = model.size(); pushJsonbValue(&state, WJB_VALUE, &value); dbms_vector_rest_push_passthrough(&state, params); pushJsonbValue(&state, WJB_END_OBJECT, nullptr); Jsonb *body = JsonbValueToJsonb(state.result); return JsonbToCString(nullptr, &body->root, 0); } /* * Convert one embedding array of the openai response into the vector text * form "[%.8g,...]" (embed.c:90-99 pattern). */ static std::string dbms_vector_embedding_array_to_text(JsonbValue *embedding) { if (embedding == nullptr || embedding->type != jbvBinary || !JsonContainerIsArray(embedding->val.binary.data)) return std::string(); JsonbContainer *container = embedding->val.binary.data; uint32_t count = JsonContainerSize(container); StringInfoData buf; initStringInfo(&buf); appendStringInfoChar(&buf, '['); for (uint32_t i = 0; i < count; i++) { JsonbValue *element = getIthJsonbValueFromContainer(container, i); if (element == nullptr || element->type != jbvNumeric) { pfree(buf.data); return std::string(); } float coordinate = DatumGetFloat4(DirectFunctionCall1( numeric_float4, NumericGetDatum(element->val.numeric))); if (i > 0) appendStringInfoChar(&buf, ','); appendStringInfo(&buf, "%.8g", coordinate); } appendStringInfoChar(&buf, ']'); std::string result(buf.data, buf.len); pfree(buf.data); return result; } /* * Extract $.data[i].embedding for every input from the provider response. * When no embedding is present the provider error is raised * (EXCP_PROVIDER_ERR -20002 parity, pls:2352-2355). */ static std::vector dbms_vector_parse_embedding_response(const DbmsVectorRestResponse &response, size_t count) { Jsonb *parsed = nullptr; PG_TRY(); { parsed = DatumGetJsonbP(DirectFunctionCall1( jsonb_in, CStringGetDatum(response.body.c_str()))); } PG_CATCH(); { FlushErrorState(); parsed = nullptr; } PG_END_TRY(); JsonbContainer *data = nullptr; if (parsed != nullptr && JsonContainerIsObject(&parsed->root)) { JsonbValue buffer; if (dbms_vector_getobjectfield(&parsed->root, "data", &buffer) != nullptr && buffer.type == jbvBinary && JsonContainerIsArray(buffer.val.binary.data)) data = buffer.val.binary.data; } std::vector vectors; if (data != nullptr) { for (uint32_t i = 0; i < count; i++) { JsonbValue *element = getIthJsonbValueFromContainer(data, i); if (element == nullptr || element->type != jbvBinary || !JsonContainerIsObject(element->val.binary.data)) break; JsonbValue embedding; if (dbms_vector_getobjectfield(element->val.binary.data, "embedding", &embedding) == nullptr || embedding.type != jbvBinary) break; std::string text = dbms_vector_embedding_array_to_text(&embedding); if (text.empty()) break; vectors.push_back(text); } } if (vectors.empty()) { /* * Compute the message before ereport: get_provider_error may run a * PG_CATCH, whose FlushErrorState would drop this ereport's frame. */ std::string provider_error = dbms_vector_rest_provider_error(response.body.c_str()); ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION), errmsg("provider returned an error: %s", provider_error.c_str()), errdetail("Oracle error: ORA-20002 " "(EXCP_PROVIDER_ERR)."))); } return vectors; } /* * The openai REST path shared by UTL_TO_EMBEDDING (count=1) and * UTL_TO_EMBEDDINGS batches: parse params, check them, extract the stored * bearer key, POST and parse the embeddings. */ static std::vector dbms_vector_openai_embeddings(const std::vector &inputs, Jsonb *params) { DbmsVectorRestParams rest_params; dbms_vector_rest_parse_params(params, rest_params); dbms_vector_rest_check_params(rest_params); Jsonb *credential = dbms_vector_credential_lookup(rest_params.credential_name); std::string api_key = dbms_vector_rest_credential_key( credential, rest_params.credential_name); char *body = dbms_vector_build_openai_body(inputs, rest_params.model, params); DbmsVectorRestResponse response = dbms_vector_rest_call(rest_params, api_key, body); pfree(body); return dbms_vector_parse_embedding_response(response, inputs.size()); } // --------------------------------------------------------------------------- // UTL_TO_EMBEDDINGS internals (batching + result envelope, pls:1882-1986) // --------------------------------------------------------------------------- /// One parsed chunk of the VECTOR_ARRAY_T input. struct DbmsVectorChunk { JsonbValue chunk_id; /* raw jsonb scalar (or null), pls:1960 */ std::string chunk_data; /* $.chunk_data (must be a string) */ DbmsVectorChunk() { memset(&chunk_id, 0, sizeof(chunk_id)); chunk_id.type = jbvNull; } DbmsVectorChunk(const JsonbValue &id, const std::string &data) : chunk_id(id), chunk_data(data) { } }; /* * Parse one VECTOR_ARRAY_T element (a JSON document string, parity with * Oracle's array-of-JSON-CLOB): it must be a JSON object carrying a string * $.chunk_data; $.chunk_id is optional and may be any scalar. */ static DbmsVectorChunk dbms_vector_parse_chunk(const char *element, size_t index) { Jsonb *parsed = nullptr; PG_TRY(); { parsed = DatumGetJsonbP(DirectFunctionCall1(jsonb_in, CStringGetDatum(element))); } PG_CATCH(); { FlushErrorState(); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("data(%zu) is not a valid JSON document", index + 1), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); } PG_END_TRY(); if (!JsonContainerIsObject(&parsed->root)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("data(%zu) must be a JSON object with chunk_data", index + 1), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); DbmsVectorChunk chunk; JsonbValue buffer; JsonbValue *found = dbms_vector_getobjectfield(&parsed->root, "chunk_data", &buffer); if (found == nullptr || found->type != jbvString) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("data(%zu) is missing a string chunk_data", index + 1), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); chunk.chunk_data.assign(found->val.string.val, found->val.string.len); found = dbms_vector_getobjectfield(&parsed->root, "chunk_id", &buffer); if (found != nullptr && found->type != jbvBinary) chunk.chunk_id = *found; return chunk; } /* * Parse the batch_size param (Oracle DEFAULT_BATCH_SIZE := 50): a numeric * value >= 1, anything else is rejected (pls:1942-1953 parity). */ static int32_t dbms_vector_parse_batch_size(Jsonb *params) { if (params == nullptr || !JsonContainerIsObject(¶ms->root)) return DBMS_VECTOR_DEFAULT_BATCH_SIZE; JsonbValue buffer; JsonbValue *found = dbms_vector_getobjectfield(¶ms->root, "batch_size", &buffer); if (found == nullptr) return DBMS_VECTOR_DEFAULT_BATCH_SIZE; if (found->type != jbvNumeric) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value for BATCH_SIZE parameter"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); int32_t batch_size; PG_TRY(); { batch_size = DatumGetInt32(DirectFunctionCall1( numeric_int4, NumericGetDatum(found->val.numeric))); } PG_CATCH(); { FlushErrorState(); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value for BATCH_SIZE parameter"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); } PG_END_TRY(); if (batch_size < 1) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value for BATCH_SIZE parameter"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); return batch_size; } /* * Provider dispatch shared by UTL_TO_EMBEDDING (pls:2026-2070) and both * UTL_TO_EMBEDDINGS overloads (pls:1895-1900, 1937-1940): 'database' needs * the local ONNX runtime and a model name; 'openai' proceeds (its REST * params are checked later by CHECK_REST_PARAMS parity); anything else is * rejected with the Oracle message parity. */ static void dbms_vector_check_provider(const DbmsVectorRestParams ¶ms) { if (params.provider == "database") { if (!dbms_vector_onnx_available()) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("local ONNX inference is not supported in this build"), errdetail("Provider 'database' requires the server to be " "built with onnxruntime support " "(--with-onnxruntime)."), errhint("Use provider 'openai' with a REST embedding " "endpoint."))); if (params.model.empty()) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("missing MODEL parameter"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); return; } if (params.provider != "openai") ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("An unsupported provider was specified: %s", params.provider.c_str()), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."), errhint("Supported providers: database (local ONNX), openai."))); } /* * Provider 'database': local ONNX inference over the model stored by * LOAD_ONNX_MODEL (params.model names it - Oracle TO_DATABASE_EMBEDDING * parity). The catalog row is read fresh on every call and the session is * created per call (no cache), so LOAD/DROP between calls behave correctly. */ static std::vector dbms_vector_database_embeddings(const std::vector &inputs, const DbmsVectorRestParams ¶ms) { bytea *model_data = nullptr; Jsonb *metadata = nullptr; std::string owner; std::string name; dbms_vector_lookup_model(params.model.c_str(), model_data, metadata, &owner, &name); return dbms_vector_onnx_run_cached(owner.c_str(), name.c_str(), model_data, metadata, inputs); } /* * Build one result envelope element * {"embed_id":,"embed_data":,"embed_vector":"[...]"} * (Oracle pls:1965-1969; embed_vector stays a JSON string in the vector text * form so callers can cast it with ::vector). */ static char * dbms_vector_build_envelope_element(const DbmsVectorChunk &chunk, const std::string &embed_vector) { JsonbInState state; JsonbValue key; JsonbValue value; JsonbValue chunk_id = chunk.chunk_id; memset(&state, 0, sizeof(state)); memset(&key, 0, sizeof(key)); memset(&value, 0, sizeof(value)); pushJsonbValue(&state, WJB_BEGIN_OBJECT, nullptr); key.type = jbvString; key.val.string.val = (char *) "embed_id"; key.val.string.len = strlen("embed_id"); pushJsonbValue(&state, WJB_KEY, &key); pushJsonbValue(&state, WJB_VALUE, &chunk_id); key.val.string.val = (char *) "embed_data"; key.val.string.len = strlen("embed_data"); pushJsonbValue(&state, WJB_KEY, &key); value.type = jbvString; value.val.string.val = (char *) chunk.chunk_data.c_str(); value.val.string.len = chunk.chunk_data.size(); pushJsonbValue(&state, WJB_VALUE, &value); key.val.string.val = (char *) "embed_vector"; key.val.string.len = strlen("embed_vector"); pushJsonbValue(&state, WJB_KEY, &key); value.val.string.val = (char *) embed_vector.c_str(); value.val.string.len = embed_vector.size(); pushJsonbValue(&state, WJB_VALUE, &value); pushJsonbValue(&state, WJB_END_OBJECT, nullptr); Jsonb *element = JsonbValueToJsonb(state.result); return JsonbToCString(nullptr, &element->root, 0); } /* * Shared array path (Oracle TO_EMBEDDINGS batch loop, pls:1955-1984): split * the chunks into batches of batch_size, embed each batch through the * dispatch (provider 'database' runs one local ONNX session per batch over * the model fetched once; 'openai' POSTs through the REST core) and zip the * answers into the envelope text[] result. */ static ArrayType * dbms_vector_embeddings_chunks(const std::vector &chunks, Jsonb *params) { DbmsVectorRestParams rest_params; dbms_vector_rest_parse_params(params, rest_params); dbms_vector_check_provider(rest_params); bool database = rest_params.provider == "database"; int32_t batch_size = dbms_vector_parse_batch_size(params); bytea *model_data = nullptr; Jsonb *model_metadata = nullptr; std::string model_owner; std::string model_name; if (database) dbms_vector_lookup_model(rest_params.model.c_str(), model_data, model_metadata, &model_owner, &model_name); std::vector envelopes; for (size_t start = 0; start < chunks.size(); start += batch_size) { size_t end = std::min(start + (size_t) batch_size, chunks.size()); std::vector inputs; for (size_t i = start; i < end; i++) inputs.push_back(chunks[i].chunk_data); std::vector vectors = database ? dbms_vector_onnx_run_cached(model_owner.c_str(), model_name.c_str(), model_data, model_metadata, inputs) : dbms_vector_openai_embeddings(inputs, params); if (vectors.size() != inputs.size()) ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION), errmsg("provider returned %zu embeddings for %zu inputs", vectors.size(), inputs.size()), errdetail("Oracle error: ORA-20002 " "(EXCP_PROVIDER_ERR)."))); for (size_t i = start; i < end; i++) envelopes.push_back( dbms_vector_build_envelope_element(chunks[i], vectors[i - start])); } if (envelopes.empty()) return construct_empty_array(TEXTOID); Datum *elements = (Datum *) palloc(envelopes.size() * sizeof(Datum)); for (size_t i = 0; i < envelopes.size(); i++) elements[i] = CStringGetTextDatum(envelopes[i]); return construct_array(elements, envelopes.size(), TEXTOID, -1, false, TYPALIGN_INT); } // --------------------------------------------------------------------------- // QUERY internals (dynamic SQL over the in-core vector operators, // pls:827-995) // --------------------------------------------------------------------------- /// Oracle query defaults (pls:836-845). #define DBMS_VECTOR_QUERY_DEFAULT_METRIC "EUCLIDEAN" /* * Map a distance metric (case-insensitive, parity with the UPPER() check at * pls:857-864) onto the ORDER BY expression over the vector column. DOT maps * to the negative inner product operator <#> so ascending order still means * best-first; EUCLIDEAN_SQUARED / L2_SQUARED have no operator and call * vector_l2_squared_distance() directly; HAMMING exists only for bit vectors, * which are outside the scope of this port. */ static std::string dbms_vector_query_order_by(const char *distance_metric, const std::string &colref) { std::string metric = dbms_vector_ascii_upper(distance_metric == nullptr ? "" : distance_metric); 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 == "EUCLIDEAN") return colref + " <-> $1"; if (metric == "COSINE") return colref + " <=> $1"; if (metric == "DOT") return colref + " <#> $1"; if (metric == "MANHATTAN") return colref + " <+> $1"; if (metric == "EUCLIDEAN_SQUARED" || metric == "L2_SQUARED") return "vector_l2_squared_distance(" + colref + ", $1)"; ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Distance metric - %s - is not a valid option", distance_metric), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); return std::string(); /* not reached */ } /* * Build the projection list (Oracle pls:866-882 minus the ROWNUM emulation): * the whole row via to_jsonb(t.*) when vec_proj_cols is absent or empty * (t.* is a whole-row reference that can never be captured by a column of * the same name as the table alias), else jsonb_build_object('', * t., ...) over the jsonb string array. */ static std::string dbms_vector_query_projection(Jsonb *vec_proj_cols) { if (vec_proj_cols == nullptr) return "to_jsonb(t.*)"; if (!JsonContainerIsArray(&vec_proj_cols->root)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("vec_proj_cols must be a JSON array of column names"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); JsonbContainer *container = &vec_proj_cols->root; uint32_t count = JsonContainerSize(container); if (count == 0) return "to_jsonb(t.*)"; std::string projection = "jsonb_build_object("; for (uint32_t i = 0; i < count; i++) { JsonbValue *element = getIthJsonbValueFromContainer(container, i); if (element == nullptr || element->type != jbvString) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("vec_proj_cols(%u) must be a column name string", i + 1), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); std::string column(element->val.string.val, element->val.string.len); dbms_vector_check_simple_name(column, "projection column name"); if (i > 0) projection += ", "; projection += "'" + column + "', t." + quote_identifier(column.c_str()); } projection += ")"; return projection; } /* * Extract an int parameter >= 1 from the idx_parameters object (Oracle * GET_NUMBER('efsearch') / GET_NUMBER('neighbor partition probes'), pls:932). */ static bool dbms_vector_query_idx_param(Jsonb *idx_parameters, const char *key, const char *param_name, int32_t &out) { JsonbValue buffer; JsonbValue *found = dbms_vector_getobjectfield(&idx_parameters->root, key, &buffer); if (found == nullptr) return false; 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(); if (value < 1) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value for %s parameter", param_name), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); out = value; return true; } /* * One SET LOCAL assignment applied around the main query (exact-scan forcing * or hnsw/ivfflat tuning, the approximation of the Oracle WITH TARGET * ACCURACY / WITH ACCURACY PARAMETERS clauses, pls:898-927). The previous * value is saved and restored afterwards so the caller's session keeps its * configuration. Values are generated internally ('on', 'off', integers), * so inlining them into the SET statement is injection-safe. */ struct DbmsVectorGucAssignment { const char *name; std::string value; std::string saved; bool had_saved = false; }; static void dbms_vector_guc_save(DbmsVectorGucAssignment &assignment) { static const char *sql = "SELECT current_setting($1, true)"; Oid argtypes[1] = {TEXTOID}; Datum values[1]; char nulls[1] = {' '}; values[0] = CStringGetTextDatum(assignment.name); 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) { bool isnull = false; Datum current = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) { assignment.saved = TextDatumGetCString(current); assignment.had_saved = true; } } } static void dbms_vector_guc_set_local(const DbmsVectorGucAssignment &assignment) { std::string sql = std::string("SET LOCAL ") + assignment.name + " = " + assignment.value; int rc = SPI_execute(sql.c_str(), false, 0); if (rc != SPI_OK_UTILITY) ereport(ERROR, (errmsg("SPI_execute failed: %s (rc=%d)", SPI_result_code_string(rc), rc))); } static void dbms_vector_guc_restore(const DbmsVectorGucAssignment &assignment) { DbmsVectorGucAssignment restore = assignment; restore.value = "'" + assignment.saved + "'"; dbms_vector_guc_set_local(restore); } /* * Validate that idx_name exists as an index on the table (warning only; no * hint is forced into the query - the ORDER BY + LIMIT lets the planner * choose, a documented deviation from the Oracle INDEX hint). */ static void dbms_vector_query_check_index(const std::string &tab_name, const std::string &idx_name) { static const char *sql = "SELECT 1 FROM pg_index i " "JOIN pg_class c ON c.oid = i.indexrelid " "WHERE i.indrelid = to_regclass($1) " "AND c.relname = $2 AND i.indisvalid"; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(tab_name.c_str()); values[1] = CStringGetTextDatum(idx_name.c_str()); int rc = SPI_execute_with_args(sql, 2, 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) ereport(WARNING, (errmsg("index %s does not exist on table %s", idx_name.c_str(), tab_name.c_str()))); } /* * Collect the jsonb column of the last SPI SELECT into a jsonb array (the * Oracle JSON_ARRAY_T result, pls:969-975). Row values are copied through * SPI_palloc because jsonb values in heap tuples may use the short varlena * header unusable as a Jsonb *. */ static Jsonb * dbms_vector_query_collect(void) { JsonbInState state; JsonbValue element; memset(&state, 0, sizeof(state)); pushJsonbValue(&state, WJB_BEGIN_ARRAY, nullptr); for (uint64_t i = 0; i < SPI_processed; i++) { bool isnull = false; Datum row_datum = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1, &isnull); if (isnull) continue; Jsonb *row = DatumGetJsonbP(row_datum); Jsonb *copy = (Jsonb *) SPI_palloc(VARSIZE(row)); memcpy(copy, row, VARSIZE(row)); JsonbToJsonbValue(copy, &element); pushJsonbValue(&state, WJB_ELEM, &element); } pushJsonbValue(&state, WJB_END_ARRAY, nullptr); return JsonbValueToJsonb(state.result); } /* * Shared implementation of both QUERY overloads (pls:827-995; in Oracle the * VECTOR overload delegates to the CLOB one, here the text overload converts * through vector_in and both share this path). */ static Jsonb * dbms_vector_query_impl(const char *tab_name, const char *vec_col_name, Datum query_vector, int32_t top_k, Jsonb *vec_proj_cols, const char *idx_name, const char *distance_metric, bool use_index, bool accuracy_isnull, Datum accuracy, Jsonb *idx_parameters) { if (tab_name == nullptr || tab_name[0] == '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("table name must be specified"))); if (vec_col_name == nullptr || vec_col_name[0] == '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("vector column name must be specified"))); std::string table(tab_name); std::string column(vec_col_name); dbms_vector_check_simple_name(table, "table name"); dbms_vector_check_simple_name(column, "vector column name"); std::string tab_ident = quote_identifier(table.c_str()); std::string col_ident = quote_identifier(column.c_str()); std::string order_by = dbms_vector_query_order_by(distance_metric, "t." + col_ident); std::string projection = dbms_vector_query_projection(vec_proj_cols); if (idx_name != nullptr && idx_name[0] != '\0') dbms_vector_check_simple_name(std::string(idx_name), "index name"); 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)."))); int32_t efsearch = 0; int32_t probes = 0; bool has_efsearch = false; bool has_probes = false; if (idx_parameters != nullptr) { has_efsearch = dbms_vector_query_idx_param(idx_parameters, "efsearch", "EFSEARCH", efsearch); has_probes = dbms_vector_query_idx_param(idx_parameters, "neighbor partition probes", "NEIGHBOR PARTITION PROBES", probes); } if (!accuracy_isnull) { char *accuracy_text = DatumGetCString(DirectFunctionCall1( numeric_out, accuracy)); elog(DEBUG1, "DBMS_VECTOR.QUERY: target accuracy %s is ignored " "(no engine equivalent; tune hnsw.ef_search/ivfflat.probes " "via idx_parameters)", accuracy_text); } std::string sql = "SELECT " + projection + " FROM " + tab_ident + " t ORDER BY " + order_by + " LIMIT $2"; /* * SPI_connect() switches CurrentMemoryContext to the SPI Proc context, * which SPI_finish() deletes; the result jsonb must be built in the * caller's context (the same context SPI_palloc uses for the row copies). */ MemoryContext result_context = CurrentMemoryContext; SPI_connect(); Jsonb *result = nullptr; PG_TRY(); { std::vector assignments; if (use_index) { if (has_efsearch) assignments.push_back({"hnsw.ef_search", std::to_string(efsearch), "", false}); if (has_probes) assignments.push_back({"ivfflat.probes", std::to_string(probes), "", false}); } else { assignments.push_back({"enable_indexscan", "off", "", false}); assignments.push_back({"enable_indexonlyscan", "off", "", false}); } for (DbmsVectorGucAssignment &assignment : assignments) { dbms_vector_guc_save(assignment); dbms_vector_guc_set_local(assignment); } if (idx_name != nullptr && idx_name[0] != '\0') dbms_vector_query_check_index(table, idx_name); { Oid argtypes[2] = {VECTOROID, INT4OID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = query_vector; values[1] = Int32GetDatum(top_k); int rc = SPI_execute_with_args(sql.c_str(), 2, argtypes, values, nulls, false, 0); if (rc != SPI_OK_SELECT) ereport(ERROR, (errmsg("SPI_execute_with_args failed: %s (rc=%d)", SPI_result_code_string(rc), rc))); } { MemoryContext old_context = MemoryContextSwitchTo(result_context); result = dbms_vector_query_collect(); MemoryContextSwitchTo(old_context); } for (DbmsVectorGucAssignment &assignment : assignments) if (assignment.had_saved) dbms_vector_guc_restore(assignment); } PG_FINALLY(); { SPI_finish(); } PG_END_TRY(); return result; } extern "C" { /// DBMS_VECTOR.UTL_TO_EMBEDDING(data CLOB, params JSON) RETURN VECTOR /// Provider dispatch (pls:2026-2070): 'database' runs local ONNX inference /// over the model named by params (needs --with-onnxruntime), 'openai' goes /// through the REST core, anything else is rejected. Datum dbms_vector_utl_to_embedding(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("data must be specified"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); const char *data = text_to_cstring(PG_GETARG_TEXT_PP(0)); Jsonb *params = PG_ARGISNULL(1) ? nullptr : PG_GETARG_JSONB_P(1); DbmsVectorRestParams rest_params; dbms_vector_rest_parse_params(params, rest_params); dbms_vector_check_provider(rest_params); std::vector inputs; inputs.emplace_back(data); std::vector vectors = rest_params.provider == "database" ? dbms_vector_database_embeddings(inputs, rest_params) : dbms_vector_openai_embeddings(inputs, params); PG_RETURN_DATUM(DirectFunctionCall3(vector_in, CStringGetDatum(vectors[0].c_str()), ObjectIdGetDatum(InvalidOid), Int32GetDatum(-1))); } /// DBMS_VECTOR.UTL_TO_EMBEDDINGS(data CLOB, params JSON) RETURN VECTOR_ARRAY_T /// Exact Oracle parity (pls:1882-1928): the CLOB is wrapped as the single /// chunk {"chunk_id":"1","chunk_data":} and delegated to the array path. Datum dbms_vector_utl_to_embeddings(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("data must be specified"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); const char *data = text_to_cstring(PG_GETARG_TEXT_PP(0)); Jsonb *params = PG_ARGISNULL(1) ? nullptr : PG_GETARG_JSONB_P(1); JsonbValue chunk_id; memset(&chunk_id, 0, sizeof(chunk_id)); chunk_id.type = jbvString; chunk_id.val.string.val = (char *) "1"; chunk_id.val.string.len = strlen("1"); DbmsVectorChunk chunk(chunk_id, data); std::vector chunks; chunks.push_back(chunk); PG_RETURN_ARRAYTYPE_P( dbms_vector_embeddings_chunks(chunks, params)); } /// DBMS_VECTOR.UTL_TO_EMBEDDINGS(data VECTOR_ARRAY_T, params JSON) /// Batch path (pls:1930-1986): each element is a JSON document with /// chunk_id/chunk_data; batches of batch_size (default 50) go through the /// REST core and come back as envelope elements. Datum dbms_vector_utl_to_embeddings_array(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("data must be specified"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); ArrayType *array = PG_GETARG_ARRAYTYPE_P(0); Jsonb *params = PG_ARGISNULL(1) ? nullptr : PG_GETARG_JSONB_P(1); Oid element_type = ARR_ELEMTYPE(array); if (element_type != TEXTOID) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("data must be a text array of JSON documents"))); int32_t element_count = ARR_NDIM(array) == 0 ? 0 : ArrayGetNItems(ARR_NDIM(array), ARR_DIMS(array)); if (element_count == 0) { DbmsVectorRestParams rest_params; dbms_vector_rest_parse_params(params, rest_params); dbms_vector_check_provider(rest_params); PG_RETURN_ARRAYTYPE_P(construct_empty_array(TEXTOID)); } Datum *elements = nullptr; bool *nulls = nullptr; int nelems = 0; deconstruct_array(array, TEXTOID, -1, false, TYPALIGN_INT, &elements, &nulls, &nelems); std::vector chunks; for (int i = 0; i < nelems; i++) { if (nulls[i]) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("data(%d) must not be NULL", i + 1), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); const char *element = text_to_cstring((text *) elements[i]); chunks.push_back(dbms_vector_parse_chunk(element, i)); } PG_RETURN_ARRAYTYPE_P( dbms_vector_embeddings_chunks(chunks, params)); } /// DBMS_VECTOR.QUERY(..., query_vector VECTOR, ...) RETURN JSON_ARRAY_T /// Direct vector path: the query vector is bound as $1 of the generated SQL. Datum dbms_vector_query(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(2)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("query vector must be specified"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); if (PG_ARGISNULL(3)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("top_k must be specified"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); PG_RETURN_JSONB_P(dbms_vector_query_impl( PG_NARGS() > 0 && !PG_ARGISNULL(0) ? text_to_cstring(PG_GETARG_TEXT_PP(0)) : nullptr, PG_NARGS() > 1 && !PG_ARGISNULL(1) ? text_to_cstring(PG_GETARG_TEXT_PP(1)) : nullptr, PG_GETARG_DATUM(2), PG_GETARG_INT32(3), PG_NARGS() > 4 && !PG_ARGISNULL(4) ? PG_GETARG_JSONB_P(4) : nullptr, PG_NARGS() > 5 && !PG_ARGISNULL(5) ? text_to_cstring(PG_GETARG_TEXT_PP(5)) : nullptr, PG_NARGS() > 6 && !PG_ARGISNULL(6) ? text_to_cstring(PG_GETARG_TEXT_PP(6)) : DBMS_VECTOR_QUERY_DEFAULT_METRIC, PG_NARGS() <= 7 || PG_ARGISNULL(7) || PG_GETARG_BOOL(7), !(PG_NARGS() > 8 && !PG_ARGISNULL(8)), PG_NARGS() > 8 && !PG_ARGISNULL(8) ? PG_GETARG_DATUM(8) : (Datum) 0, PG_NARGS() > 9 && !PG_ARGISNULL(9) ? PG_GETARG_JSONB_P(9) : nullptr)); } /// DBMS_VECTOR.QUERY(..., query_vector CLOB, ...) RETURN JSON_ARRAY_T /// FROM_VECTOR parity: the text form is validated through vector_in and /// then shares the vector path (Oracle pls:977-995). Datum dbms_vector_query_text(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(2)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("query vector must be specified"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); if (PG_ARGISNULL(3)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("top_k must be specified"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); const char *query_text = text_to_cstring(PG_GETARG_TEXT_PP(2)); Datum query_vector = DirectFunctionCall3(vector_in, CStringGetDatum(query_text), ObjectIdGetDatum(InvalidOid), Int32GetDatum(-1)); PG_RETURN_JSONB_P(dbms_vector_query_impl( PG_NARGS() > 0 && !PG_ARGISNULL(0) ? text_to_cstring(PG_GETARG_TEXT_PP(0)) : nullptr, PG_NARGS() > 1 && !PG_ARGISNULL(1) ? text_to_cstring(PG_GETARG_TEXT_PP(1)) : nullptr, query_vector, PG_GETARG_INT32(3), PG_NARGS() > 4 && !PG_ARGISNULL(4) ? PG_GETARG_JSONB_P(4) : nullptr, PG_NARGS() > 5 && !PG_ARGISNULL(5) ? text_to_cstring(PG_GETARG_TEXT_PP(5)) : nullptr, PG_NARGS() > 6 && !PG_ARGISNULL(6) ? text_to_cstring(PG_GETARG_TEXT_PP(6)) : DBMS_VECTOR_QUERY_DEFAULT_METRIC, PG_NARGS() <= 7 || PG_ARGISNULL(7) || PG_GETARG_BOOL(7), !(PG_NARGS() > 8 && !PG_ARGISNULL(8)), PG_NARGS() > 8 && !PG_ARGISNULL(8) ? PG_GETARG_DATUM(8) : (Datum) 0, PG_NARGS() > 9 && !PG_ARGISNULL(9) ? PG_GETARG_JSONB_P(9) : nullptr)); } /// DBMS_VECTOR.LOAD_ONNX_MODEL(directory, file_name, model_name, metadata) /// The directory is resolved via the BFILE alias mechanism (TEMP_DIR); /// an absolute path is also accepted (documented deviation: RuDB has no /// Oracle DIRECTORY catalog). Datum dbms_vector_load_onnx_model_dir(PG_FUNCTION_ARGS) { const char *directory = PG_ARGISNULL(0) ? nullptr : text_to_cstring(PG_GETARG_TEXT_PP(0)); const char *file_name = PG_ARGISNULL(1) ? nullptr : text_to_cstring(PG_GETARG_TEXT_PP(1)); const char *model_name = PG_ARGISNULL(2) ? nullptr : text_to_cstring(PG_GETARG_TEXT_PP(2)); if (directory == nullptr || directory[0] == '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("directory must be specified"))); if (file_name == nullptr || file_name[0] == '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("file name must be specified"))); if (!dbms_vector_filename_is_safe(file_name)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid file name: %s", file_name), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); std::string owner; std::string name; dbms_vector_resolve_model_name(model_name, owner, name); /* * Absolute directories are accepted directly; anything else must be a * BFILE directory alias and is resolved server-side by BFileManager * (TEMP_DIR via env/search paths, unknown aliases raise ORA-22285). */ std::string full_path; if (directory[0] == '/') full_path = std::string(directory) + "/" + file_name; else full_path = BFileManager::GetFullPath(directory, file_name); struct stat st = dbms_vector_stat_model_file(full_path); bytea *model_data = dbms_vector_read_model_file(full_path, st); Jsonb *metadata = PG_ARGISNULL(3) ? nullptr : PG_GETARG_JSONB_P(3); metadata = dbms_vector_check_model_metadata(metadata); dbms_vector_store_model(owner, name, model_data, metadata); PG_RETURN_VOID(); } /// DBMS_VECTOR.LOAD_ONNX_MODEL(model_name, model_data BLOB, metadata) /// Catalog storage with runtime validation on --with-onnxruntime builds /// (dbms_vector_store_model); storage-only otherwise. Datum dbms_vector_load_onnx_model(PG_FUNCTION_ARGS) { const char *model_name = PG_ARGISNULL(0) ? nullptr : text_to_cstring(PG_GETARG_TEXT_PP(0)); std::string owner; std::string name; dbms_vector_resolve_model_name(model_name, owner, name); bytea *model_data = PG_ARGISNULL(1) ? nullptr : PG_GETARG_BYTEA_P(1); model_data = dbms_vector_check_model_data(model_data); Jsonb *metadata = PG_ARGISNULL(2) ? nullptr : PG_GETARG_JSONB_P(2); metadata = dbms_vector_check_model_metadata(metadata); dbms_vector_store_model(owner, name, model_data, metadata); PG_RETURN_VOID(); } /// DBMS_VECTOR.DROP_ONNX_MODEL(model_name, force) /// force is accepted for signature parity; no dependent objects can exist /// in this port yet, so it is a documented no-op. Datum dbms_vector_drop_onnx_model(PG_FUNCTION_ARGS) { const char *model_name = PG_ARGISNULL(0) ? nullptr : text_to_cstring(PG_GETARG_TEXT_PP(0)); bool force = !PG_ARGISNULL(1) && PG_GETARG_BOOL(1); std::string owner; std::string name; dbms_vector_resolve_model_name(model_name, owner, name); if (force) elog(DEBUG1, "DROP_ONNX_MODEL force parameter has no effect in this port"); SPI_connect(); PG_TRY(); { static const char *sql = "DELETE FROM \"SYS\".vector_models " "WHERE owner = $1 AND model_name = $2"; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner.c_str()); values[1] = CStringGetTextDatum(name.c_str()); int rc = SPI_execute_with_args(sql, 2, argtypes, values, nulls, false, 1); if (rc != SPI_OK_DELETE) ereport(ERROR, (errmsg("SPI_execute_with_args failed: %s (rc=%d)", SPI_result_code_string(rc), rc))); if (SPI_processed == 0) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("model %s does not exist", name.c_str()), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); /* * Invalidate every backend's pinned sessions of any model: the * generation bump makes cached entries stale on their next use * (INMEMORY_ONNX_MODEL). */ dbms_vector_onnx_bump_generation(); } PG_FINALLY(); { SPI_finish(); } PG_END_TRY(); PG_RETURN_VOID(); } /// DBMS_VECTOR.CREATE_CREDENTIAL(credential_name, params JSON) /// Thin wrapper over dbms_vector_credential_create() (public C++ API). Datum dbms_vector_create_credential(PG_FUNCTION_ARGS) { dbms_vector_credential_create( PG_ARGISNULL(0) ? std::string() : std::string(text_to_cstring(PG_GETARG_TEXT_PP(0))), PG_ARGISNULL(1) ? nullptr : PG_GETARG_JSONB_P(1)); PG_RETURN_VOID(); } /// DBMS_VECTOR.DROP_CREDENTIAL(credential_name) /// Thin wrapper over dbms_vector_credential_drop() (public C++ API). Datum dbms_vector_drop_credential(PG_FUNCTION_ARGS) { dbms_vector_credential_drop( PG_ARGISNULL(0) ? std::string() : std::string(text_to_cstring(PG_GETARG_TEXT_PP(0)))); PG_RETURN_VOID(); } /* * Internal helper: resolve a credential name, honoring the * OWNER.NAME qualification rules and the owner-or-superuser access rule, * and return its stored params jsonb with the secret values * (password/access_token/private_key) redacted to "***". */ Datum dbms_vector_get_credential(PG_FUNCTION_ARGS) { const char *credential_name = PG_ARGISNULL(0) ? nullptr : text_to_cstring(PG_GETARG_TEXT_PP(0)); if (credential_name == nullptr || credential_name[0] == '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("credential name must be specified"))); Jsonb *params = dbms_vector_credential_lookup( std::string(credential_name)); PG_RETURN_JSONB_P(dbms_vector_redact_credential_params(params)); } /* * Internal helper: reports whether local ONNX inference (provider * 'database') is available in this build. Exposed as a pg_catalog function * for tests and monitoring. */ Datum dbms_vector_onnx_enabled(PG_FUNCTION_ARGS) { PG_RETURN_BOOL(dbms_vector_onnx_available()); } /* * UTL_TO_CHUNKS (clob overload): thin conversion wrapper over the shared * chunker core (dbms_vector_text.cpp). The DBMS_VECTOR_CHAIN facades * delegate to the same core, so both packages chunk identically. */ Datum dbms_vector_utl_to_chunks(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("data must be specified"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); text *data = PG_GETARG_TEXT_PP(0); Jsonb *params = PG_NARGS() > 1 && !PG_ARGISNULL(1) ? PG_GETARG_JSONB_P(1) : nullptr; char *result = dbms_vector_text_chunks(VARDATA_ANY(data), VARSIZE_ANY_EXHDR(data), params); PG_RETURN_TEXT_P(cstring_to_text(result)); } /* * UTL_TO_CHUNKS (varchar2 overload): see the clob overload above. */ Datum dbms_vector_utl_to_chunks_1(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("data must be specified"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); text *data = PG_GETARG_TEXT_PP(0); Jsonb *params = PG_NARGS() > 1 && !PG_ARGISNULL(1) ? PG_GETARG_JSONB_P(1) : nullptr; char *result = dbms_vector_text_chunks(VARDATA_ANY(data), VARSIZE_ANY_EXHDR(data), params); PG_RETURN_TEXT_P(cstring_to_text(result)); } /* * UTL_TO_GENERATE_TEXT: thin conversion wrapper over the shared * generate-text core (dbms_vector_text.cpp). The DBMS_VECTOR_CHAIN * facade delegates to the same core, so both packages generate * identically. */ Datum dbms_vector_utl_to_generate_text(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("data must be specified"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); text *data = PG_GETARG_TEXT_PP(0); Jsonb *params = PG_NARGS() > 1 && !PG_ARGISNULL(1) ? PG_GETARG_JSONB_P(1) : nullptr; char *result = dbms_vector_text_generate(VARDATA_ANY(data), VARSIZE_ANY_EXHDR(data), params); PG_RETURN_TEXT_P(cstring_to_text(result)); } /* * CREATE_INDEX core (shared with REBUILD_INDEX branch parity, Oracle * pls:733): validate the Oracle parameter triple through the shared index * mapping (dbms_vector_index_map.cpp), generate the CREATE INDEX DDL for * the mapped engine and SPI-execute it; on failure of the generated DDL * the idx_ddl escape hatch runs as-is (Oracle pls:659-666 ordering: the * fallback fires only then). The index name is uppercased like Oracle; * target accuracy is accepted and logged only (no engine equivalent); * idx_parallel_creation is accepted and ignored (native build resources * apply). */ static void dbms_vector_create_index_impl(const char *idx_name, const char *table_name, const char *idx_vector_col, const char *idx_include_cols, const char *idx_partitioning_scheme, const char *idx_organization, const char *idx_distance_metric, bool accuracy_isnull, Datum accuracy, Jsonb *idx_parameters, const char *idx_ddl) { if (idx_name == nullptr || idx_name[0] == '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("index name must be specified"))); if (table_name == nullptr || table_name[0] == '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("table name must be specified"))); if (idx_vector_col == nullptr || idx_vector_col[0] == '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("vector column name must be specified"))); if (idx_organization == nullptr || idx_organization[0] == '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("idx_organization must be specified"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); if (idx_parameters == nullptr) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("idx_parameters must be specified"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); dbms_vector_index_check_partitioning(idx_partitioning_scheme); DbmsVectorIndexMapping mapping = dbms_vector_index_map( idx_organization, idx_distance_metric, idx_parameters); std::string name = dbms_vector_ascii_upper(idx_name); dbms_vector_check_simple_name(name, "index name"); dbms_vector_check_simple_name(std::string(table_name), "table name"); dbms_vector_check_simple_name(std::string(idx_vector_col), "vector column name"); /* * Identifiers are already validated as simple SQL names, so they go * into the DDL unquoted; an unquoted name follows the engine's case * folding exactly like Oracle's unquoted identifiers do. */ std::string ddl = "CREATE INDEX " + name + " ON " + table_name + " USING " + mapping.am + " (" + idx_vector_col + " " + mapping.opclass + ")"; if (idx_include_cols != nullptr && idx_include_cols[0] != '\0') { dbms_vector_check_simple_name(std::string(idx_include_cols), "include column name"); ddl += std::string(" INCLUDE (") + idx_include_cols + ")"; } std::string reloptions = dbms_vector_index_reloptions_clause(mapping); if (!reloptions.empty()) ddl += " WITH (" + reloptions + ")"; if (!accuracy_isnull) { char *accuracy_text = DatumGetCString(DirectFunctionCall1( numeric_out, accuracy)); elog(DEBUG1, "DBMS_VECTOR.CREATE_INDEX: target accuracy %s is ignored " "(no engine equivalent)", accuracy_text); } /* * The generated DDL runs inside an internal subtransaction so its * failure rolls back only itself (statement-level rollback, like * Oracle's EXECUTE IMMEDIATE with an EXCEPTION handler): the CALL * transaction stays usable and the idx_ddl fallback - or the * re-raised original error - runs in a clean state. */ bool have_fallback = idx_ddl != nullptr && idx_ddl[0] != '\0'; MemoryContext oldcontext = CurrentMemoryContext; ResourceOwner oldowner = CurrentResourceOwner; BeginInternalSubTransaction(NULL); MemoryContextSwitchTo(oldcontext); PG_TRY(); { SPI_connect(); int rc = SPI_execute(ddl.c_str(), false, 0); if (rc != SPI_OK_UTILITY) ereport(ERROR, (errmsg("SPI_execute failed: %s (rc=%d)", SPI_result_code_string(rc), rc))); SPI_finish(); ReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldcontext); CurrentResourceOwner = oldowner; } PG_CATCH(); { MemoryContextSwitchTo(oldcontext); ErrorData *edata = CopyErrorData(); FlushErrorState(); RollbackAndReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldcontext); CurrentResourceOwner = oldowner; if (!have_fallback) ReThrowError(edata); FreeErrorData(edata); elog(DEBUG1, "DBMS_VECTOR.CREATE_INDEX: generated DDL failed, " "running the idx_ddl fallback"); BeginInternalSubTransaction(NULL); MemoryContextSwitchTo(oldcontext); PG_TRY(_fallback); { SPI_connect(); int rc = SPI_execute(idx_ddl, false, 0); if (rc != SPI_OK_UTILITY) ereport(ERROR, (errmsg("SPI_execute failed: %s (rc=%d)", SPI_result_code_string(rc), rc))); SPI_finish(); ReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldcontext); CurrentResourceOwner = oldowner; } PG_CATCH(_fallback); { MemoryContextSwitchTo(oldcontext); ErrorData *fallback_edata = CopyErrorData(); FlushErrorState(); RollbackAndReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldcontext); CurrentResourceOwner = oldowner; ReThrowError(fallback_edata); } PG_END_TRY(_fallback); } PG_END_TRY(); } /// DBMS_VECTOR.CREATE_INDEX(...): thin wrapper over the shared core. /// Arg access must respect PG_NARGS(): CALL with SQL-defaulted args /// omitted passes fewer arguments than the full signature. Datum dbms_vector_create_index(PG_FUNCTION_ARGS) { dbms_vector_create_index_impl( PG_NARGS() > 0 && !PG_ARGISNULL(0) ? text_to_cstring(PG_GETARG_TEXT_PP(0)) : nullptr, PG_NARGS() > 1 && !PG_ARGISNULL(1) ? text_to_cstring(PG_GETARG_TEXT_PP(1)) : nullptr, PG_NARGS() > 2 && !PG_ARGISNULL(2) ? text_to_cstring(PG_GETARG_TEXT_PP(2)) : nullptr, PG_NARGS() > 3 && !PG_ARGISNULL(3) ? text_to_cstring(PG_GETARG_TEXT_PP(3)) : nullptr, PG_NARGS() > 4 && !PG_ARGISNULL(4) ? text_to_cstring(PG_GETARG_TEXT_PP(4)) : nullptr, PG_NARGS() > 5 && !PG_ARGISNULL(5) ? text_to_cstring(PG_GETARG_TEXT_PP(5)) : nullptr, PG_NARGS() > 6 && !PG_ARGISNULL(6) ? text_to_cstring(PG_GETARG_TEXT_PP(6)) : nullptr, !(PG_NARGS() > 7 && !PG_ARGISNULL(7)), PG_NARGS() > 7 && !PG_ARGISNULL(7) ? PG_GETARG_DATUM(7) : (Datum) 0, PG_NARGS() > 8 && !PG_ARGISNULL(8) ? PG_GETARG_JSONB_P(8) : nullptr, PG_NARGS() > 10 && !PG_ARGISNULL(10) ? text_to_cstring(PG_GETARG_TEXT_PP(10)) : nullptr); PG_RETURN_VOID(); } /* * REBUILD_INDEX internals: the stored DDL of an index (the * DBMS_METADATA.GET_DDL analog) fetched through SPI. */ static char * dbms_vector_get_indexdef(Oid indexrelid) { static const char *sql = "SELECT pg_get_indexdef($1)"; Oid argtypes[1] = {OIDOID}; Datum values[1]; char nulls[1] = {' '}; values[0] = ObjectIdGetDatum(indexrelid); 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))); bool isnull = false; Datum ddl = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (isnull) ereport(ERROR, (errmsg("pg_get_indexdef returned NULL for index %u", indexrelid))); return TextDatumGetCString(ddl); } /* * DROP INDEX executed as-is inside the caller's (sub)transaction. */ static void dbms_vector_drop_index(const std::string &name) { std::string ddl = "DROP INDEX " + name; int rc = SPI_execute(ddl.c_str(), false, 0); if (rc != SPI_OK_UTILITY) ereport(ERROR, (errmsg("SPI_execute failed: %s (rc=%d)", SPI_result_code_string(rc), rc))); } /* * Reverse-map an existing operator class onto the distance metric that * creates it (the REBUILD_INDEX override merge needs the effective metric * of the index being rebuilt). */ static std::string dbms_vector_metric_from_opclass(const std::string &opclass) { if (opclass == "vector_cosine_ops") return "COSINE"; if (opclass == "vector_ip_ops") return "DOT"; if (opclass == "vector_l1_ops") return "MANHATTAN"; return "EUCLIDEAN"; } /* * Effective idx_parameters jsonb of a rebuild: the explicitly given one, * else the index's current numeric keys re-expressed in the Oracle * vocabulary (m -> neighbors, ef_construction -> efConstruction, * lists -> partitions; the type follows the target engine). */ static Jsonb * dbms_vector_rebuild_effective_params(const DbmsVectorIndexRef &ref, const std::string &type, Jsonb *idx_parameters) { if (idx_parameters != nullptr) return idx_parameters; int32_t neighbors = 0; int32_t ef_construction = 0; int32_t lists = 0; for (const std::string &option : ref.reloptions) { auto eq = option.find('='); if (eq == std::string::npos) continue; std::string key = option.substr(0, eq); int32_t value = atoi(option.c_str() + eq + 1); if (key == "m") neighbors = value; else if (key == "ef_construction") ef_construction = value; else if (key == "lists") lists = value; } JsonbInState state; JsonbValue key; memset(&state, 0, sizeof(state)); memset(&key, 0, sizeof(key)); pushJsonbValue(&state, WJB_BEGIN_OBJECT, nullptr); struct IntKey { const char *name; int32_t value; }; IntKey keys[] = { {"type", -1}, {"neighbors", neighbors}, {"efConstruction", ef_construction}, {"partitions", lists}, }; for (const IntKey &entry : keys) { if (entry.value == 0 && entry.name[0] != 't') continue; key.type = jbvString; key.val.string.val = (char *) entry.name; key.val.string.len = strlen(entry.name); pushJsonbValue(&state, WJB_KEY, &key); if (entry.name[0] == 't') { JsonbValue value; memset(&value, 0, sizeof(value)); value.type = jbvString; value.val.string.val = (char *) type.c_str(); value.val.string.len = type.size(); pushJsonbValue(&state, WJB_VALUE, &value); } else { JsonbValue value; memset(&value, 0, sizeof(value)); value.type = jbvNumeric; value.val.numeric = DatumGetNumeric(DirectFunctionCall1( int8_numeric, Int64GetDatum((int64_t) entry.value))); pushJsonbValue(&state, WJB_VALUE, &value); } } pushJsonbValue(&state, WJB_END_OBJECT, nullptr); return JsonbValueToJsonb(state.result); } /* * DBMS_VECTOR.REBUILD_INDEX(...): three-branch parity with the Oracle * body (pls:692-830). (a) the full parameter set drops the index and * re-runs the CREATE_INDEX core with the stored DDL as the fallback; * (b) partial overrides re-generate the DDL from the current index * merged with the overrides (organization/metric/parameters; accuracy * and parallel creation only trigger the branch); (c) no overrides drop * and re-execute the stored DDL as-is. The drop and the rebuild run in * one internal subtransaction, so a failed rebuild leaves the old index * in place instead of dropping it. */ Datum dbms_vector_rebuild_index(PG_FUNCTION_ARGS) { /* Arg access respects PG_NARGS(): CALL may omit SQL-defaulted args. */ const char *idx_name = PG_NARGS() > 0 && !PG_ARGISNULL(0) ? text_to_cstring(PG_GETARG_TEXT_PP(0)) : nullptr; const char *table_name = PG_NARGS() > 1 && !PG_ARGISNULL(1) ? text_to_cstring(PG_GETARG_TEXT_PP(1)) : nullptr; const char *idx_vector_col = PG_NARGS() > 2 && !PG_ARGISNULL(2) ? text_to_cstring(PG_GETARG_TEXT_PP(2)) : nullptr; const char *idx_include_cols = PG_NARGS() > 3 && !PG_ARGISNULL(3) ? text_to_cstring(PG_GETARG_TEXT_PP(3)) : nullptr; const char *idx_partitioning_scheme = PG_NARGS() > 4 && !PG_ARGISNULL(4) ? text_to_cstring(PG_GETARG_TEXT_PP(4)) : nullptr; const char *idx_organization = PG_NARGS() > 5 && !PG_ARGISNULL(5) ? text_to_cstring(PG_GETARG_TEXT_PP(5)) : nullptr; const char *idx_distance_metric = PG_NARGS() > 6 && !PG_ARGISNULL(6) ? text_to_cstring(PG_GETARG_TEXT_PP(6)) : nullptr; bool accuracy_isnull = !(PG_NARGS() > 7 && !PG_ARGISNULL(7)); Datum accuracy = PG_NARGS() > 7 && !PG_ARGISNULL(7) ? PG_GETARG_DATUM(7) : (Datum) 0; Jsonb *idx_parameters = PG_NARGS() > 8 && !PG_ARGISNULL(8) ? PG_GETARG_JSONB_P(8) : nullptr; int32_t idx_parallel_creation = PG_NARGS() > 9 && !PG_ARGISNULL(9) ? PG_GETARG_INT32(9) : 4; if (idx_name == nullptr || idx_name[0] == '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("index name must be specified"))); std::string name = dbms_vector_ascii_upper(idx_name); dbms_vector_check_simple_name(name, "index name"); bool metric_given = idx_distance_metric != nullptr && idx_distance_metric[0] != '\0' && dbms_vector_ascii_upper(idx_distance_metric) != "EUCLIDEAN"; /* * The SQL defaults are indistinguishable from explicitly passed * default values (Oracle has the same ambiguity and compares against * the defaults), so a default-valued argument does not select the * override branch. */ bool accuracy_given = false; if (!accuracy_isnull) { char *accuracy_text = DatumGetCString(DirectFunctionCall1( numeric_out, accuracy)); accuracy_given = strcmp(accuracy_text, "95") != 0; } bool parallel_given = idx_parallel_creation != 4; bool full_params = table_name != nullptr && idx_vector_col != nullptr && idx_organization != nullptr && idx_parameters != nullptr; bool overrides = idx_organization != nullptr || metric_given || accuracy_given || idx_parameters != nullptr || parallel_given; /* * Resolve the index and fetch its stored DDL first (read-only, before * any mutation); the DDL text is copied out of the SPI context. */ DbmsVectorIndexRef ref; char *stored_ddl = nullptr; MemoryContext caller_context = CurrentMemoryContext; SPI_connect(); PG_TRY(); { if (!dbms_vector_index_lookup(name.c_str(), ref)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("index %s does not exist", name.c_str()), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); char *ddl_text = dbms_vector_get_indexdef(ref.indexrelid); MemoryContext old_context = MemoryContextSwitchTo(caller_context); stored_ddl = pstrdup(ddl_text); MemoryContextSwitchTo(old_context); } PG_FINALLY(); { SPI_finish(); } PG_END_TRY(); if (accuracy_given) { char *accuracy_text = DatumGetCString(DirectFunctionCall1( numeric_out, accuracy)); elog(DEBUG1, "DBMS_VECTOR.REBUILD_INDEX: target accuracy %s is ignored " "(no engine equivalent)", accuracy_text); } /* * The drop and the rebuild run in one internal subtransaction: a * failed rebuild leaves the old index in place instead of dropping * it (an improvement over the Oracle two-statement behavior). */ MemoryContext oldcontext = CurrentMemoryContext; ResourceOwner oldowner = CurrentResourceOwner; BeginInternalSubTransaction(NULL); MemoryContextSwitchTo(oldcontext); PG_TRY(); { SPI_connect(); if (full_params) { /* * Branch (a): drop, then the CREATE_INDEX core with the * stored DDL as its fallback. The subtransaction stays open * across both steps so a total failure rolls back to the * old index. */ dbms_vector_drop_index(name); SPI_finish(); dbms_vector_create_index_impl(name.c_str(), table_name, idx_vector_col, idx_include_cols, idx_partitioning_scheme, idx_organization, idx_distance_metric, accuracy_isnull, accuracy, idx_parameters, stored_ddl); } else { std::string ddl; if (overrides) { /* * Branch (b): merge the overrides into the current index * and re-generate the DDL through the shared mapping * (string surgery on the Oracle DDL does not translate to * the engine DDL shape; regeneration is the documented * equivalent). */ std::string organization = idx_organization != nullptr ? dbms_vector_ascii_upper(idx_organization) : (ref.am == "hnsw" ? std::string(DBMS_VECTOR_IDX_ORG_HNSW) : std::string(DBMS_VECTOR_IDX_ORG_IVF)); std::string metric = metric_given ? dbms_vector_ascii_upper(idx_distance_metric) : dbms_vector_metric_from_opclass(ref.opclass); std::string am = organization == DBMS_VECTOR_IDX_ORG_HNSW ? "hnsw" : "ivfflat"; std::string type = am == "hnsw" ? "HNSW" : "IVF"; Jsonb *effective_params = dbms_vector_rebuild_effective_params(ref, type, idx_parameters); DbmsVectorIndexMapping mapping = dbms_vector_index_map( organization.c_str(), metric.c_str(), effective_params); std::string reloptions = dbms_vector_index_reloptions_clause(mapping); ddl = "CREATE INDEX " + name + " ON " + ref.table_name + " USING " + mapping.am + " (" + ref.column_name + " " + mapping.opclass + ")"; if (!reloptions.empty()) ddl += " WITH (" + reloptions + ")"; } else { /* Branch (c): re-execute the stored DDL verbatim. */ ddl = stored_ddl; } dbms_vector_drop_index(name); int rc = SPI_execute(ddl.c_str(), false, 0); if (rc != SPI_OK_UTILITY) ereport(ERROR, (errmsg("SPI_execute failed: %s (rc=%d)", SPI_result_code_string(rc), rc))); SPI_finish(); } ReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldcontext); CurrentResourceOwner = oldowner; } PG_CATCH(); { MemoryContextSwitchTo(oldcontext); ErrorData *edata = CopyErrorData(); FlushErrorState(); RollbackAndReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldcontext); CurrentResourceOwner = oldowner; ReThrowError(edata); } PG_END_TRY(); PG_RETURN_VOID(); } /* * DBMS_VECTOR.GET_INDEX_STATUS(idx_name) RETURN JSON: one * {"am","index_name","state"} document. The state derivation follows the * fallback contract: an entry in pg_stat_progress_create_index holding a * relation lock on the index or its table means the build is still running * (LOADING); !indisvalid means FAILED; anything else is COMPLETED. A * missing or non-vector index is rejected through the shared lookup. */ Datum dbms_vector_get_index_status(PG_FUNCTION_ARGS) { const char *idx_name = PG_NARGS() > 0 && !PG_ARGISNULL(0) ? text_to_cstring(PG_GETARG_TEXT_PP(0)) : nullptr; if (idx_name == nullptr || idx_name[0] == '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("index name must be specified"))); std::string name = dbms_vector_ascii_upper(idx_name); dbms_vector_check_simple_name(name, "index name"); MemoryContext result_context = CurrentMemoryContext; SPI_connect(); Jsonb *result = nullptr; PG_TRY(); { DbmsVectorIndexRef ref; if (!dbms_vector_index_lookup(name.c_str(), ref)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("index %s does not exist", name.c_str()), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); bool loading = false; { static const char *sql = "SELECT EXISTS (" " SELECT 1 FROM pg_stat_progress_create_index p" " JOIN pg_locks l ON l.pid = p.pid" " AND l.locktype = 'relation'" " WHERE l.relation = ANY (ARRAY[$1, $2]::oid[]))"; Oid argtypes[2] = {OIDOID, OIDOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = ObjectIdGetDatum(ref.indexrelid); values[1] = ObjectIdGetDatum(ref.indrelid); int rc = SPI_execute_with_args(sql, 2, 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))); bool isnull = false; loading = DatumGetBool(SPI_getbinval( SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull)); } const char *state; if (loading) state = "LOADING"; else if (!ref.indisvalid) state = "FAILED"; else state = "COMPLETED"; const char *stored_name = get_rel_name(ref.indexrelid); JsonbInState jsonb_state; JsonbValue key; JsonbValue value; memset(&jsonb_state, 0, sizeof(jsonb_state)); memset(&key, 0, sizeof(key)); memset(&value, 0, sizeof(value)); pushJsonbValue(&jsonb_state, WJB_BEGIN_OBJECT, nullptr); struct StringField { const char *name; const char *value; }; StringField fields[] = { {"am", ref.am.c_str()}, {"index_name", stored_name == nullptr ? "" : stored_name}, {"state", state}, }; for (const StringField &field : fields) { key.type = jbvString; key.val.string.val = (char *) field.name; key.val.string.len = strlen(field.name); pushJsonbValue(&jsonb_state, WJB_KEY, &key); value.type = jbvString; value.val.string.val = (char *) field.value; value.val.string.len = strlen(field.value); pushJsonbValue(&jsonb_state, WJB_VALUE, &value); } pushJsonbValue(&jsonb_state, WJB_END_OBJECT, nullptr); MemoryContext old_context = MemoryContextSwitchTo(result_context); result = JsonbValueToJsonb(jsonb_state.result); MemoryContextSwitchTo(old_context); } PG_FINALLY(); { SPI_finish(); } PG_END_TRY(); PG_RETURN_JSONB_P(result); } /* * INDEX_VECTOR_MEMORY_ADVISOR internals: the dimension of a vector * column (its typmod), the live row estimate of a table and the integer * value of a reloption entry. */ static int64_t dbms_vector_advisor_column_dim(Oid table_oid, const char *column_name) { static const char *sql = "SELECT a.atttypmod FROM pg_attribute a " "JOIN pg_type t ON t.oid = a.atttypid " "WHERE a.attrelid = $1 AND a.attname = $2 AND t.typname = 'vector'"; Oid argtypes[2] = {OIDOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = ObjectIdGetDatum(table_oid); values[1] = CStringGetTextDatum(column_name); int rc = SPI_execute_with_args(sql, 2, 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) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), errmsg("column %s is not a vector column", column_name), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); bool isnull = false; return DatumGetInt32(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull)); } static int64_t dbms_vector_advisor_row_estimate(Oid table_oid) { static const char *sql = "SELECT GREATEST(c.reltuples, 0)::bigint FROM pg_class c " "WHERE c.oid = $1"; Oid argtypes[1] = {OIDOID}; Datum values[1]; char nulls[1] = {' '}; values[0] = ObjectIdGetDatum(table_oid); 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))); bool isnull = false; return DatumGetInt64(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull)); } static int64_t dbms_vector_advisor_reloption(const std::vector &reloptions, const char *key) { std::string prefix = std::string(key) + "="; for (const std::string &option : reloptions) if (option.rfind(prefix, 0) == 0) return atoi(option.c_str() + prefix.size()); return 0; } /* * The before-create mode: estimate an hnsw index with the engine-default * m over the first vector column of the named table. */ static bool dbms_vector_advisor_before_create(const char *table_name, int64_t &dim, int64_t &rows) { static const char *sql = "SELECT a.atttypmod, GREATEST(c.reltuples, 0)::bigint " "FROM pg_class c " "JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 " " AND NOT a.attisdropped " "JOIN pg_type t ON t.oid = a.atttypid AND t.typname = 'vector' " "WHERE c.oid = to_regclass($1) " "ORDER BY a.attnum LIMIT 1"; Oid argtypes[1] = {TEXTOID}; Datum values[1]; char nulls[1] = {' '}; values[0] = CStringGetTextDatum(table_name); 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) { static const char *probe = "SELECT to_regclass($1) IS 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 isnull = false; if (DatumGetBool(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull))) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_TABLE), errmsg("table %s does not exist", table_name), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), errmsg("table %s has no vector column", table_name), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); } bool isnull = false; dim = DatumGetInt32(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull)); rows = DatumGetInt64(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull)); return true; } /* * DBMS_VECTOR.INDEX_VECTOR_MEMORY_ADVISOR(idx_name, table_name) RETURN * JSON: a {"bytes_per_row","rows_estimated","estimated_bytes"} estimate * of the in-memory footprint. These are documented rudb formulas, not * Oracle's: HNSW stores the vector (dim*4) plus the m-link layer * (m * 2 neighbor entries of (offset 8 + weight 4) bytes) per row; * IVFFLAT stores the vectors plus one centroid (dim*4) per list. Inputs * are pg_class.reltuples, the index reloptions and the vector column * typmod. When idx_name does not resolve and table_name is given, the * before-create mode estimates an hnsw index with the engine-default * m; when neither resolves, the lookup error surfaces. Values are * estimates rounded to whole bytes. */ Datum dbms_vector_index_vector_memory_advisor(PG_FUNCTION_ARGS) { const char *idx_name = PG_NARGS() > 0 && !PG_ARGISNULL(0) ? text_to_cstring(PG_GETARG_TEXT_PP(0)) : nullptr; const char *table_name = PG_NARGS() > 1 && !PG_ARGISNULL(1) ? text_to_cstring(PG_GETARG_TEXT_PP(1)) : nullptr; if (idx_name == nullptr && table_name == nullptr) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("idx_name or table_name must be specified"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); MemoryContext result_context = CurrentMemoryContext; SPI_connect(); Jsonb *result = nullptr; PG_TRY(); { int64_t dim = 0; int64_t rows = 0; std::string am = "hnsw"; int64_t m = 0; int64_t lists = 0; bool before_create = idx_name == nullptr || idx_name[0] == '\0'; if (!before_create) { DbmsVectorIndexRef ref; if (!dbms_vector_index_lookup(idx_name, ref)) { if (table_name == nullptr || table_name[0] == '\0') ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("index %s does not exist", dbms_vector_ascii_upper(idx_name) .c_str()), errdetail("Oracle error: ORA-20003 " "(EXCP_GU_ERR)."))); /* Unknown name with a table: the before-create mode. */ before_create = true; } else { am = ref.am; m = dbms_vector_advisor_reloption(ref.reloptions, "m"); lists = dbms_vector_advisor_reloption(ref.reloptions, "lists"); dim = dbms_vector_advisor_column_dim(ref.indrelid, ref.column_name .c_str()); rows = dbms_vector_advisor_row_estimate(ref.indrelid); } } if (before_create) dbms_vector_advisor_before_create(table_name, dim, rows); /* * Engine defaults apply when the index carries no explicit * reloption (hnsw m defaults to 16, ivfflat lists to 1000). */ if (am == "hnsw" && m == 0) m = 16; if (am == "ivfflat" && lists == 0) lists = 1000; int64_t bytes_per_row; int64_t estimated_bytes; if (am == "hnsw") { bytes_per_row = dim * 8 + m * 24; estimated_bytes = rows * bytes_per_row; } else { bytes_per_row = dim * 4; estimated_bytes = rows * bytes_per_row + lists * dim * 4; } JsonbInState jsonb_state; JsonbValue key; JsonbValue value; memset(&jsonb_state, 0, sizeof(jsonb_state)); memset(&key, 0, sizeof(key)); memset(&value, 0, sizeof(value)); pushJsonbValue(&jsonb_state, WJB_BEGIN_OBJECT, nullptr); struct IntField { const char *name; int64_t value; }; IntField fields[] = { {"bytes_per_row", bytes_per_row}, {"rows_estimated", rows}, {"estimated_bytes", estimated_bytes}, }; for (const IntField &field : fields) { key.type = jbvString; key.val.string.val = (char *) field.name; key.val.string.len = strlen(field.name); pushJsonbValue(&jsonb_state, WJB_KEY, &key); value.type = jbvNumeric; value.val.numeric = DatumGetNumeric(DirectFunctionCall1( int8_numeric, Int64GetDatum(field.value))); pushJsonbValue(&jsonb_state, WJB_VALUE, &value); } pushJsonbValue(&jsonb_state, WJB_END_OBJECT, nullptr); MemoryContext old_context = MemoryContextSwitchTo(result_context); result = JsonbValueToJsonb(jsonb_state.result); MemoryContextSwitchTo(old_context); } PG_FINALLY(); { SPI_finish(); } PG_END_TRY(); PG_RETURN_JSONB_P(result); } /* * DBMS_VECTOR.INMEMORY_ONNX_MODEL(model_name, params): pin a stored model * into this backend's ONNX session cache so provider 'database' batches * skip the per-call session creation. The model resolves through the * catalog lookup (missing/permission errors are flavor-independent); the * runtime gate follows, so servers without --with-onnxruntime raise the * deferred-inference error here. The params argument is accepted and * ignored (no runtime-tunable session options in this port). */ Datum dbms_vector_inmemory_onnx_model(PG_FUNCTION_ARGS) { const char *model_name = PG_NARGS() > 0 && !PG_ARGISNULL(0) ? text_to_cstring(PG_GETARG_TEXT_PP(0)) : nullptr; if (model_name == nullptr || model_name[0] == '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("model name must be specified"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); if (PG_NARGS() > 1 && !PG_ARGISNULL(1)) elog(DEBUG1, "DBMS_VECTOR.INMEMORY_ONNX_MODEL: params argument " "is accepted and ignored"); bytea *model_data = nullptr; Jsonb *metadata = nullptr; std::string owner; std::string name; dbms_vector_lookup_model(model_name, model_data, metadata, &owner, &name); if (!dbms_vector_onnx_available()) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("local ONNX inference is not supported in this build"), errdetail("Provider 'database' requires the server to be " "built with onnxruntime support " "(--with-onnxruntime)."), errhint("Use provider 'openai' with a REST embedding " "endpoint."))); dbms_vector_onnx_pin(owner.c_str(), name.c_str(), model_data, metadata); PG_RETURN_VOID(); } /* * ENABLE/DISABLE_CHECKPOINT core (stage 1: API + persisted state, no AM * behavior yet). With an index name the call resolves the vector index, * checks the caller is the index owner or a superuser, upserts the * per-index override in SYS.vector_index_checkpointing and mirrors it * into the index reloption "checkpointing". Without one it records the * cluster-wide override as the ('*', '*') sentinel row of the same table * (documented deviation: ALTER SYSTEM cannot run inside a CALL * transaction, so the cluster default GUC * dbms_vector.vector_index_checkpointing stays under DBA control and the * sentinel is the persisted package-level override). */ static void dbms_vector_set_checkpoint(const char *idx_name, bool enabled) { if (idx_name == nullptr || idx_name[0] == '\0') { if (!superuser()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("permission denied to change the cluster-wide " "checkpointing state"), errdetail("Only superusers may toggle the cluster-wide " "state."))); SPI_connect(); PG_TRY(); { static const char *sql = "INSERT INTO \"SYS\".vector_index_checkpointing " "(owner, idx_schema, idx_name, enabled, updated) " "VALUES (current_user, '*', '*', $1, now()) " "ON CONFLICT (idx_schema, idx_name) " "DO UPDATE SET enabled = EXCLUDED.enabled, " "updated = now()"; Oid argtypes[1] = {BOOLOID}; Datum values[1]; char nulls[1] = {' '}; values[0] = BoolGetDatum(enabled); int rc = SPI_execute_with_args(sql, 1, argtypes, values, nulls, false, 1); if (rc != SPI_OK_INSERT) ereport(ERROR, (errmsg("SPI_execute_with_args failed: %s (rc=%d)", SPI_result_code_string(rc), rc))); } PG_FINALLY(); { SPI_finish(); } PG_END_TRY(); return; } std::string name = dbms_vector_ascii_upper(idx_name); dbms_vector_check_simple_name(name, "index name"); SPI_connect(); PG_TRY(); { DbmsVectorIndexRef ref; if (!dbms_vector_index_lookup(name.c_str(), ref)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("index %s does not exist", name.c_str()), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); /* Owner or superuser only. */ if (!superuser()) { static const char *sql = "SELECT relowner FROM pg_class WHERE oid = $1"; Oid argtypes[1] = {OIDOID}; Datum values[1]; char nulls[1] = {' '}; values[0] = ObjectIdGetDatum(ref.indexrelid); 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))); bool isnull = false; Oid owner = DatumGetObjectId(SPI_getbinval( SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull)); if (owner != GetUserId()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("permission denied for index %s", name.c_str()), errhint("Only the index owner or a superuser may " "toggle its checkpointing state."))); } static const char *sql = "INSERT INTO \"SYS\".vector_index_checkpointing " "(owner, idx_schema, idx_name, enabled, updated) " "SELECT $1, n.nspname, c.relname, $2, now() " " FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace " " WHERE c.oid = $3 " "ON CONFLICT (idx_schema, idx_name) " "DO UPDATE SET enabled = EXCLUDED.enabled, updated = now()"; Oid argtypes[3] = {TEXTOID, BOOLOID, OIDOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; values[0] = CStringGetTextDatum( GetUserNameFromId(GetUserId(), false)); values[1] = BoolGetDatum(enabled); values[2] = ObjectIdGetDatum(ref.indexrelid); int rc = SPI_execute_with_args(sql, 3, argtypes, values, nulls, false, 1); if (rc != SPI_OK_INSERT) ereport(ERROR, (errmsg("SPI_execute_with_args failed: %s (rc=%d)", SPI_result_code_string(rc), rc))); /* Mirror into the index reloption. */ const char *stored_name = get_rel_name(ref.indexrelid); std::string alter = std::string("ALTER INDEX ") + quote_identifier(stored_name) + " SET (checkpointing = " + (enabled ? "on" : "off") + ")"; rc = SPI_execute(alter.c_str(), false, 0); if (rc != SPI_OK_UTILITY) ereport(ERROR, (errmsg("SPI_execute failed: %s (rc=%d)", SPI_result_code_string(rc), rc))); } PG_FINALLY(); { SPI_finish(); } PG_END_TRY(); } /* * ENABLE_CHECKPOINT / DISABLE_CHECKPOINT - persisted checkpointing state * (cluster GUC + SYS table + index reloption mirror). */ Datum dbms_vector_enable_checkpoint(PG_FUNCTION_ARGS) { dbms_vector_set_checkpoint( PG_NARGS() > 0 && !PG_ARGISNULL(0) ? text_to_cstring(PG_GETARG_TEXT_PP(0)) : nullptr, true); PG_RETURN_VOID(); } Datum dbms_vector_disable_checkpoint(PG_FUNCTION_ARGS) { dbms_vector_set_checkpoint( PG_NARGS() > 0 && !PG_ARGISNULL(0) ? text_to_cstring(PG_GETARG_TEXT_PP(0)) : nullptr, false); PG_RETURN_VOID(); } } // extern "C"