// utl_ref.cpp extern "C" { #include "postgres.h" #include "fmgr.h" #include "funcapi.h" #include "executor/spi.h" #include "access/htup_details.h" #include "access/genam.h" #include "access/table.h" #define REL_OPEN(oid, lm) table_open((oid), (lm)) #define REL_CLOSE(rel, lm) table_close((rel), (lm)) #include "catalog/namespace.h" #include "catalog/pg_type.h" #include "utils/builtins.h" #include "utils/lsyscache.h" #include "utils/relcache.h" #include "utils/typcache.h" #include "utils/errcodes.h" #include "utils/bytea.h" #include "nodes/pg_list.h" #include "lib/stringinfo.h" } #include "utl_ref.hpp" extern "C" { PG_FUNCTION_INFO_V1(utl_ref_delete_object); PG_FUNCTION_INFO_V1(utl_ref_lock_object1); PG_FUNCTION_INFO_V1(utl_ref_lock_object2); PG_FUNCTION_INFO_V1(utl_ref_select_object); PG_FUNCTION_INFO_V1(utl_ref_update_object); PG_FUNCTION_INFO_V1(utl_ref_update_obj_v2); PG_FUNCTION_INFO_V1(utl_ref_get_version); /// @brief Версия RUDB пакета UTL_REF (Oracle UTL_REF пакет) #define RUDB_UTL_REF_VERSION "1.0.0" } static char* qident(const char* ident) /// @brief Возвращает идентификатор в кавычках с экранированием двойных кавычек. { if (ident == nullptr) return pstrdup("\"\""); StringInfoData buf; initStringInfo(&buf); appendStringInfoChar(&buf, '"'); for (const char* p = ident; *p; ++p) { if (*p == '"') appendStringInfoString(&buf, "\"\""); else appendStringInfoChar(&buf, *p); } appendStringInfoChar(&buf, '"'); return buf.data; } typedef struct ParsedRef { Oid relid; Oid keytype; Datum keyval; bool keyisnull; } ParsedRef; typedef struct TargetInfo { char *qualified_relname; char *pk_colname_quoted; Oid pk_type; } TargetInfo; static void raise_no_data_found(void) /// @brief Бросает ошибку ORA-01403: no data found. { ereport(ERROR, (errcode(ERRCODE_NO_DATA_FOUND), errmsg("ORA-01403: no data found"))); } static void raise_pk_unsupported(void) /// @brief Бросает ошибку о неподдерживаемом составном первичном ключе. { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("UTL_REF: only single-column primary keys are supported in this version"))); } static ParsedRef parse_ref(bytea *refdata) /// @brief Разбирает RAW ссылку на составляющие: relid, тип и значение PK. { ParsedRef result; int32 len; char *ptr; if (refdata == nullptr) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("UTL_REF: reference is NULL"))); ptr = VARDATA_ANY(refdata); len = VARSIZE_ANY_EXHDR(refdata); if (len < 12) ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("UTL_REF: invalid reference payload (too short)"))); uint32 relid_net; uint32 keytype_net; uint32 keylen_net; memcpy(&relid_net, ptr + 0, 4); memcpy(&keytype_net, ptr + 4, 4); memcpy(&keylen_net, ptr + 8, 4); Oid relid = (Oid) relid_net; Oid keytype = (Oid) keytype_net; uint32 keylen = (uint32) keylen_net; if (12 + (int32)keylen != len) ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("UTL_REF: invalid reference payload (bad keylen)"))); char *keybytes = ptr + 12; int16 typlen; bool typbyval; char typalign; get_typlenbyvalalign(keytype, &typlen, &typbyval, &typalign); Datum keydatum; if (typbyval) { if (keylen > sizeof(Datum)) ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("UTL_REF: key is too large for pass-by-value type"))); uintptr_t tmp = 0; memcpy(&tmp, keybytes, keylen); keydatum = (Datum) tmp; } else { void *p = palloc(keylen); memcpy(p, keybytes, keylen); keydatum = PointerGetDatum(p); } result.relid = relid; result.keytype = keytype; result.keyval = keydatum; result.keyisnull = false; return result; } static TargetInfo build_target_info(Oid relid) /// @brief Получает полное имя таблицы, имя PK-колонки и тип PK по OID таблицы. { TargetInfo ti; Relation rel; List *idxlist; ListCell *lc; AttrNumber pk_attnum = InvalidAttrNumber; Oid pk_type = InvalidOid; rel = REL_OPEN(relid, AccessShareLock); const char *nspname = get_namespace_name(RelationGetNamespace(rel)); const char *relname = RelationGetRelationName(rel); if (nspname == NULL || relname == NULL) { REL_CLOSE(rel, AccessShareLock); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_TABLE), errmsg("UTL_REF: relation OID %u is invalid", relid))); } { char *qnsp = qident(nspname); char *qrel = qident(relname); StringInfoData buf; initStringInfo(&buf); appendStringInfo(&buf, "%s.%s", qnsp, qrel); ti.qualified_relname = pstrdup(buf.data); } idxlist = RelationGetIndexList(rel); foreach(lc, idxlist) { Oid idxOid = lfirst_oid(lc); Relation idxRel = index_open(idxOid, AccessShareLock); if (idxRel->rd_index->indisprimary) { int nkeys = idxRel->rd_index->indnkeyatts; if (nkeys != 1) { index_close(idxRel, AccessShareLock); REL_CLOSE(rel, AccessShareLock); list_free(idxlist); raise_pk_unsupported(); } pk_attnum = idxRel->rd_index->indkey.values[0]; if (pk_attnum == InvalidAttrNumber) { index_close(idxRel, AccessShareLock); REL_CLOSE(rel, AccessShareLock); list_free(idxlist); raise_pk_unsupported(); } TupleDesc tupd = RelationGetDescr(rel); Form_pg_attribute attr = TupleDescAttr(tupd, pk_attnum - 1); pk_type = attr->atttypid; char *attname = pstrdup(NameStr(attr->attname)); char *qatt = qident(attname); ti.pk_colname_quoted = qatt; index_close(idxRel, AccessShareLock); break; } index_close(idxRel, AccessShareLock); } list_free(idxlist); REL_CLOSE(rel, AccessShareLock); if (pk_attnum == InvalidAttrNumber || pk_type == InvalidOid) raise_pk_unsupported(); ti.pk_type = pk_type; return ti; } static bytea *helper_json_for_row(const ParsedRef *pr, const TargetInfo *ti, bool for_update) /// @brief Возвращает JSON строки как bytea по REF с опциональной блокировкой FOR UPDATE. { bytea *ret_blob = NULL; int spi_rc; StringInfoData sql; initStringInfo(&sql); appendStringInfo( &sql, "SELECT row_to_json(t) " "FROM %s t " "WHERE %s = $1%s", ti->qualified_relname, ti->pk_colname_quoted, (for_update ? " FOR UPDATE" : "") ); Oid argtypes[1]; Datum values[1]; char nulls[1]; argtypes[0] = pr->keytype; values[0] = pr->keyval; nulls[0] = (pr->keyisnull ? 'n' : ' '); if ((spi_rc = SPI_connect()) != SPI_OK_CONNECT) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("UTL_REF: SPI_connect failed, rc=%d", spi_rc))); spi_rc = SPI_execute_with_args(sql.data, 1, argtypes, values, nulls, false, 1); if (spi_rc < 0) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("UTL_REF: SPI_execute_with_args failed, rc=%d", spi_rc))); } if (SPI_processed == 0) { SPI_finish(); raise_no_data_found(); } bool isnull = false; Datum jsonDatum = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (isnull) { SPI_finish(); raise_no_data_found(); } text *jsonText = (text *) DatumGetPointer(jsonDatum); int jsonLen = VARSIZE_ANY_EXHDR(jsonText); char *jsonPtr = VARDATA_ANY(jsonText); /* Must survive SPI_finish(); allocate in the caller context. */ ret_blob = (bytea *) SPI_palloc(VARHDRSZ + jsonLen); SET_VARSIZE(ret_blob, VARHDRSZ + jsonLen); memcpy(VARDATA(ret_blob), jsonPtr, jsonLen); SPI_finish(); return ret_blob; } static void helper_lock_only(const ParsedRef *pr, const TargetInfo *ti) /// @brief Ставит блокировку FOR UPDATE на строку по REF. { int spi_rc; StringInfoData sql; initStringInfo(&sql); appendStringInfo( &sql, "SELECT 1 FROM %s t WHERE %s = $1 FOR UPDATE", ti->qualified_relname, ti->pk_colname_quoted ); Oid argtypes[1]; Datum values[1]; char nulls[1]; argtypes[0] = pr->keytype; values[0] = pr->keyval; nulls[0] = (pr->keyisnull ? 'n' : ' '); if ((spi_rc = SPI_connect()) != SPI_OK_CONNECT) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("UTL_REF: SPI_connect failed, rc=%d", spi_rc))); spi_rc = SPI_execute_with_args(sql.data, 1, argtypes, values, nulls, false, 1); if (spi_rc < 0) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("UTL_REF: SPI_execute_with_args failed, rc=%d", spi_rc))); } if (SPI_processed == 0) { SPI_finish(); raise_no_data_found(); } SPI_finish(); } static void helper_delete(const ParsedRef *pr, const TargetInfo *ti) /// @brief Удаляет строку по REF, иначе ORA-01403 если не найдена. { int spi_rc; StringInfoData sql; initStringInfo(&sql); appendStringInfo( &sql, "DELETE FROM %s WHERE %s = $1", ti->qualified_relname, ti->pk_colname_quoted ); Oid argtypes[1]; Datum values[1]; char nulls[1]; argtypes[0] = pr->keytype; values[0] = pr->keyval; nulls[0] = (pr->keyisnull ? 'n' : ' '); if ((spi_rc = SPI_connect()) != SPI_OK_CONNECT) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("UTL_REF: SPI_connect failed, rc=%d", spi_rc))); spi_rc = SPI_execute_with_args(sql.data, 1, argtypes, values, nulls, false, 0); if (spi_rc < 0) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("UTL_REF: SPI_execute_with_args failed, rc=%d", spi_rc))); } if (SPI_processed == 0) { SPI_finish(); raise_no_data_found(); } SPI_finish(); } static void helper_update(const ParsedRef *pr, const TargetInfo *ti, bytea *blob_json) /// @brief Выполняет полное обновление строки по REF данными из JSON в bytea. { int spi_rc; if (blob_json == nullptr) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("UTL_REF.UPDATE_OBJECT: object is NULL"))); Relation rel = REL_OPEN(pr->relid, RowExclusiveLock); TupleDesc tupd = RelationGetDescr(rel); StringInfoData collist; initStringInfo(&collist); bool first = true; for (int i = 0; i < tupd->natts; i++) { Form_pg_attribute attr = TupleDescAttr(tupd, i); if (attr->attisdropped) continue; if (attr->attnum <= 0) continue; char *qatt = qident(NameStr(attr->attname)); if (!first) appendStringInfoString(&collist, ", "); appendStringInfoString(&collist, qatt); first = false; } if (first) { REL_CLOSE(rel, RowExclusiveLock); ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("UTL_REF.UPDATE_OBJECT: relation has no updatable columns"))); } int blen = VARSIZE_ANY_EXHDR(blob_json); char *bptr = VARDATA_ANY(blob_json); char *json_cstr = (char *) palloc(blen + 1); memcpy(json_cstr, bptr, blen); json_cstr[blen] = '\0'; text *jsonText = cstring_to_text(json_cstr); StringInfoData sql; initStringInfo(&sql); appendStringInfo( &sql, "UPDATE %s SET (%s) = (" " SELECT %s FROM json_populate_record(NULL::%s, $2::json)" ") WHERE %s = $1", ti->qualified_relname, collist.data, collist.data, ti->qualified_relname, ti->pk_colname_quoted ); Oid argtypes[2]; Datum values[2]; char nulls[2]; argtypes[0] = pr->keytype; argtypes[1] = TEXTOID; values[0] = pr->keyval; values[1] = PointerGetDatum(jsonText); nulls[0] = (pr->keyisnull ? 'n' : ' '); nulls[1] = ' '; if ((spi_rc = SPI_connect()) != SPI_OK_CONNECT) { REL_CLOSE(rel, RowExclusiveLock); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("UTL_REF: SPI_connect failed, rc=%d", spi_rc))); } spi_rc = SPI_execute_with_args(sql.data, 2, argtypes, values, nulls, false, 0); if (spi_rc < 0) { SPI_finish(); REL_CLOSE(rel, RowExclusiveLock); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("UTL_REF: SPI_execute_with_args failed, rc=%d", spi_rc))); } if (SPI_processed == 0) { SPI_finish(); REL_CLOSE(rel, RowExclusiveLock); raise_no_data_found(); } SPI_finish(); REL_CLOSE(rel, RowExclusiveLock); } extern "C" Datum utl_ref_delete_object(PG_FUNCTION_ARGS) /// @brief UTL_REF.DELETE_OBJECT: удаляет объект по ссылке RAW. { bytea *refdata = PG_GETARG_BYTEA_P(0); ParsedRef pr = parse_ref(refdata); TargetInfo ti = build_target_info(pr.relid); helper_delete(&pr, &ti); PG_RETURN_VOID(); } extern "C" Datum utl_ref_lock_object1(PG_FUNCTION_ARGS) /// @brief UTL_REF.LOCK_OBJECT: ставит FOR UPDATE по ссылке RAW без возврата объекта. { bytea *refdata = PG_GETARG_BYTEA_P(0); ParsedRef pr = parse_ref(refdata); TargetInfo ti = build_target_info(pr.relid); helper_lock_only(&pr, &ti); PG_RETURN_VOID(); } extern "C" Datum utl_ref_lock_object2(PG_FUNCTION_ARGS) /// @brief UTL_REF.LOCK_OBJECT: возвращает объект как bytea(JSON) и блокирует строку. { bytea *refdata = PG_GETARG_BYTEA_P(0); ParsedRef pr = parse_ref(refdata); TargetInfo ti = build_target_info(pr.relid); bytea *blob = helper_json_for_row(&pr, &ti, true); TupleDesc tupdesc; Datum values[1]; bool nulls[1] = {false}; HeapTuple rettuple; if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("UTL_REF.LOCK_OBJECT: expected RECORD return type"))); values[0] = PointerGetDatum(blob); nulls[0] = (blob == NULL); rettuple = heap_form_tuple(tupdesc, values, nulls); PG_RETURN_DATUM(HeapTupleGetDatum(rettuple)); } extern "C" Datum utl_ref_select_object(PG_FUNCTION_ARGS) /// @brief UTL_REF.SELECT_OBJECT: возвращает объект как bytea(JSON) без блокировки. { bytea *refdata = PG_GETARG_BYTEA_P(0); ParsedRef pr = parse_ref(refdata); TargetInfo ti = build_target_info(pr.relid); bytea *blob = helper_json_for_row(&pr, &ti, false); TupleDesc tupdesc; Datum values[1]; bool nulls[1] = {false}; HeapTuple rettuple; if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("UTL_REF.SELECT_OBJECT: expected RECORD return type"))); values[0] = PointerGetDatum(blob); nulls[0] = (blob == NULL); rettuple = heap_form_tuple(tupdesc, values, nulls); PG_RETURN_DATUM(HeapTupleGetDatum(rettuple)); } extern "C" Datum utl_ref_update_object(PG_FUNCTION_ARGS) /// @brief UTL_REF.UPDATE_OBJECT: полностью обновляет строку по ссылке из JSON(bytea). { LOCAL_FCINFO(fcinfo2, 3); InitFunctionCallInfoData(*fcinfo2, fcinfo->flinfo, 3, PG_GET_COLLATION(), fcinfo->context, NULL); fcinfo2->args[0].value = fcinfo->args[0].value; fcinfo2->args[0].isnull = fcinfo->args[0].isnull; fcinfo2->args[1].value = fcinfo->args[1].value; fcinfo2->args[1].isnull = fcinfo->args[1].isnull; fcinfo2->args[2].value = Int32GetDatum(0); fcinfo2->args[2].isnull = false; return utl_ref_update_obj_v2(fcinfo2); } extern "C" Datum utl_ref_update_obj_v2(PG_FUNCTION_ARGS) /// @brief UTL_REF.UPDATE_OBJECT: полностью обновляет строку по ссылке из JSON(bytea) с дополнительными параметрами режима. { bytea *refdata = PG_GETARG_BYTEA_P(0); bytea *blob_json = PG_ARGISNULL(1) ? NULL : PG_GETARG_BYTEA_P(1); int32 options = PG_ARGISNULL(2) ? 0 : PG_GETARG_INT32(2); const int32 minimum_options = -64; const int32 supported_option_mask = 0x03; bool compatibility_mode = (options & 0x01) != 0; bool validate_payload = (options & 0x02) != 0; int32 payload_hint = 0; ParsedRef pr = parse_ref(refdata); TargetInfo ti = build_target_info(pr.relid); if (options < minimum_options) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("UTL_REF.UPDATE_OBJECT: invalid options"))); options &= supported_option_mask; if (blob_json != NULL) payload_hint = VARSIZE_ANY_EXHDR(blob_json); if (compatibility_mode && payload_hint > 0) payload_hint = payload_hint; if (validate_payload && blob_json != NULL) (void) VARDATA_ANY(blob_json); helper_update(&pr, &ti, blob_json); (void) options; (void) payload_hint; PG_RETURN_VOID(); } /// @brief Возвращает версию RUDB пакета UTL_REF (Oracle UTL_REF пакет) extern "C" Datum utl_ref_get_version(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P(cstring_to_text(RUDB_UTL_REF_VERSION)); }