#include "dbms_soda.hpp" extern "C" { #include "utils/array.h" #include "catalog/namespace.h" #include "catalog/pg_type.h" #include "executor/executor.h" #include "executor/spi.h" #include "nodes/miscnodes.h" #include "nodes/pg_list.h" #include "parser/scansup.h" #include "utils/builtins.h" #include "utils/elog.h" #include "utils/fmgroids.h" #include "utils/jsonb.h" #include "utils/lsyscache.h" #include "utils/memutils.h" #include "utils/numeric.h" #include "utils/timestamp.h" } #include "pgtime.h" #include #include #include #include #include #include extern "C" { PG_FUNCTION_INFO_V1(dbms_soda_create_collection); PG_FUNCTION_INFO_V1(dbms_soda_open_collection); PG_FUNCTION_INFO_V1(dbms_soda_drop_collection); PG_FUNCTION_INFO_V1(dbms_soda_list_collection_names); PG_FUNCTION_INFO_V1(dbms_soda_create_document); PG_FUNCTION_INFO_V1(soda_document_get_blob); PG_FUNCTION_INFO_V1(soda_document_get_clob); PG_FUNCTION_INFO_V1(soda_document_get_created_on); PG_FUNCTION_INFO_V1(soda_document_get_data_type); PG_FUNCTION_INFO_V1(soda_document_get_json); PG_FUNCTION_INFO_V1(soda_document_get_key); PG_FUNCTION_INFO_V1(soda_document_get_last_modified); PG_FUNCTION_INFO_V1(soda_document_get_media_type); PG_FUNCTION_INFO_V1(soda_document_get_varchar2); PG_FUNCTION_INFO_V1(soda_document_get_version); PG_FUNCTION_INFO_V1(soda_collection_create_index); PG_FUNCTION_INFO_V1(soda_collection_drop_index); PG_FUNCTION_INFO_V1(soda_collection_get_index); PG_FUNCTION_INFO_V1(soda_collection_list_indexes); PG_FUNCTION_INFO_V1(soda_collection_get_name); PG_FUNCTION_INFO_V1(soda_collection_get_metadata); PG_FUNCTION_INFO_V1(soda_collection_truncate); PG_FUNCTION_INFO_V1(soda_collection_find); PG_FUNCTION_INFO_V1(soda_collection_find_one_internal); PG_FUNCTION_INFO_V1(soda_collection_insert_one); PG_FUNCTION_INFO_V1(soda_collection_insert_one_and_get_internal); PG_FUNCTION_INFO_V1(soda_collection_save); PG_FUNCTION_INFO_V1(soda_collection_save_and_get_internal); PG_FUNCTION_INFO_V1(soda_collection_get_data_guide); PG_FUNCTION_INFO_V1(soda_collection_create_view_from_dg); PG_FUNCTION_INFO_V1(soda_operation_key); PG_FUNCTION_INFO_V1(soda_operation_keys); PG_FUNCTION_INFO_V1(soda_operation_filter); PG_FUNCTION_INFO_V1(soda_operation_limit); PG_FUNCTION_INFO_V1(soda_operation_skip); PG_FUNCTION_INFO_V1(soda_operation_version); PG_FUNCTION_INFO_V1(soda_operation_hint); PG_FUNCTION_INFO_V1(soda_operation_acquire_lock); PG_FUNCTION_INFO_V1(soda_operation_as_of_scn); PG_FUNCTION_INFO_V1(soda_operation_as_of_timestamp); PG_FUNCTION_INFO_V1(soda_operation_sample); PG_FUNCTION_INFO_V1(soda_operation_count); PG_FUNCTION_INFO_V1(soda_operation_get_data_guide); PG_FUNCTION_INFO_V1(soda_operation_get_one_internal); PG_FUNCTION_INFO_V1(soda_operation_get_cursor); PG_FUNCTION_INFO_V1(soda_operation_remove); PG_FUNCTION_INFO_V1(soda_operation_replace_one); PG_FUNCTION_INFO_V1(soda_operation_replace_one_and_get_internal); PG_FUNCTION_INFO_V1(soda_cursor_next_internal); PG_FUNCTION_INFO_V1(soda_cursor_has_next); PG_FUNCTION_INFO_V1(soda_cursor_close); } namespace DbmsSoda { struct CollectionDescriptor { std::string collectionName_; std::string schemaName_; std::string tableName_; std::string keyColumnName_; std::string contentColumnName_; std::string versionColumnName_; std::string creationTimeColumnName_; std::string lastModifiedColumnName_; Jsonb *metadataJson_; bool isMapped_; }; #define DBMS_SODA_CREATE_MODE_DDL 1 #define DBMS_SODA_CREATE_MODE_MAP 2 static bool table_exists(const std::string &owner_name, const std::string &table_name); static bool metadata_table_exists(const std::string &owner_name); static bool is_default_key_column(const CollectionDescriptor &descriptor) { return !descriptor.isMapped_ && descriptor.keyColumnName_ == "RESID"; } static bool is_raw_key_value(const std::string &key_value) { if (key_value.empty()) { return false; } for (char keyChar : key_value) { if (!((keyChar >= '0' && keyChar <= '9') || (keyChar >= 'A' && keyChar <= 'F') || (keyChar >= 'a' && keyChar <= 'f'))) { return false; } } return true; } static void validate_raw_key_value(const CollectionDescriptor &descriptor, const std::string &key_value) { if (is_default_key_column(descriptor) && !is_raw_key_value(key_value)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA key value is not valid for RAW key collection"), errdetail("key=%s", key_value.c_str()))); } } static JsonbValue * get_object_field(JsonbContainer *container, const char *field_name, JsonbValue *value_buffer) { if (container == nullptr || !JsonContainerIsObject(container)) { return nullptr; } return getKeyJsonValueFromContainer(container, field_name, strlen(field_name), value_buffer); } static std::string jsonb_value_to_string(const JsonbValue *json_value) { char *valueCString = nullptr; std::string resultValue; if (json_value == nullptr) { return resultValue; } switch (json_value->type) { case jbvString: return std::string(json_value->val.string.val, json_value->val.string.len); case jbvBinary: valueCString = JsonbToCString(nullptr, json_value->val.binary.data, json_value->val.binary.len); resultValue = valueCString == nullptr ? "" : std::string(valueCString); if (valueCString != nullptr) { pfree(valueCString); } return resultValue; default: break; } return resultValue; } static std::string quoteidentifier_copy(const std::string &identifier_value) { const char *identifierCString = identifier_value.c_str(); const char *quotedIdentifier = quote_identifier(identifierCString); std::string resultValue = quotedIdentifier == nullptr ? "" : std::string(quotedIdentifier); if (quotedIdentifier != nullptr && quotedIdentifier != identifierCString) { pfree(const_cast(quotedIdentifier)); } return resultValue; } static std::string build_qualified_name(const std::string &owner_name, const std::string &object_name) { return quoteidentifier_copy(owner_name) + "." + quoteidentifier_copy(object_name); } static std::string build_metadata_schema_name() { return "pg_catalog"; } static std::string build_metadata_table_name() { return "dbms_soda_collections"; } static std::string build_metadata_qualified_name(const std::string &owner_name) { (void) owner_name; return build_qualified_name(build_metadata_schema_name(), build_metadata_table_name()); } static std::string build_index_metadata_table_name() { return "dbms_soda_indexes"; } static std::string build_index_metadata_qualified_name(const std::string &owner_name) { (void) owner_name; return build_qualified_name(build_metadata_schema_name(), build_index_metadata_table_name()); } static std::string resolve_owner_name() { List *searchPath = fetch_search_path(false); if (searchPath != NIL) { Oid schemaOid = linitial_oid(searchPath); char *_schemaName = get_namespace_name(schemaOid); if (_schemaName != nullptr && strcmp(_schemaName, "pg_catalog") != 0) { std::string schemaName(_schemaName); pfree(_schemaName); return schemaName; } if (_schemaName != nullptr) { pfree(_schemaName); } } return "public"; } static std::string normalize_identifier_input(const std::string &identifier_value) { char *_normalizedIdentifier = downcase_identifier(identifier_value.c_str(), identifier_value.length(), false, false); std::string normalizedValue = _normalizedIdentifier == nullptr ? "" : std::string(_normalizedIdentifier); if (_normalizedIdentifier != nullptr) { pfree(_normalizedIdentifier); } return normalizedValue; } static std::string build_collection_table_name(const std::string &collection_name) { return normalize_identifier_input(collection_name); } static std::string jsonb_to_text_copy(Jsonb *json_value) { char *jsonCString = JsonbToCString(nullptr, &json_value->root, VARSIZE(json_value)); std::string jsonText = jsonCString == nullptr ? "" : std::string(jsonCString); if (jsonCString != nullptr) { pfree(jsonCString); } return jsonText; } static Jsonb * copy_jsonb_to_registry_context(Jsonb *json_value) { MemoryContext oldContext; Jsonb *resultValue; Size valueSize; if (json_value == nullptr) { return nullptr; } valueSize = VARSIZE_ANY(json_value); oldContext = MemoryContextSwitchTo(TopMemoryContext); resultValue = reinterpret_cast(palloc(valueSize)); memcpy(resultValue, json_value, valueSize); MemoryContextSwitchTo(oldContext); return resultValue; } static std::string textdatum_to_string_copy(Datum value) { char *valueCString = TextDatumGetCString(value); std::string resultValue = valueCString == nullptr ? "" : std::string(valueCString); if (valueCString != nullptr) { pfree(valueCString); } return resultValue; } static Jsonb * parse_metadata_json(text *metadata_text) { char *_metadataCString = text_to_cstring(metadata_text); Datum metadataDatum = DirectFunctionCall1(jsonb_in, CStringGetDatum(_metadataCString)); pfree(_metadataCString); return DatumGetJsonbP(metadataDatum); } static Jsonb * build_metadata_json(const CollectionDescriptor &descriptor) { JsonbInState parseState = {}; JsonbValue keyValue; JsonbValue valueValue; JsonbValue *resultValue = nullptr; auto pushStringField = [&parseState, &keyValue, &valueValue](const char *field_name, const std::string &field_value) { keyValue.type = jbvString; keyValue.val.string.val = const_cast(field_name); keyValue.val.string.len = strlen(field_name); valueValue.type = jbvString; valueValue.val.string.val = const_cast(field_value.c_str()); valueValue.val.string.len = field_value.length(); (void) pushJsonbValue(&parseState, WJB_KEY, &keyValue); (void) pushJsonbValue(&parseState, WJB_VALUE, &valueValue); }; auto pushStringLiteralField = [&parseState, &keyValue, &valueValue](const char *field_name, const char *field_value) { keyValue.type = jbvString; keyValue.val.string.val = const_cast(field_name); keyValue.val.string.len = strlen(field_name); valueValue.type = jbvString; valueValue.val.string.val = const_cast(field_value); valueValue.val.string.len = strlen(field_value); (void) pushJsonbValue(&parseState, WJB_KEY, &keyValue); (void) pushJsonbValue(&parseState, WJB_VALUE, &valueValue); }; (void) pushJsonbValue(&parseState, WJB_BEGIN_OBJECT, nullptr); pushStringField("schemaName", descriptor.schemaName_); pushStringField("tableName", descriptor.tableName_); keyValue.type = jbvString; keyValue.val.string.val = const_cast("keyColumn"); keyValue.val.string.len = strlen("keyColumn"); (void) pushJsonbValue(&parseState, WJB_KEY, &keyValue); (void) pushJsonbValue(&parseState, WJB_BEGIN_OBJECT, nullptr); pushStringField("name", descriptor.keyColumnName_); pushStringLiteralField("sqlType", "RAW"); if (!descriptor.isMapped_) { pushStringLiteralField("assignmentMethod", "EMBEDDED_OID"); pushStringLiteralField("path", "_id"); } (void) pushJsonbValue(&parseState, WJB_END_OBJECT, nullptr); keyValue.type = jbvString; keyValue.val.string.val = const_cast("contentColumn"); keyValue.val.string.len = strlen("contentColumn"); (void) pushJsonbValue(&parseState, WJB_KEY, &keyValue); (void) pushJsonbValue(&parseState, WJB_BEGIN_OBJECT, nullptr); pushStringField("name", descriptor.contentColumnName_); pushStringLiteralField("sqlType", "JSON"); (void) pushJsonbValue(&parseState, WJB_END_OBJECT, nullptr); keyValue.type = jbvString; keyValue.val.string.val = const_cast("versionColumn"); keyValue.val.string.len = strlen("versionColumn"); (void) pushJsonbValue(&parseState, WJB_KEY, &keyValue); (void) pushJsonbValue(&parseState, WJB_BEGIN_OBJECT, nullptr); pushStringField("name", descriptor.versionColumnName_); if (!descriptor.isMapped_) { pushStringLiteralField("method", "NONE"); } (void) pushJsonbValue(&parseState, WJB_END_OBJECT, nullptr); if (!descriptor.creationTimeColumnName_.empty()) { keyValue.type = jbvString; keyValue.val.string.val = const_cast("creationTimeColumn"); keyValue.val.string.len = strlen("creationTimeColumn"); (void) pushJsonbValue(&parseState, WJB_KEY, &keyValue); (void) pushJsonbValue(&parseState, WJB_BEGIN_OBJECT, nullptr); pushStringField("name", descriptor.creationTimeColumnName_); (void) pushJsonbValue(&parseState, WJB_END_OBJECT, nullptr); } if (!descriptor.lastModifiedColumnName_.empty()) { keyValue.type = jbvString; keyValue.val.string.val = const_cast("lastModifiedColumn"); keyValue.val.string.len = strlen("lastModifiedColumn"); (void) pushJsonbValue(&parseState, WJB_KEY, &keyValue); (void) pushJsonbValue(&parseState, WJB_BEGIN_OBJECT, nullptr); pushStringField("name", descriptor.lastModifiedColumnName_); (void) pushJsonbValue(&parseState, WJB_END_OBJECT, nullptr); } keyValue.type = jbvString; keyValue.val.string.val = const_cast("readOnly"); keyValue.val.string.len = strlen("readOnly"); valueValue.type = jbvBool; valueValue.val.boolean = false; (void) pushJsonbValue(&parseState, WJB_KEY, &keyValue); (void) pushJsonbValue(&parseState, WJB_VALUE, &valueValue); keyValue.type = jbvString; keyValue.val.string.val = const_cast("native"); keyValue.val.string.len = strlen("native"); valueValue.type = jbvBool; valueValue.val.boolean = !descriptor.isMapped_; (void) pushJsonbValue(&parseState, WJB_KEY, &keyValue); (void) pushJsonbValue(&parseState, WJB_VALUE, &valueValue); (void) pushJsonbValue(&parseState, WJB_END_OBJECT, nullptr); resultValue = parseState.result; return JsonbValueToJsonb(resultValue); } static void apply_metadata(Jsonb *metadata_json, CollectionDescriptor *descriptor) { JsonbValue rootValue; JsonbValue tableBuffer; JsonbValue keyBuffer; JsonbValue contentBuffer; JsonbValue versionBuffer; JsonbValue creationTimeBuffer; JsonbValue lastModifiedBuffer; JsonbValue nameBuffer; JsonbValue *tableValue = nullptr; JsonbValue *keyValue = nullptr; JsonbValue *contentValue = nullptr; JsonbValue *versionValue = nullptr; JsonbValue *creationTimeValue = nullptr; JsonbValue *lastModifiedValue = nullptr; JsonbValue *nameValue = nullptr; if (metadata_json == nullptr) { return; } JsonbToJsonbValue(metadata_json, &rootValue); if (rootValue.type != jbvBinary || !JsonContainerIsObject(rootValue.val.binary.data)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("DBMS_SODA.CREATE_COLLECTION metadata must be a JSON object"))); } tableValue = get_object_field(rootValue.val.binary.data, "tableName", &tableBuffer); if (tableValue != nullptr) { descriptor->tableName_ = jsonb_value_to_string(tableValue); } keyValue = get_object_field(rootValue.val.binary.data, "keyColumn", &keyBuffer); if (keyValue != nullptr && keyValue->type == jbvBinary && JsonContainerIsObject(keyValue->val.binary.data)) { nameValue = get_object_field(keyValue->val.binary.data, "name", &nameBuffer); if (nameValue != nullptr) { descriptor->keyColumnName_ = jsonb_value_to_string(nameValue); } } contentValue = get_object_field(rootValue.val.binary.data, "contentColumn", &contentBuffer); if (contentValue != nullptr && contentValue->type == jbvBinary && JsonContainerIsObject(contentValue->val.binary.data)) { nameValue = get_object_field(contentValue->val.binary.data, "name", &nameBuffer); if (nameValue != nullptr) { descriptor->contentColumnName_ = jsonb_value_to_string(nameValue); } } versionValue = get_object_field(rootValue.val.binary.data, "versionColumn", &versionBuffer); if (versionValue != nullptr && versionValue->type == jbvBinary && JsonContainerIsObject(versionValue->val.binary.data)) { nameValue = get_object_field(versionValue->val.binary.data, "name", &nameBuffer); if (nameValue != nullptr) { descriptor->versionColumnName_ = jsonb_value_to_string(nameValue); } } creationTimeValue = get_object_field(rootValue.val.binary.data, "creationTimeColumn", &creationTimeBuffer); if (creationTimeValue != nullptr && creationTimeValue->type == jbvBinary && JsonContainerIsObject(creationTimeValue->val.binary.data)) { nameValue = get_object_field(creationTimeValue->val.binary.data, "name", &nameBuffer); if (nameValue != nullptr) { descriptor->creationTimeColumnName_ = jsonb_value_to_string(nameValue); } } lastModifiedValue = get_object_field(rootValue.val.binary.data, "lastModifiedColumn", &lastModifiedBuffer); if (lastModifiedValue != nullptr && lastModifiedValue->type == jbvBinary && JsonContainerIsObject(lastModifiedValue->val.binary.data)) { nameValue = get_object_field(lastModifiedValue->val.binary.data, "name", &nameBuffer); if (nameValue != nullptr) { descriptor->lastModifiedColumnName_ = jsonb_value_to_string(nameValue); } } } static void ensure_metadata_table(const std::string &owner_name) { int spiStatus = SPI_OK_CONNECT; int executeStatus = SPI_OK_UTILITY; std::string createSql = "CREATE TABLE IF NOT EXISTS " + build_metadata_qualified_name(owner_name) + " (" "collection_schema text NOT NULL, " "collection_name text NOT NULL, " "table_name text NOT NULL, " "key_column text NOT NULL, " "content_column text NOT NULL, " "version_column text NOT NULL, " "metadata jsonb, " "is_mapped bool NOT NULL DEFAULT false, " "created_at timestamptz NOT NULL DEFAULT clock_timestamp(), " "PRIMARY KEY(collection_schema, collection_name), " "UNIQUE(collection_schema, table_name)" ")"; spiStatus = SPI_connect(); if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed in DBMS_SODA metadata initialization"), errdetail("spi_status=%d", spiStatus))); } if (metadata_table_exists(owner_name)) { SPI_finish(); return; } executeStatus = SPI_execute(createSql.c_str(), false, 0); if (executeStatus != SPI_OK_UTILITY) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA metadata table initialization failed"), errdetail("spi_status=%d", executeStatus))); } SPI_finish(); } static void ensure_index_metadata_table(const std::string &owner_name) { int spiStatus = SPI_OK_CONNECT; int executeStatus = SPI_OK_UTILITY; std::string createSql = "CREATE TABLE IF NOT EXISTS " + build_index_metadata_qualified_name(owner_name) + " (" "collection_schema text NOT NULL, " "collection_name text NOT NULL, " "index_name text NOT NULL, " "specification jsonb NOT NULL, " "created_at timestamptz NOT NULL DEFAULT clock_timestamp(), " "PRIMARY KEY(collection_schema, collection_name, index_name)" ")"; spiStatus = SPI_connect(); if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed in DBMS_SODA index metadata initialization"), errdetail("spi_status=%d", spiStatus))); } if (table_exists(build_metadata_schema_name(), build_index_metadata_table_name())) { SPI_finish(); return; } executeStatus = SPI_execute(createSql.c_str(), false, 0); if (executeStatus != SPI_OK_UTILITY) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA index metadata table initialization failed"), errdetail("spi_status=%d", executeStatus))); } SPI_finish(); } static bool table_exists(const std::string &owner_name, const std::string &table_name) { Oid argTypes[1] = {TEXTOID}; Datum values[1]; const char nulls[1] = {' '}; std::string selectSql = "SELECT to_regclass($1) IS NOT NULL"; bool isNull = false; int executeStatus = SPI_OK_SELECT; values[0] = CStringGetTextDatum(build_qualified_name(owner_name, table_name).c_str()); executeStatus = SPI_execute_with_args(selectSql.c_str(), 1, argTypes, values, nulls, true, 1); if (executeStatus != SPI_OK_SELECT || SPI_processed != 1) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA table lookup failed"), errdetail("spi_status=%d", executeStatus))); } return DatumGetBool(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isNull)); } static bool metadata_table_exists(const std::string &owner_name) { (void) owner_name; return table_exists(build_metadata_schema_name(), build_metadata_table_name()); } static void validate_column_shape(const std::string &owner_name, const std::string &table_name, const std::string &column_name, const std::string &expected_type) { Oid argTypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; const char nulls[3] = {' ', ' ', ' '}; std::string selectSql = "SELECT data_type FROM information_schema.columns " "WHERE table_schema = $1 AND table_name = $2 AND column_name = $3"; bool isNull = false; int executeStatus = SPI_OK_SELECT; values[0] = CStringGetTextDatum(owner_name.c_str()); values[1] = CStringGetTextDatum(table_name.c_str()); values[2] = CStringGetTextDatum(column_name.c_str()); executeStatus = SPI_execute_with_args(selectSql.c_str(), 3, argTypes, values, nulls, true, 1); if (executeStatus != SPI_OK_SELECT) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA collection shape validation failed"), errdetail("spi_status=%d", executeStatus))); } if (SPI_processed != 1) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("DBMS_SODA mapped table has invalid shape"), errdetail("missing column=%s", column_name.c_str()))); } char *typeCString = TextDatumGetCString(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isNull)); if (typeCString == nullptr || expected_type != typeCString) { if (typeCString != nullptr) { pfree(typeCString); } ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("DBMS_SODA mapped table has invalid shape"), errdetail("column=%s, expected_type=%s", column_name.c_str(), expected_type.c_str()))); } pfree(typeCString); } static void validate_collection_table(const CollectionDescriptor &descriptor) { validate_column_shape(descriptor.schemaName_, descriptor.tableName_, descriptor.keyColumnName_, "text"); validate_column_shape(descriptor.schemaName_, descriptor.tableName_, descriptor.contentColumnName_, "jsonb"); validate_column_shape(descriptor.schemaName_, descriptor.tableName_, descriptor.versionColumnName_, "text"); if (!descriptor.creationTimeColumnName_.empty()) { validate_column_shape(descriptor.schemaName_, descriptor.tableName_, descriptor.creationTimeColumnName_, "timestamp with time zone"); } if (!descriptor.lastModifiedColumnName_.empty()) { validate_column_shape(descriptor.schemaName_, descriptor.tableName_, descriptor.lastModifiedColumnName_, "timestamp with time zone"); } } static bool fetch_collection_descriptor(const std::string &owner_name, const std::string &collection_name, CollectionDescriptor *descriptor) { Oid argTypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; const char nulls[2] = {' ', ' '}; std::string selectSql = "SELECT collection_schema, collection_name, table_name, key_column, content_column, " "version_column, metadata, is_mapped FROM " + build_metadata_qualified_name(owner_name) + " WHERE collection_schema = $1 AND collection_name = $2"; int executeStatus = SPI_OK_SELECT; bool isNull = false; values[0] = CStringGetTextDatum(owner_name.c_str()); values[1] = CStringGetTextDatum(collection_name.c_str()); executeStatus = SPI_execute_with_args(selectSql.c_str(), 2, argTypes, values, nulls, true, 1); if (executeStatus != SPI_OK_SELECT) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA collection metadata lookup failed"), errdetail("spi_status=%d", executeStatus))); } if (SPI_processed == 0) { return false; } descriptor->schemaName_ = textdatum_to_string_copy( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isNull)); descriptor->collectionName_ = textdatum_to_string_copy( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isNull)); descriptor->tableName_ = textdatum_to_string_copy( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 3, &isNull)); descriptor->keyColumnName_ = textdatum_to_string_copy( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 4, &isNull)); descriptor->contentColumnName_ = textdatum_to_string_copy( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 5, &isNull)); descriptor->versionColumnName_ = textdatum_to_string_copy( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 6, &isNull)); Datum metadataDatum = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 7, &isNull); Jsonb *metadataValue = isNull ? nullptr : DatumGetJsonbP(metadataDatum); descriptor->metadataJson_ = copy_jsonb_to_registry_context(metadataValue); descriptor->isMapped_ = DatumGetBool(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 8, &isNull)); descriptor->creationTimeColumnName_.clear(); descriptor->lastModifiedColumnName_.clear(); apply_metadata(descriptor->metadataJson_, descriptor); if (isNull || descriptor->metadataJson_ == nullptr) { descriptor->metadataJson_ = copy_jsonb_to_registry_context(build_metadata_json(*descriptor)); } return true; } static void insert_collection_descriptor(const CollectionDescriptor &descriptor) { Oid argTypes[8] = {TEXTOID, TEXTOID, TEXTOID, TEXTOID, TEXTOID, TEXTOID, JSONBOID, BOOLOID}; Datum values[8]; const char nulls[8] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}; std::string insertSql = "INSERT INTO " + build_metadata_qualified_name(descriptor.schemaName_) + " (collection_schema, collection_name, table_name, key_column, content_column, " "version_column, metadata, is_mapped) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)"; int executeStatus = SPI_OK_INSERT; values[0] = CStringGetTextDatum(descriptor.schemaName_.c_str()); values[1] = CStringGetTextDatum(descriptor.collectionName_.c_str()); values[2] = CStringGetTextDatum(descriptor.tableName_.c_str()); values[3] = CStringGetTextDatum(descriptor.keyColumnName_.c_str()); values[4] = CStringGetTextDatum(descriptor.contentColumnName_.c_str()); values[5] = CStringGetTextDatum(descriptor.versionColumnName_.c_str()); values[6] = JsonbPGetDatum(descriptor.metadataJson_); values[7] = BoolGetDatum(descriptor.isMapped_); executeStatus = SPI_execute_with_args(insertSql.c_str(), 8, argTypes, values, nulls, false, 0); if (executeStatus != SPI_OK_INSERT) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA failed to register collection metadata"), errdetail("spi_status=%d, collection_name=%s", executeStatus, descriptor.collectionName_.c_str()))); } } static void create_physical_collection(const CollectionDescriptor &descriptor) { std::string createTableSql = "CREATE TABLE " + build_qualified_name(descriptor.schemaName_, descriptor.tableName_) + " (" + quoteidentifier_copy(descriptor.keyColumnName_) + " text PRIMARY KEY DEFAULT upper(replace(gen_random_uuid()::text, '-', '')), " + quoteidentifier_copy(descriptor.contentColumnName_) + " jsonb NOT NULL, " + quoteidentifier_copy(descriptor.versionColumnName_) + " text NOT NULL DEFAULT upper(replace(gen_random_uuid()::text, '-', '')), " "\"media_type\" text DEFAULT 'application/json', " "\"content_data_type\" int4 NOT NULL DEFAULT 4"; if (!descriptor.creationTimeColumnName_.empty()) { createTableSql += ", " + quoteidentifier_copy(descriptor.creationTimeColumnName_) + " timestamptz NOT NULL DEFAULT clock_timestamp()"; } if (!descriptor.lastModifiedColumnName_.empty()) { createTableSql += ", " + quoteidentifier_copy(descriptor.lastModifiedColumnName_) + " timestamptz NOT NULL DEFAULT clock_timestamp()"; } createTableSql += ")"; int executeStatus = SPI_OK_UTILITY; executeStatus = SPI_execute(createTableSql.c_str(), false, 0); if (executeStatus != SPI_OK_UTILITY) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA failed to create collection table"), errdetail("spi_status=%d, table_name=%s", executeStatus, descriptor.tableName_.c_str()))); } } static CollectionDescriptor create_collection(const std::string &owner_name, const std::string &collection_name, Jsonb *metadata_json, int32 create_mode) { CollectionDescriptor descriptor{collection_name, owner_name, build_collection_table_name(collection_name), "RESID", "DATA", "ETAG", "", "", nullptr, false}; CollectionDescriptor existingDescriptor; int spiStatus = SPI_OK_CONNECT; if (collection_name.empty()) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("DBMS_SODA.CREATE_COLLECTION does not allow empty collection name"))); } if (create_mode != DBMS_SODA_CREATE_MODE_DDL && create_mode != DBMS_SODA_CREATE_MODE_MAP) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("DBMS_SODA.CREATE_COLLECTION invalid create mode"), errdetail("create_mode=%d", create_mode))); } descriptor.isMapped_ = create_mode == DBMS_SODA_CREATE_MODE_MAP; apply_metadata(metadata_json, &descriptor); ensure_metadata_table(owner_name); spiStatus = SPI_connect(); if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed in DBMS_SODA.CREATE_COLLECTION"), errdetail("spi_status=%d", spiStatus))); } if (fetch_collection_descriptor(owner_name, collection_name, &existingDescriptor)) { SPI_finish(); return existingDescriptor; } if (table_exists(owner_name, descriptor.tableName_)) { if (create_mode == DBMS_SODA_CREATE_MODE_MAP || create_mode == DBMS_SODA_CREATE_MODE_DDL) { descriptor.isMapped_ = true; descriptor.metadataJson_ = copy_jsonb_to_registry_context(build_metadata_json(descriptor)); validate_collection_table(descriptor); insert_collection_descriptor(descriptor); SPI_finish(); return descriptor; } } if (create_mode == DBMS_SODA_CREATE_MODE_MAP) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_TABLE), errmsg("DBMS_SODA.CREATE_COLLECTION MAP mode requires existing table"), errdetail("table_name=%s", descriptor.tableName_.c_str()))); } descriptor.metadataJson_ = copy_jsonb_to_registry_context(build_metadata_json(descriptor)); create_physical_collection(descriptor); insert_collection_descriptor(descriptor); SPI_finish(); return descriptor; } static bool open_collection(const std::string &owner_name, const std::string &collection_name, CollectionDescriptor *descriptor) { int spiStatus = SPI_OK_CONNECT; bool foundCollection = false; if (collection_name.empty()) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("DBMS_SODA.OPEN_COLLECTION does not allow empty collection name"))); } spiStatus = SPI_connect(); if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed in DBMS_SODA.OPEN_COLLECTION"), errdetail("spi_status=%d", spiStatus))); } if (!metadata_table_exists(owner_name)) { SPI_finish(); return false; } foundCollection = fetch_collection_descriptor(owner_name, collection_name, descriptor); if (!foundCollection) { SPI_finish(); return false; } validate_collection_table(*descriptor); SPI_finish(); return true; } static Datum drop_collection(const std::string &owner_name, const std::string &collection_name, bool purge, bool drop_mapped_table) { CollectionDescriptor descriptor; Oid argTypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; const char nulls[2] = {' ', ' '}; std::string deleteSql = "DELETE FROM " + build_metadata_qualified_name(owner_name) + " WHERE collection_schema = $1 AND collection_name = $2"; int spiStatus = SPI_OK_CONNECT; int executeStatus = SPI_OK_DELETE; std::string actionSql; bool foundCollection = false; bool shouldDropTable = false; if (collection_name.empty()) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("DBMS_SODA.DROP_COLLECTION does not allow empty collection name"))); } values[0] = CStringGetTextDatum(owner_name.c_str()); values[1] = CStringGetTextDatum(collection_name.c_str()); spiStatus = SPI_connect(); if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed in DBMS_SODA.DROP_COLLECTION"), errdetail("spi_status=%d", spiStatus))); } if (!metadata_table_exists(owner_name)) { SPI_finish(); return DirectFunctionCall1(int4_numeric, Int32GetDatum(0)); } foundCollection = fetch_collection_descriptor(owner_name, collection_name, &descriptor); if (!foundCollection) { SPI_finish(); return DirectFunctionCall1(int4_numeric, Int32GetDatum(0)); } shouldDropTable = !descriptor.isMapped_ || drop_mapped_table; if (table_exists(descriptor.schemaName_, descriptor.tableName_)) { if (shouldDropTable) { actionSql = "DROP TABLE " + build_qualified_name(descriptor.schemaName_, descriptor.tableName_); } else { actionSql = "TRUNCATE TABLE " + build_qualified_name(descriptor.schemaName_, descriptor.tableName_); } executeStatus = SPI_execute(actionSql.c_str(), false, 0); if (executeStatus != SPI_OK_UTILITY) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA failed to drop collection storage"), errdetail("spi_status=%d, collection_name=%s", executeStatus, descriptor.collectionName_.c_str()))); } } executeStatus = SPI_execute_with_args(deleteSql.c_str(), 2, argTypes, values, nulls, false, 0); if (executeStatus != SPI_OK_DELETE) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA failed to delete collection metadata"), errdetail("spi_status=%d, collection_name=%s", executeStatus, descriptor.collectionName_.c_str()))); } SPI_finish(); (void) purge; return DirectFunctionCall1(int4_numeric, Int32GetDatum(1)); } static ArrayType * list_collection_names(const std::string &owner_name) { Oid argTypes[1] = {TEXTOID}; Datum values[1]; const char nulls[1] = {' '}; std::string selectSql = "SELECT collection_name FROM " + build_metadata_qualified_name(owner_name) + " WHERE collection_schema = $1 ORDER BY collection_name"; int spiStatus = SPI_OK_CONNECT; int executeStatus = SPI_OK_SELECT; std::vector collectionNames; spiStatus = SPI_connect(); if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed in DBMS_SODA.LIST_COLLECTION_NAMES"), errdetail("spi_status=%d", spiStatus))); } if (!metadata_table_exists(owner_name)) { SPI_finish(); return construct_array(nullptr, 0, 8943, -1, false, TYPALIGN_INT); } values[0] = CStringGetTextDatum(owner_name.c_str()); executeStatus = SPI_execute_with_args(selectSql.c_str(), 1, argTypes, values, nulls, true, 0); if (executeStatus != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA failed to list collection names"), errdetail("spi_status=%d", executeStatus))); } for (uint64 rowIndex = 0; rowIndex < SPI_processed; ++rowIndex) { bool isNull = false; char *collectionNameCString = TextDatumGetCString(SPI_getbinval(SPI_tuptable->vals[rowIndex], SPI_tuptable->tupdesc, 1, &isNull)); if (!isNull && collectionNameCString != nullptr) { collectionNames.emplace_back(collectionNameCString); pfree(collectionNameCString); } } SPI_finish(); std::vector collectionNameDatums; collectionNameDatums.reserve(collectionNames.size()); for (const std::string &collectionName : collectionNames) { collectionNameDatums.push_back(CStringGetTextDatum(collectionName.c_str())); } return construct_array(collectionNameDatums.empty() ? nullptr : collectionNameDatums.data(), static_cast(collectionNameDatums.size()), 8943, -1, false, TYPALIGN_INT); } static int32 register_collection(const CollectionDescriptor &descriptor); } // namespace DbmsSoda extern "C" Datum dbms_soda_create_collection(PG_FUNCTION_ARGS) { text *_collectionNameText = PG_GETARG_TEXT_PP(0); text *_metadataText = PG_ARGISNULL(1) ? nullptr : PG_GETARG_TEXT_PP(1); int32 createMode = PG_ARGISNULL(2) ? DBMS_SODA_CREATE_MODE_DDL : PG_GETARG_INT32(2); std::string ownerName = DbmsSoda::resolve_owner_name(); char *_collectionNameCString = text_to_cstring(_collectionNameText); Jsonb *_metadataJson = _metadataText == nullptr ? nullptr : DbmsSoda::parse_metadata_json(_metadataText); DbmsSoda::CollectionDescriptor descriptor; ereport(LOG, (errmsg("DBMS_SODA.CREATE_COLLECTION call"), errdetail("collection_name=%s, metadata_is_null=%s, create_mode=%d", _collectionNameCString, _metadataJson == nullptr ? "true" : "false", createMode))); descriptor = DbmsSoda::create_collection(ownerName, std::string(_collectionNameCString), _metadataJson, createMode); pfree(_collectionNameCString); PG_RETURN_INT32(DbmsSoda::register_collection(descriptor)); } extern "C" Datum dbms_soda_open_collection(PG_FUNCTION_ARGS) { text *_collectionNameText = PG_GETARG_TEXT_PP(0); std::string ownerName = DbmsSoda::resolve_owner_name(); char *_collectionNameCString = text_to_cstring(_collectionNameText); DbmsSoda::CollectionDescriptor descriptor; bool foundCollection = false; ereport(LOG, (errmsg("DBMS_SODA.OPEN_COLLECTION call"), errdetail("collection_name=%s", _collectionNameCString))); foundCollection = DbmsSoda::open_collection(ownerName, std::string(_collectionNameCString), &descriptor); pfree(_collectionNameCString); if (!foundCollection) { PG_RETURN_NULL(); } PG_RETURN_INT32(DbmsSoda::register_collection(descriptor)); } extern "C" Datum dbms_soda_drop_collection(PG_FUNCTION_ARGS) { text *_collectionNameText = PG_GETARG_TEXT_PP(0); bool purge = PG_ARGISNULL(1) ? false : PG_GETARG_BOOL(1); bool dropMappedTable = PG_ARGISNULL(2) ? false : PG_GETARG_BOOL(2); std::string ownerName = DbmsSoda::resolve_owner_name(); char *_collectionNameCString = text_to_cstring(_collectionNameText); Datum resultValue; ereport(LOG, (errmsg("DBMS_SODA.DROP_COLLECTION call"), errdetail("collection_name=%s, purge=%s, drop_mapped_table=%s", _collectionNameCString, purge ? "true" : "false", dropMappedTable ? "true" : "false"))); resultValue = DbmsSoda::drop_collection(ownerName, std::string(_collectionNameCString), purge, dropMappedTable); pfree(_collectionNameCString); PG_RETURN_DATUM(resultValue); } extern "C" Datum dbms_soda_list_collection_names(PG_FUNCTION_ARGS) { std::string ownerName = DbmsSoda::resolve_owner_name(); ereport(LOG, (errmsg("DBMS_SODA.LIST_COLLECTION_NAMES call"), errdetail("schema=%s", ownerName.c_str()))); PG_RETURN_ARRAYTYPE_P(DbmsSoda::list_collection_names(ownerName)); } namespace DbmsSoda { static const Oid kNvarchar2Oid = 8943; static const int32 kDocVarchar2 = 1; static const int32 kDocBlob = 2; static const int32 kDocClob = 3; static const int32 kDocJson = 4; struct DocumentDescriptor { std::string key_; std::string content_; std::string version_; std::string mediaType_; TimestampTz createdOn_; TimestampTz lastModified_; int32 contentDataType_; bool contentIsNull_; bool versionIsNull_; bool mediaTypeIsNull_; bool createdOnIsNull_; bool lastModifiedIsNull_; bool contentDataTypeIsNull_; }; struct OperationState { int32 handle_; CollectionDescriptor collection_; std::string key_; std::vector keyList_; std::string filterSpec_; std::string version_; std::string hint_; std::string asOfTimestamp_; int32 limit_; int32 skip_; int64 asOfScn_; double samplePct_; int64 sampleSeed_; int32 sampleMethod_; bool acquireLock_; bool asOfScnIsSet_; bool sampleIsSet_; bool sampleSeedIsSet_; }; struct CursorState { int32 handle_; std::vector documents_; size_t position_; }; static std::unordered_map operationRegistry_; static std::unordered_map cursorRegistry_; static std::unordered_map collectionRegistry_; static std::unordered_map documentRegistry_; static int32 nextOperationHandle_ = 1; static int32 nextCursorHandle_ = 1; static int32 nextCollectionHandle_ = 1; static int32 nextDocumentHandle_ = 1; static std::string quoted_column(const std::string &column_name) { return quoteidentifier_copy(column_name); } static std::string quote_literal_value(const std::string &text_value) { char *_quotedValue = quote_literal_cstr(text_value.c_str()); std::string quotedValue = _quotedValue == nullptr ? "NULL" : std::string(_quotedValue); if (_quotedValue != nullptr) { pfree(_quotedValue); } return quotedValue; } static std::string datum_to_text_copy(Datum value) { char *_valueCString = TextDatumGetCString(value); std::string resultValue = _valueCString == nullptr ? "" : std::string(_valueCString); if (_valueCString != nullptr) { pfree(_valueCString); } return resultValue; } static std::string datum_to_bytea_string(Datum value) { bytea *byteaValue = DatumGetByteaPP(value); std::string resultValue(VARDATA_ANY(byteaValue), VARSIZE_ANY_EXHDR(byteaValue)); if (reinterpret_cast(byteaValue) != DatumGetPointer(value)) { pfree(byteaValue); } return resultValue; } static Datum build_number_datum(int64 value) { return DirectFunctionCall1(int8_numeric, Int64GetDatum(value)); } static Jsonb * parse_json_string(const std::string &json_text) { Datum jsonDatum = DirectFunctionCall1(jsonb_in, CStringGetDatum(json_text.c_str())); return DatumGetJsonbP(jsonDatum); } static std::vector> jsonb_object_fields(JsonbContainer *container) { std::vector> fields; JsonbIterator *iterator = JsonbIteratorInit(container); JsonbValue value; JsonbIteratorToken token; std::string currentKey; while ((token = JsonbIteratorNext(&iterator, &value, true)) != WJB_DONE) { if (token == WJB_KEY) { currentKey.assign(value.val.string.val, value.val.string.len); } else if (token == WJB_VALUE) { fields.push_back({currentKey, value}); } } return fields; } static std::vector jsonb_array_elements(JsonbContainer *container) { std::vector elements; JsonbIterator *iterator = JsonbIteratorInit(container); JsonbValue value; JsonbIteratorToken token; while ((token = JsonbIteratorNext(&iterator, &value, true)) != WJB_DONE) { if (token == WJB_ELEM) { elements.push_back(value); } } return elements; } static std::string json_string_literal(const std::string &text_value) { std::string resultValue = "\""; for (char valueChar : text_value) { switch (valueChar) { case '\\': resultValue += "\\\\"; break; case '"': resultValue += "\\\""; break; case '\b': resultValue += "\\b"; break; case '\f': resultValue += "\\f"; break; case '\n': resultValue += "\\n"; break; case '\r': resultValue += "\\r"; break; case '\t': resultValue += "\\t"; break; default: resultValue += valueChar; break; } } resultValue += "\""; return resultValue; } static std::string jsonb_value_to_json_text(const JsonbValue &json_value) { switch (json_value.type) { case jbvNull: return "null"; case jbvString: return json_string_literal(std::string(json_value.val.string.val, json_value.val.string.len)); case jbvNumeric: { char *numericCString = DatumGetCString(DirectFunctionCall1(numeric_out, NumericGetDatum(json_value.val.numeric))); std::string resultValue(numericCString); pfree(numericCString); return resultValue; } case jbvBool: return json_value.val.boolean ? "true" : "false"; case jbvBinary: { char *jsonCString = JsonbToCString(nullptr, json_value.val.binary.data, json_value.val.binary.len); std::string resultValue = jsonCString == nullptr ? "" : std::string(jsonCString); if (jsonCString != nullptr) { pfree(jsonCString); } return resultValue; } default: break; } ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA filter contains unsupported JSON value"))); } static std::string jsonb_value_to_text(const JsonbValue &json_value) { switch (json_value.type) { case jbvString: return std::string(json_value.val.string.val, json_value.val.string.len); case jbvNumeric: { char *numericCString = DatumGetCString(DirectFunctionCall1(numeric_out, NumericGetDatum(json_value.val.numeric))); std::string resultValue(numericCString); pfree(numericCString); return resultValue; } case jbvBool: return json_value.val.boolean ? "true" : "false"; case jbvNull: return "null"; default: return jsonb_value_to_json_text(json_value); } } static bool jsonb_value_is_numeric(const JsonbValue &json_value) { return json_value.type == jbvNumeric; } static bool jsonb_value_as_bool(const JsonbValue &json_value) { if (json_value.type != jbvBool) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA filter operator expects a boolean value"))); } return json_value.val.boolean; } static std::string json_path_array_sql(const std::vector &path_segments) { if (path_segments.empty()) { return "ARRAY[]::text[]"; } std::string resultValue = "ARRAY["; for (size_t segmentIndex = 0; segmentIndex < path_segments.size(); ++segmentIndex) { if (segmentIndex > 0) { resultValue += ", "; } resultValue += quote_literal_value(path_segments[segmentIndex]); } resultValue += "]"; return resultValue; } static std::string jsonb_path_expr(const std::string &content_column, const std::vector &path_segments) { return "(" + content_column + " #> " + json_path_array_sql(path_segments) + ")"; } static std::string jsonb_path_text_expr(const std::string &content_column, const std::vector &path_segments) { return "(" + content_column + " #>> " + json_path_array_sql(path_segments) + ")"; } static std::string combine_predicates(const std::vector &predicates, const char *separator_text) { if (predicates.empty()) { return "TRUE"; } std::string resultValue = "(" + predicates[0] + ")"; for (size_t predicateIndex = 1; predicateIndex < predicates.size(); ++predicateIndex) { resultValue += separator_text; resultValue += "(" + predicates[predicateIndex] + ")"; } return resultValue; } static std::vector build_json_value_list(const JsonbValue &operand_value, bool as_json) { if (operand_value.type != jbvBinary || !JsonContainerIsArray(operand_value.val.binary.data)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA filter operator expects an array value"))); } std::vector values; for (const JsonbValue &elementValue : jsonb_array_elements(operand_value.val.binary.data)) { values.push_back(quote_literal_value(as_json ? jsonb_value_to_json_text(elementValue) : jsonb_value_to_text(elementValue))); } return values; } static std::string build_sql_in_list(const std::vector &values, const char *type_suffix) { if (values.empty()) { return "(NULL)"; } std::string resultValue = "(" + values[0] + type_suffix; for (size_t valueIndex = 1; valueIndex < values.size(); ++valueIndex) { resultValue += ", " + values[valueIndex] + type_suffix; } resultValue += ")"; return resultValue; } static std::string build_qbe_predicate(const std::string &content_column, const JsonbValue &query_value, const std::vector &path_segments); static std::string build_qbe_operator_predicate(const std::string &content_column, const std::string &operator_name, const JsonbValue &operand_value, const std::vector &path_segments) { std::string jsonExpr = jsonb_path_expr(content_column, path_segments); std::string textExpr = jsonb_path_text_expr(content_column, path_segments); if (operator_name == "$eq") { return jsonExpr + " = " + quote_literal_value(jsonb_value_to_json_text(operand_value)) + "::jsonb"; } if (operator_name == "$ne") { return "(" + jsonExpr + " IS NULL OR " + jsonExpr + " <> " + quote_literal_value(jsonb_value_to_json_text(operand_value)) + "::jsonb)"; } if (operator_name == "$exists") { return jsonExpr + (jsonb_value_as_bool(operand_value) ? " IS NOT NULL" : " IS NULL"); } if (operator_name == "$like") { return textExpr + " LIKE " + quote_literal_value(jsonb_value_to_text(operand_value)); } if (operator_name == "$regex") { return textExpr + " ~ " + quote_literal_value(jsonb_value_to_text(operand_value)); } if (operator_name == "$in" || operator_name == "$nin") { std::string inPredicate; if (operand_value.type != jbvBinary || !JsonContainerIsArray(operand_value.val.binary.data)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA filter operator expects an array value"), errdetail("operator=%s", operator_name.c_str()))); } bool numericValues = true; for (const JsonbValue &elementValue : jsonb_array_elements(operand_value.val.binary.data)) { numericValues = numericValues && jsonb_value_is_numeric(elementValue); } if (numericValues) { inPredicate = "(" + textExpr + ")::numeric IN " + build_sql_in_list(build_json_value_list(operand_value, false), "::numeric"); } else { inPredicate = jsonExpr + " IN " + build_sql_in_list(build_json_value_list(operand_value, true), "::jsonb"); } return operator_name == "$in" ? inPredicate : "NOT (" + inPredicate + ")"; } if (operator_name == "$not") { return "NOT (" + build_qbe_predicate(content_column, operand_value, path_segments) + ")"; } if (operator_name == "$gt" || operator_name == "$lt" || operator_name == "$gte" || operator_name == "$lte") { const char *sqlOperator = operator_name == "$gt" ? " > " : operator_name == "$lt" ? " < " : operator_name == "$gte" ? " >= " : " <= "; if (operand_value.type == jbvNumeric) { return "(" + textExpr + ")::numeric" + sqlOperator + jsonb_value_to_text(operand_value) + "::numeric"; } return textExpr + sqlOperator + quote_literal_value(jsonb_value_to_text(operand_value)); } ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("SODA filter operator is not supported"), errdetail("operator=%s", operator_name.c_str()))); } static std::string build_qbe_logical_predicate(const std::string &content_column, const std::string &operator_name, const JsonbValue &operand_value, const std::vector &path_segments) { if (operand_value.type != jbvBinary || !JsonContainerIsArray(operand_value.val.binary.data)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA logical filter operator expects an array"))); } std::vector predicates; for (const JsonbValue &elementValue : jsonb_array_elements(operand_value.val.binary.data)) { predicates.push_back(build_qbe_predicate(content_column, elementValue, path_segments)); } return combine_predicates(predicates, operator_name == "$and" ? " AND " : " OR "); } static std::string build_qbe_predicate(const std::string &content_column, const JsonbValue &query_value, const std::vector &path_segments) { if (query_value.type == jbvBinary && JsonContainerIsObject(query_value.val.binary.data)) { std::vector predicates; bool hasOperator = false; for (const auto &fieldValue : jsonb_object_fields(query_value.val.binary.data)) { const std::string &fieldName = fieldValue.first; const JsonbValue &fieldJsonValue = fieldValue.second; if (!fieldName.empty() && fieldName[0] == '$') { hasOperator = true; if (fieldName == "$and" || fieldName == "$or") { predicates.push_back(build_qbe_logical_predicate(content_column, fieldName, fieldJsonValue, path_segments)); } else { predicates.push_back(build_qbe_operator_predicate(content_column, fieldName, fieldJsonValue, path_segments)); } } } if (hasOperator) { return combine_predicates(predicates, " AND "); } for (const auto &fieldValue : jsonb_object_fields(query_value.val.binary.data)) { std::vector childPath = path_segments; childPath.push_back(fieldValue.first); predicates.push_back(build_qbe_predicate(content_column, fieldValue.second, childPath)); } return combine_predicates(predicates, " AND "); } return jsonb_path_expr(content_column, path_segments) + " = " + quote_literal_value(jsonb_value_to_json_text(query_value)) + "::jsonb"; } static std::string build_qbe_filter_predicate(const std::string &content_column, const std::string &filter_spec) { Jsonb *filterJson = parse_json_string(filter_spec); JsonbValue rootValue; JsonbToJsonbValue(filterJson, &rootValue); return build_qbe_predicate(content_column, rootValue, {}); } static DocumentDescriptor build_empty_document() { DocumentDescriptor document; document.createdOn_ = 0; document.lastModified_ = 0; document.contentDataType_ = kDocVarchar2; document.contentIsNull_ = true; document.versionIsNull_ = true; document.mediaTypeIsNull_ = true; document.createdOnIsNull_ = true; document.lastModifiedIsNull_ = true; document.contentDataTypeIsNull_ = true; return document; } static int32 register_collection(const CollectionDescriptor &descriptor) { int32 handleValue = nextCollectionHandle_++; collectionRegistry_[handleValue] = descriptor; return handleValue; } static int32 register_document(const DocumentDescriptor &document) { int32 handleValue = nextDocumentHandle_++; documentRegistry_[handleValue] = document; return handleValue; } static CollectionDescriptor * lookup_collection(int32 handle_value) { auto collectionIterator = collectionRegistry_.find(handle_value); if (collectionIterator == collectionRegistry_.end()) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid SODA collection handle"), errdetail("handle=%d", handle_value))); } return &collectionIterator->second; } static DocumentDescriptor * lookup_document(int32 handle_value) { auto documentIterator = documentRegistry_.find(handle_value); if (documentIterator == documentRegistry_.end()) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid SODA document handle"), errdetail("handle=%d", handle_value))); } return &documentIterator->second; } static CollectionDescriptor resolve_collection_from_handle(int32 handle_value) { CollectionDescriptor descriptor = *lookup_collection(handle_value); if (descriptor.collectionName_.empty()) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA collection argument must include collection_name"))); } if (descriptor.schemaName_.empty()) { descriptor.schemaName_ = resolve_owner_name(); } return descriptor; } static bool column_exists(const std::string &owner_name, const std::string &table_name, const std::string &column_name) { Oid argTypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; const char nulls[3] = {' ', ' ', ' '}; std::string selectSql = "SELECT EXISTS (" "SELECT 1 FROM information_schema.columns " "WHERE table_schema = $1 AND table_name = $2 AND column_name = $3)"; bool isNull = false; int executeStatus = SPI_OK_SELECT; values[0] = CStringGetTextDatum(owner_name.c_str()); values[1] = CStringGetTextDatum(table_name.c_str()); values[2] = CStringGetTextDatum(column_name.c_str()); executeStatus = SPI_execute_with_args(selectSql.c_str(), 3, argTypes, values, nulls, true, 1); if (executeStatus != SPI_OK_SELECT || SPI_processed != 1) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA column lookup failed"), errdetail("spi_status=%d", executeStatus))); } return DatumGetBool(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isNull)); } static std::string build_document_select_sql(const CollectionDescriptor &descriptor, const std::string &where_clause, int32 limit_value, int32 skip_value, bool include_content, bool for_update) { bool hasMediaType = column_exists(descriptor.schemaName_, descriptor.tableName_, "media_type"); bool hasContentDataType = column_exists(descriptor.schemaName_, descriptor.tableName_, "content_data_type"); bool hasCreatedOn = !descriptor.creationTimeColumnName_.empty() && column_exists(descriptor.schemaName_, descriptor.tableName_, descriptor.creationTimeColumnName_); bool hasLastModified = !descriptor.lastModifiedColumnName_.empty() && column_exists(descriptor.schemaName_, descriptor.tableName_, descriptor.lastModifiedColumnName_); std::string contentExpr = include_content ? quoted_column(descriptor.contentColumnName_) : "NULL::text"; std::string mediaTypeExpr = hasMediaType ? "\"media_type\"" : "NULL::text"; std::string createdExpr = hasCreatedOn ? quoted_column(descriptor.creationTimeColumnName_) : "NULL::timestamptz"; std::string modifiedExpr = hasLastModified ? quoted_column(descriptor.lastModifiedColumnName_) : "NULL::timestamptz"; std::string dataTypeExpr = hasContentDataType ? "\"content_data_type\"" : "NULL::int4"; std::string selectSql = "SELECT " + quoted_column(descriptor.keyColumnName_) + ", " + contentExpr + "::text, " + quoted_column(descriptor.versionColumnName_) + ", " + mediaTypeExpr + "::text, " + createdExpr + ", " + modifiedExpr + ", " + dataTypeExpr + " " + "FROM " + build_qualified_name(descriptor.schemaName_, descriptor.tableName_); if (!where_clause.empty()) { selectSql += " WHERE " + where_clause; } selectSql += " ORDER BY " + quoted_column(descriptor.keyColumnName_); if (limit_value >= 0) { selectSql += " LIMIT " + std::to_string(limit_value); } if (skip_value > 0) { selectSql += " OFFSET " + std::to_string(skip_value); } if (for_update) { selectSql += " FOR UPDATE"; } return selectSql; } static std::vector read_text_array(ArrayType *array_value) { Datum *elements = nullptr; bool *nulls = nullptr; int elementCount = 0; std::vector resultValues; deconstruct_array(array_value, kNvarchar2Oid, -1, false, TYPALIGN_INT, &elements, &nulls, &elementCount); for (int elementIndex = 0; elementIndex < elementCount; ++elementIndex) { if (!nulls[elementIndex]) { resultValues.push_back(datum_to_text_copy(elements[elementIndex])); } } if (elements != nullptr) { pfree(elements); } if (nulls != nullptr) { pfree(nulls); } return resultValues; } static DocumentDescriptor build_document_from_row(SPITupleTable *tuptable, uint64 row_index) { DocumentDescriptor document = build_empty_document(); bool isNull = false; Datum keyDatum = SPI_getbinval(tuptable->vals[row_index], tuptable->tupdesc, 1, &isNull); if (!isNull) { document.key_ = datum_to_text_copy(keyDatum); } Datum contentDatum = SPI_getbinval(tuptable->vals[row_index], tuptable->tupdesc, 2, &isNull); if (!isNull) { document.content_ = datum_to_text_copy(contentDatum); document.contentIsNull_ = false; } Datum versionDatum = SPI_getbinval(tuptable->vals[row_index], tuptable->tupdesc, 3, &isNull); if (!isNull) { document.version_ = datum_to_text_copy(versionDatum); document.versionIsNull_ = false; } Datum mediaTypeDatum = SPI_getbinval(tuptable->vals[row_index], tuptable->tupdesc, 4, &isNull); if (!isNull) { document.mediaType_ = datum_to_text_copy(mediaTypeDatum); document.mediaTypeIsNull_ = false; } else { document.mediaType_ = "application/json"; document.mediaTypeIsNull_ = false; } Datum createdOnDatum = SPI_getbinval(tuptable->vals[row_index], tuptable->tupdesc, 5, &isNull); if (!isNull) { document.createdOn_ = DatumGetTimestampTz(createdOnDatum); document.createdOnIsNull_ = false; } Datum lastModifiedDatum = SPI_getbinval(tuptable->vals[row_index], tuptable->tupdesc, 6, &isNull); if (!isNull) { document.lastModified_ = DatumGetTimestampTz(lastModifiedDatum); document.lastModifiedIsNull_ = false; } Datum contentDataTypeDatum = SPI_getbinval(tuptable->vals[row_index], tuptable->tupdesc, 7, &isNull); if (!isNull) { document.contentDataType_ = DatumGetInt32(contentDataTypeDatum); document.contentDataTypeIsNull_ = false; } else { document.contentDataType_ = kDocJson; document.contentDataTypeIsNull_ = false; } return document; } static OperationState * lookup_operation(int32 handle_value) { auto operationIt = operationRegistry_.find(handle_value); if (operationIt == operationRegistry_.end()) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA operation handle is invalid"), errdetail("handle=%d", handle_value))); } return &operationIt->second; } static CursorState * lookup_cursor(int32 handle_value) { auto cursorIt = cursorRegistry_.find(handle_value); if (cursorIt == cursorRegistry_.end()) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA cursor handle is invalid"), errdetail("handle=%d", handle_value))); } return &cursorIt->second; } static void validate_operation_execution(const OperationState &operation, bool allow_lock, bool reject_lock = true) { if (operation.asOfScnIsSet_ || !operation.asOfTimestamp_.empty()) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("SODA as-of operations are not supported yet"))); } if (!allow_lock && reject_lock && operation.acquireLock_) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA acquire_lock is not allowed for this operation"))); } } static std::string build_sample_predicate(const OperationState &operation) { if (!operation.sampleIsSet_) { return ""; } int64 threshold = static_cast(operation.samplePct_ * 10000.0); std::string seedText = operation.sampleSeedIsSet_ ? std::to_string(operation.sampleSeed_) : "0"; return "(((hashtext((" + quoted_column(operation.collection_.keyColumnName_) + "::text || ':' || " + quote_literal_value(seedText) + ")::text)::bigint + 2147483648) % 1000000) < " + std::to_string(threshold) + ")"; } static std::string build_operation_where_clause(const OperationState &operation, bool include_sample) { std::vector predicates; if (!operation.key_.empty()) { validate_raw_key_value(operation.collection_, operation.key_); predicates.push_back(quoted_column(operation.collection_.keyColumnName_) + " = " + quote_literal_value(operation.key_)); } if (!operation.keyList_.empty()) { for (const std::string &keyValue : operation.keyList_) { validate_raw_key_value(operation.collection_, keyValue); } std::string keyListPredicate = quoted_column(operation.collection_.keyColumnName_) + " IN (" + quote_literal_value(operation.keyList_[0]); for (size_t keyIndex = 1; keyIndex < operation.keyList_.size(); ++keyIndex) { keyListPredicate += ", " + quote_literal_value(operation.keyList_[keyIndex]); } keyListPredicate += ")"; predicates.push_back(keyListPredicate); } if (!operation.filterSpec_.empty()) { predicates.push_back(build_qbe_filter_predicate( quoted_column(operation.collection_.contentColumnName_), operation.filterSpec_)); } if (!operation.version_.empty()) { predicates.push_back(quoted_column(operation.collection_.versionColumnName_) + " = " + quote_literal_value(operation.version_)); } if (include_sample && operation.sampleIsSet_) { predicates.push_back(build_sample_predicate(operation)); } if (predicates.empty()) { return ""; } std::string whereClause = predicates[0]; for (size_t i = 1; i < predicates.size(); ++i) { whereClause += " AND " + predicates[i]; } return whereClause; } static int32 create_operation(const CollectionDescriptor &descriptor) { OperationState operation; operation.handle_ = nextOperationHandle_++; operation.collection_ = descriptor; operation.limit_ = -1; operation.skip_ = 0; operation.asOfScn_ = 0; operation.samplePct_ = 0; operation.sampleSeed_ = 0; operation.sampleMethod_ = 0; operation.acquireLock_ = false; operation.asOfScnIsSet_ = false; operation.sampleIsSet_ = false; operation.sampleSeedIsSet_ = false; operationRegistry_[operation.handle_] = operation; return operation.handle_; } static DocumentDescriptor fetch_single_document(const CollectionDescriptor &descriptor, const std::string &where_clause, bool include_content, bool for_update, bool volatile_select, bool *found_document) { std::string selectSql = build_document_select_sql(descriptor, where_clause, 1, 0, include_content, for_update); int executeStatus = SPI_execute(selectSql.c_str(), !for_update && !volatile_select, 1); if (executeStatus != SPI_OK_SELECT) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA document fetch failed"), errdetail("spi_status=%d", executeStatus))); } *found_document = SPI_processed == 1; if (!*found_document) { return build_empty_document(); } return build_document_from_row(SPI_tuptable, 0); } static DocumentDescriptor insert_document(const CollectionDescriptor &descriptor, const DocumentDescriptor &document, bool include_content) { bool hasMediaType = column_exists(descriptor.schemaName_, descriptor.tableName_, "media_type"); bool hasContentDataType = column_exists(descriptor.schemaName_, descriptor.tableName_, "content_data_type"); bool hasCreatedOn = !descriptor.creationTimeColumnName_.empty() && column_exists(descriptor.schemaName_, descriptor.tableName_, descriptor.creationTimeColumnName_); bool hasLastModified = !descriptor.lastModifiedColumnName_.empty() && column_exists(descriptor.schemaName_, descriptor.tableName_, descriptor.lastModifiedColumnName_); std::vector columns; std::vector values; std::string returnMediaType = hasMediaType ? "\"media_type\"" : "NULL::text"; std::string returnCreated = hasCreatedOn ? quoted_column(descriptor.creationTimeColumnName_) : "NULL::timestamptz"; std::string returnModified = hasLastModified ? quoted_column(descriptor.lastModifiedColumnName_) : "NULL::timestamptz"; std::string returnDataType = hasContentDataType ? "\"content_data_type\"" : "NULL::int4"; std::string insertSql; int executeStatus = SPI_OK_INSERT_RETURNING; if (!document.key_.empty()) { validate_raw_key_value(descriptor, document.key_); columns.push_back(quoted_column(descriptor.keyColumnName_)); values.push_back(quote_literal_value(document.key_)); } columns.push_back(quoted_column(descriptor.contentColumnName_)); values.push_back(quote_literal_value(document.content_) + "::jsonb"); if (hasMediaType) { columns.push_back("\"media_type\""); values.push_back(quote_literal_value(document.mediaType_)); } if (hasContentDataType && !document.contentDataTypeIsNull_) { columns.push_back("\"content_data_type\""); values.push_back(std::to_string(document.contentDataType_)); } insertSql = "INSERT INTO " + build_qualified_name(descriptor.schemaName_, descriptor.tableName_) + " (" + columns[0]; for (size_t i = 1; i < columns.size(); ++i) { insertSql += ", " + columns[i]; } insertSql += ") VALUES (" + values[0]; for (size_t i = 1; i < values.size(); ++i) { insertSql += ", " + values[i]; } insertSql += ") RETURNING " + quoted_column(descriptor.keyColumnName_) + ", " + (include_content ? quoted_column(descriptor.contentColumnName_) + "::text" : "NULL::text") + ", " + quoted_column(descriptor.versionColumnName_) + ", " + returnMediaType + "::text, " + returnCreated + ", " + returnModified + ", " + returnDataType; executeStatus = SPI_execute(insertSql.c_str(), false, 1); if (executeStatus != SPI_OK_INSERT_RETURNING || SPI_processed != 1) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA insert failed"), errdetail("spi_status=%d", executeStatus))); } return build_document_from_row(SPI_tuptable, 0); } static DocumentDescriptor update_document_by_key(const CollectionDescriptor &descriptor, const std::string &key_value, const DocumentDescriptor &document, bool include_content) { bool hasMediaType = column_exists(descriptor.schemaName_, descriptor.tableName_, "media_type"); bool hasContentDataType = column_exists(descriptor.schemaName_, descriptor.tableName_, "content_data_type"); bool hasLastModified = !descriptor.lastModifiedColumnName_.empty() && column_exists(descriptor.schemaName_, descriptor.tableName_, descriptor.lastModifiedColumnName_); bool hasCreatedOn = !descriptor.creationTimeColumnName_.empty() && column_exists(descriptor.schemaName_, descriptor.tableName_, descriptor.creationTimeColumnName_); std::vector assignments; std::string returnMediaType = hasMediaType ? "\"media_type\"" : "NULL::text"; std::string returnCreated = hasCreatedOn ? quoted_column(descriptor.creationTimeColumnName_) : "NULL::timestamptz"; std::string returnModified = hasLastModified ? quoted_column(descriptor.lastModifiedColumnName_) : "NULL::timestamptz"; std::string returnDataType = hasContentDataType ? "\"content_data_type\"" : "NULL::int4"; int executeStatus = SPI_OK_UPDATE_RETURNING; assignments.push_back(quoted_column(descriptor.contentColumnName_) + " = " + quote_literal_value(document.content_) + "::jsonb"); assignments.push_back(quoted_column(descriptor.versionColumnName_) + " = upper(replace(gen_random_uuid()::text, '-', ''))"); if (hasMediaType) { assignments.push_back("\"media_type\" = " + quote_literal_value(document.mediaType_)); } if (hasContentDataType && !document.contentDataTypeIsNull_) { assignments.push_back("\"content_data_type\" = " + std::to_string(document.contentDataType_)); } if (hasLastModified) { assignments.push_back(quoted_column(descriptor.lastModifiedColumnName_) + " = clock_timestamp()"); } std::string updateSql = "UPDATE " + build_qualified_name(descriptor.schemaName_, descriptor.tableName_) + " SET " + assignments[0]; for (size_t i = 1; i < assignments.size(); ++i) { updateSql += ", " + assignments[i]; } updateSql += " WHERE " + quoted_column(descriptor.keyColumnName_) + " = " + quote_literal_value(key_value) + " RETURNING " + quoted_column(descriptor.keyColumnName_) + ", " + (include_content ? quoted_column(descriptor.contentColumnName_) + "::text" : "NULL::text") + ", " + quoted_column(descriptor.versionColumnName_) + ", " + returnMediaType + "::text, " + returnCreated + ", " + returnModified + ", " + returnDataType; executeStatus = SPI_execute(updateSql.c_str(), false, 1); if (executeStatus != SPI_OK_UPDATE_RETURNING) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA update failed"), errdetail("spi_status=%d", executeStatus))); } if (SPI_processed != 1) { return build_empty_document(); } return build_document_from_row(SPI_tuptable, 0); } static bool document_exists_by_key(const CollectionDescriptor &descriptor, const std::string &key_value) { std::string selectSql = "SELECT 1 FROM " + build_qualified_name(descriptor.schemaName_, descriptor.tableName_) + " WHERE " + quoted_column(descriptor.keyColumnName_) + " = " + quote_literal_value(key_value) + " LIMIT 1"; int executeStatus = SPI_execute(selectSql.c_str(), true, 1); if (executeStatus != SPI_OK_SELECT) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA existence check failed"), errdetail("spi_status=%d", executeStatus))); } return SPI_processed == 1; } static DocumentDescriptor save_document(const CollectionDescriptor &descriptor, const DocumentDescriptor &document, bool include_content) { if (!document.key_.empty() && document_exists_by_key(descriptor, document.key_)) { return update_document_by_key(descriptor, document.key_, document, include_content); } return insert_document(descriptor, document, include_content); } static std::string get_data_guide(const CollectionDescriptor &descriptor, int32 format_value, int32 pretty_value) { Oid argTypes[4] = {TEXTOID, TEXTOID, INT4OID, INT4OID}; Datum values[4]; const char nulls[4] = {' ', ' ', ' ', ' '}; bool isNull = false; std::string selectSql = "SELECT pg_catalog.dbms_json_get_index_dataguide($1, $2, $3, $4)"; values[0] = CStringGetTextDatum((descriptor.schemaName_ + "." + descriptor.tableName_).c_str()); values[1] = CStringGetTextDatum(descriptor.contentColumnName_.c_str()); values[2] = Int32GetDatum(format_value); values[3] = Int32GetDatum(pretty_value); int executeStatus = SPI_execute_with_args(selectSql.c_str(), 4, argTypes, values, nulls, true, 1); if (executeStatus != SPI_OK_SELECT || SPI_processed != 1) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA data guide lookup failed"), errdetail("spi_status=%d", executeStatus))); } Datum guideDatum = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isNull); if (isNull) { return ""; } return datum_to_text_copy(guideDatum); } static std::string get_index_name_from_spec(Jsonb *specification_json) { JsonbValue rootValue; JsonbValue nameBuffer; JsonbValue *nameValue = nullptr; if (specification_json == nullptr) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA index specification must not be null"))); } JsonbToJsonbValue(specification_json, &rootValue); if (rootValue.type != jbvBinary || !JsonContainerIsObject(rootValue.val.binary.data)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA index specification must be a JSON object"))); } nameValue = get_object_field(rootValue.val.binary.data, "name", &nameBuffer); if (nameValue == nullptr) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA index specification must include name"))); } return jsonb_value_to_string(nameValue); } static bool fetch_index_spec(const std::string &owner_name, const std::string &collection_name, const std::string &index_name, std::string *specification_text) { Oid argTypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; const char nulls[3] = {' ', ' ', ' '}; std::string selectSql = "SELECT specification::text FROM " + build_index_metadata_qualified_name(owner_name) + " WHERE collection_schema = $1 AND collection_name = $2 AND index_name = $3"; bool isNull = false; int executeStatus = SPI_OK_SELECT; values[0] = CStringGetTextDatum(owner_name.c_str()); values[1] = CStringGetTextDatum(collection_name.c_str()); values[2] = CStringGetTextDatum(index_name.c_str()); executeStatus = SPI_execute_with_args(selectSql.c_str(), 3, argTypes, values, nulls, true, 1); if (executeStatus != SPI_OK_SELECT) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA index metadata lookup failed"), errdetail("spi_status=%d", executeStatus))); } if (SPI_processed == 0) { return false; } *specification_text = datum_to_text_copy( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isNull)); return true; } static bool jsonb_object_string_field(JsonbContainer *container, const char *field_name, std::string *field_value) { JsonbValue valueBuffer; JsonbValue *fieldValue = get_object_field(container, field_name, &valueBuffer); if (fieldValue == nullptr) { return false; } *field_value = jsonb_value_to_string(fieldValue); return true; } static bool jsonb_object_bool_field(JsonbContainer *container, const char *field_name, bool default_value) { JsonbValue valueBuffer; JsonbValue *fieldValue = get_object_field(container, field_name, &valueBuffer); if (fieldValue == nullptr) { return default_value; } if (fieldValue->type != jbvBool) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA index specification boolean field has invalid type"), errdetail("field=%s", field_name))); } return fieldValue->val.boolean; } static std::string trim_soda_path(const std::string &path_value) { size_t startIndex = 0; size_t endIndex = path_value.length(); while (startIndex < endIndex && std::isspace(static_cast(path_value[startIndex]))) { ++startIndex; } while (endIndex > startIndex && std::isspace(static_cast(path_value[endIndex - 1]))) { --endIndex; } std::string trimmedValue = path_value.substr(startIndex, endIndex - startIndex); if (trimmedValue.rfind("$.", 0) == 0) { trimmedValue = trimmedValue.substr(2); } else if (!trimmedValue.empty() && trimmedValue[0] == '$') { trimmedValue = trimmedValue.substr(1); if (!trimmedValue.empty() && trimmedValue[0] == '.') { trimmedValue = trimmedValue.substr(1); } } return trimmedValue; } static std::vector soda_path_segments(const std::string &path_value) { std::vector segments; std::string trimmedPath = trim_soda_path(path_value); size_t segmentStart = 0; while (segmentStart <= trimmedPath.length()) { size_t segmentEnd = trimmedPath.find('.', segmentStart); std::string segment = trimmedPath.substr( segmentStart, segmentEnd == std::string::npos ? std::string::npos : segmentEnd - segmentStart); if (!segment.empty()) { segments.push_back(segment); } if (segmentEnd == std::string::npos) { break; } segmentStart = segmentEnd + 1; } if (segments.empty()) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA index field path must not be empty"))); } return segments; } static std::string index_field_expression(const std::string &content_column, const std::string &path_value, const std::string &datatype_value, const std::string &order_value) { std::string textExpr = jsonb_path_text_expr(content_column, soda_path_segments(path_value)); std::string normalizedType = datatype_value; std::string normalizedOrder = order_value; std::string resultValue; for (char &typeChar : normalizedType) { typeChar = static_cast(std::tolower(static_cast(typeChar))); } for (char &orderChar : normalizedOrder) { orderChar = static_cast(std::tolower(static_cast(orderChar))); } if (normalizedType == "number" || normalizedType == "numeric" || normalizedType == "double" || normalizedType == "integer") { resultValue = "(" + textExpr + ")::numeric"; } else if (normalizedType == "boolean" || normalizedType == "bool") { resultValue = "(" + textExpr + ")::boolean"; } else if (normalizedType == "json" || normalizedType == "jsonb") { resultValue = jsonb_path_expr(content_column, soda_path_segments(path_value)); } else { resultValue = textExpr; } if (normalizedOrder == "asc") { resultValue = "(" + resultValue + ") ASC"; } else if (normalizedOrder == "desc") { resultValue = "(" + resultValue + ") DESC"; } else if (!normalizedOrder.empty()) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA index specification field order is invalid"), errdetail("order=%s", order_value.c_str()))); } return resultValue; } static std::string build_index_create_sql(const CollectionDescriptor &descriptor, const std::string &index_name, Jsonb *specification_json) { JsonbValue rootValue; JsonbValue fieldsBuffer; JsonbValue *fieldsValue = nullptr; JsonbToJsonbValue(specification_json, &rootValue); if (rootValue.type != jbvBinary || !JsonContainerIsObject(rootValue.val.binary.data)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA index specification must be a JSON object"))); } fieldsValue = get_object_field(rootValue.val.binary.data, "fields", &fieldsBuffer); if (fieldsValue == nullptr) { return "CREATE INDEX " + quoteidentifier_copy(index_name) + " ON " + build_qualified_name(descriptor.schemaName_, descriptor.tableName_) + " USING GIN (" + quoted_column(descriptor.contentColumnName_) + ")"; } if (fieldsValue->type != jbvBinary || !JsonContainerIsArray(fieldsValue->val.binary.data)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA index specification fields must be an array"))); } std::vector indexExpressions; bool uniqueIndex = jsonb_object_bool_field(rootValue.val.binary.data, "unique", false); for (const JsonbValue &fieldValue : jsonb_array_elements(fieldsValue->val.binary.data)) { std::string pathValue; std::string datatypeValue; std::string orderValue; if (fieldValue.type != jbvBinary || !JsonContainerIsObject(fieldValue.val.binary.data)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA index specification field must be a JSON object"))); } if (!jsonb_object_string_field(fieldValue.val.binary.data, "path", &pathValue)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA index specification field must include path"))); } if (!jsonb_object_string_field(fieldValue.val.binary.data, "datatype", &datatypeValue)) { (void) jsonb_object_string_field(fieldValue.val.binary.data, "type", &datatypeValue); } (void) jsonb_object_string_field(fieldValue.val.binary.data, "order", &orderValue); indexExpressions.push_back(index_field_expression(quoted_column(descriptor.contentColumnName_), pathValue, datatypeValue, orderValue)); } if (indexExpressions.empty()) { return "CREATE INDEX " + quoteidentifier_copy(index_name) + " ON " + build_qualified_name(descriptor.schemaName_, descriptor.tableName_) + " USING GIN (" + quoted_column(descriptor.contentColumnName_) + ")"; } std::string createSql = "CREATE "; if (uniqueIndex) { createSql += "UNIQUE "; } createSql += "INDEX " + quoteidentifier_copy(index_name) + " ON " + build_qualified_name(descriptor.schemaName_, descriptor.tableName_) + " (" + indexExpressions[0]; for (size_t expressionIndex = 1; expressionIndex < indexExpressions.size(); ++expressionIndex) { createSql += ", " + indexExpressions[expressionIndex]; } createSql += ")"; return createSql; } static int32 create_index(const CollectionDescriptor &descriptor, Jsonb *specification_json) { std::string indexName = get_index_name_from_spec(specification_json); Oid argTypes[4] = {TEXTOID, TEXTOID, TEXTOID, JSONBOID}; Datum values[4]; const char nulls[4] = {' ', ' ', ' ', ' '}; std::string existingSpec; std::string createSql = build_index_create_sql(descriptor, indexName, specification_json); std::string insertSql = "INSERT INTO " + build_index_metadata_qualified_name(descriptor.schemaName_) + " (collection_schema, collection_name, index_name, specification) " "VALUES ($1, $2, $3, $4)"; int executeStatus = SPI_OK_UTILITY; if (fetch_index_spec(descriptor.schemaName_, descriptor.collectionName_, indexName, &existingSpec) || table_exists(descriptor.schemaName_, indexName)) { return 0; } executeStatus = SPI_execute(createSql.c_str(), false, 0); if (executeStatus != SPI_OK_UTILITY) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA create_index failed"), errdetail("spi_status=%d, index_name=%s", executeStatus, indexName.c_str()))); } values[0] = CStringGetTextDatum(descriptor.schemaName_.c_str()); values[1] = CStringGetTextDatum(descriptor.collectionName_.c_str()); values[2] = CStringGetTextDatum(indexName.c_str()); values[3] = JsonbPGetDatum(specification_json); executeStatus = SPI_execute_with_args(insertSql.c_str(), 4, argTypes, values, nulls, false, 0); if (executeStatus != SPI_OK_INSERT) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA create_index metadata registration failed"), errdetail("spi_status=%d, index_name=%s", executeStatus, indexName.c_str()))); } return 1; } static int32 drop_index(const CollectionDescriptor &descriptor, const std::string &index_name, bool force_value) { Oid argTypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; const char nulls[3] = {' ', ' ', ' '}; std::string existingSpec; std::string dropSql = "DROP INDEX " + build_qualified_name(descriptor.schemaName_, index_name); std::string deleteSql = "DELETE FROM " + build_index_metadata_qualified_name(descriptor.schemaName_) + " WHERE collection_schema = $1 AND collection_name = $2 AND index_name = $3"; int executeStatus = SPI_OK_DELETE; bool hasMetadata = fetch_index_spec(descriptor.schemaName_, descriptor.collectionName_, index_name, &existingSpec); bool hasPhysicalIndex = table_exists(descriptor.schemaName_, index_name); if (!hasMetadata && !hasPhysicalIndex) { return 0; } if (hasPhysicalIndex) { executeStatus = SPI_execute(dropSql.c_str(), false, 0); if (executeStatus != SPI_OK_UTILITY) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA drop_index failed"), errdetail("spi_status=%d, index_name=%s", executeStatus, index_name.c_str()))); } } values[0] = CStringGetTextDatum(descriptor.schemaName_.c_str()); values[1] = CStringGetTextDatum(descriptor.collectionName_.c_str()); values[2] = CStringGetTextDatum(index_name.c_str()); executeStatus = SPI_execute_with_args(deleteSql.c_str(), 3, argTypes, values, nulls, false, 0); if (executeStatus != SPI_OK_DELETE) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA drop_index metadata delete failed"), errdetail("spi_status=%d, index_name=%s", executeStatus, index_name.c_str()))); } (void) force_value; return 1; } static std::vector list_index_specs(const CollectionDescriptor &descriptor) { Oid argTypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; const char nulls[2] = {' ', ' '}; std::string selectSql = "SELECT specification::text FROM " + build_index_metadata_qualified_name(descriptor.schemaName_) + " WHERE collection_schema = $1 AND collection_name = $2 ORDER BY index_name"; std::vector specificationValues; int executeStatus = SPI_OK_SELECT; bool isNull = false; values[0] = CStringGetTextDatum(descriptor.schemaName_.c_str()); values[1] = CStringGetTextDatum(descriptor.collectionName_.c_str()); executeStatus = SPI_execute_with_args(selectSql.c_str(), 2, argTypes, values, nulls, true, 0); if (executeStatus != SPI_OK_SELECT) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_SODA list_indexes failed"), errdetail("spi_status=%d", executeStatus))); } for (uint64 rowIndex = 0; rowIndex < SPI_processed; ++rowIndex) { Datum specDatum = SPI_getbinval(SPI_tuptable->vals[rowIndex], SPI_tuptable->tupdesc, 1, &isNull); if (!isNull) { specificationValues.push_back(datum_to_text_copy(specDatum)); } } return specificationValues; } static void validate_document_data_type(int32 actual_type, int32 expected_type, const char *method_name) { if (actual_type != expected_type) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA document content type mismatch"), errdetail("%s expects document data type %d, actual data type is %d", method_name, expected_type, actual_type))); } } static bytea * bytea_from_string(const std::string &value) { bytea *resultValue = reinterpret_cast(palloc(VARHDRSZ + value.length())); SET_VARSIZE(resultValue, VARHDRSZ + value.length()); if (!value.empty()) { memcpy(VARDATA(resultValue), value.data(), value.length()); } return resultValue; } static std::string oracle_timestamp_utc_text(TimestampTz timestamp_value) { struct pg_tm tm; fsec_t fsec = 0; int tz = 0; pg_tz *utcTimezone = pg_tzset("UTC"); char timestampBuffer[32]; if (timestamp2tm(timestamp_value, &tz, &tm, &fsec, nullptr, utcTimezone) != 0) { ereport(ERROR, (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE), errmsg("timestamp out of range"))); } std::snprintf(timestampBuffer, sizeof(timestampBuffer), "%04d-%02d-%02dT%02d:%02d:%02d.%06dZ", tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, static_cast(fsec)); return std::string(timestampBuffer); } } // namespace DbmsSoda extern "C" Datum dbms_soda_create_document(PG_FUNCTION_ARGS) { DbmsSoda::DocumentDescriptor document = DbmsSoda::build_empty_document(); if (!PG_ARGISNULL(0)) { document.key_ = DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(0)); } if (!PG_ARGISNULL(1)) { document.content_ = DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(1)); document.contentIsNull_ = false; document.contentDataType_ = DbmsSoda::kDocJson; document.contentDataTypeIsNull_ = false; } if (!PG_ARGISNULL(2)) { document.mediaType_ = DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(2)); document.mediaTypeIsNull_ = false; } else { document.mediaType_ = "application/json"; document.mediaTypeIsNull_ = false; } PG_RETURN_INT32(DbmsSoda::register_document(document)); } extern "C" Datum soda_document_construct_varchar2(PG_FUNCTION_ARGS) { DbmsSoda::DocumentDescriptor document = DbmsSoda::build_empty_document(); if (!PG_ARGISNULL(0)) { document.key_ = DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(0)); } if (!PG_ARGISNULL(1)) { document.content_ = DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(1)); document.contentIsNull_ = false; } document.contentDataType_ = DbmsSoda::kDocVarchar2; document.contentDataTypeIsNull_ = false; document.mediaType_ = PG_ARGISNULL(2) ? "application/json" : DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(2)); document.mediaTypeIsNull_ = false; PG_RETURN_INT32(DbmsSoda::register_document(document)); } extern "C" Datum soda_document_construct_blob(PG_FUNCTION_ARGS) { DbmsSoda::DocumentDescriptor document = DbmsSoda::build_empty_document(); if (!PG_ARGISNULL(0)) { document.key_ = DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(0)); } if (!PG_ARGISNULL(1)) { document.content_ = DbmsSoda::datum_to_bytea_string(PG_GETARG_DATUM(1)); document.contentIsNull_ = false; } document.contentDataType_ = DbmsSoda::kDocBlob; document.contentDataTypeIsNull_ = false; document.mediaType_ = PG_ARGISNULL(2) ? "application/json" : DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(2)); document.mediaTypeIsNull_ = false; PG_RETURN_INT32(DbmsSoda::register_document(document)); } extern "C" Datum soda_document_construct_clob(PG_FUNCTION_ARGS) { DbmsSoda::DocumentDescriptor document = DbmsSoda::build_empty_document(); if (!PG_ARGISNULL(0)) { document.key_ = DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(0)); } if (!PG_ARGISNULL(1)) { document.content_ = DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(1)); document.contentIsNull_ = false; } document.contentDataType_ = DbmsSoda::kDocClob; document.contentDataTypeIsNull_ = false; document.mediaType_ = PG_ARGISNULL(2) ? "application/json" : DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(2)); document.mediaTypeIsNull_ = false; PG_RETURN_INT32(DbmsSoda::register_document(document)); } extern "C" Datum soda_document_construct_json(PG_FUNCTION_ARGS) { DbmsSoda::DocumentDescriptor document = DbmsSoda::build_empty_document(); if (!PG_ARGISNULL(0)) { document.key_ = DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(0)); } if (!PG_ARGISNULL(1)) { char *jsonCString = DatumGetCString(DirectFunctionCall1(json_out, PG_GETARG_DATUM(1))); document.content_ = jsonCString == nullptr ? "" : std::string(jsonCString); if (jsonCString != nullptr) { pfree(jsonCString); } document.contentIsNull_ = false; } document.contentDataType_ = DbmsSoda::kDocJson; document.contentDataTypeIsNull_ = false; document.mediaType_ = "application/json"; document.mediaTypeIsNull_ = false; PG_RETURN_INT32(DbmsSoda::register_document(document)); } extern "C" Datum soda_document_get_blob(PG_FUNCTION_ARGS) { DbmsSoda::DocumentDescriptor *document = DbmsSoda::lookup_document(PG_GETARG_INT32(0)); DbmsSoda::validate_document_data_type(document->contentDataType_, DbmsSoda::kDocBlob, "SODA_DOCUMENT_T.GET_BLOB"); if (!document->contentIsNull_) { PG_RETURN_BYTEA_P(DbmsSoda::bytea_from_string(document->content_)); } PG_RETURN_NULL(); } extern "C" Datum soda_document_get_clob(PG_FUNCTION_ARGS) { DbmsSoda::DocumentDescriptor *document = DbmsSoda::lookup_document(PG_GETARG_INT32(0)); DbmsSoda::validate_document_data_type(document->contentDataType_, DbmsSoda::kDocClob, "SODA_DOCUMENT_T.GET_CLOB"); if (document->contentIsNull_) { PG_RETURN_NULL(); } PG_RETURN_TEXT_P(cstring_to_text(document->content_.c_str())); } extern "C" Datum soda_document_get_created_on(PG_FUNCTION_ARGS) { DbmsSoda::DocumentDescriptor *document = DbmsSoda::lookup_document(PG_GETARG_INT32(0)); std::string timestampText; if (document->createdOnIsNull_) { PG_RETURN_NULL(); } timestampText = DbmsSoda::oracle_timestamp_utc_text(document->createdOn_); PG_RETURN_TEXT_P(cstring_to_text(timestampText.c_str())); } extern "C" Datum soda_document_get_data_type(PG_FUNCTION_ARGS) { DbmsSoda::DocumentDescriptor *document = DbmsSoda::lookup_document(PG_GETARG_INT32(0)); PG_RETURN_INT32(document->contentDataType_); } extern "C" Datum soda_document_get_json(PG_FUNCTION_ARGS) { DbmsSoda::DocumentDescriptor *document = DbmsSoda::lookup_document(PG_GETARG_INT32(0)); DbmsSoda::validate_document_data_type(document->contentDataType_, DbmsSoda::kDocJson, "SODA_DOCUMENT_T.GET_JSON"); if (document->contentIsNull_) { PG_RETURN_NULL(); } PG_RETURN_DATUM(DirectFunctionCall1(json_in, CStringGetDatum(document->content_.c_str()))); } extern "C" Datum soda_document_get_key(PG_FUNCTION_ARGS) { DbmsSoda::DocumentDescriptor *document = DbmsSoda::lookup_document(PG_GETARG_INT32(0)); if (document->key_.empty()) { PG_RETURN_NULL(); } PG_RETURN_TEXT_P(cstring_to_text(document->key_.c_str())); } extern "C" Datum soda_document_get_last_modified(PG_FUNCTION_ARGS) { DbmsSoda::DocumentDescriptor *document = DbmsSoda::lookup_document(PG_GETARG_INT32(0)); std::string timestampText; if (document->lastModifiedIsNull_) { PG_RETURN_NULL(); } timestampText = DbmsSoda::oracle_timestamp_utc_text(document->lastModified_); PG_RETURN_TEXT_P(cstring_to_text(timestampText.c_str())); } extern "C" Datum soda_document_get_media_type(PG_FUNCTION_ARGS) { DbmsSoda::DocumentDescriptor *document = DbmsSoda::lookup_document(PG_GETARG_INT32(0)); if (document->mediaTypeIsNull_) { PG_RETURN_TEXT_P(cstring_to_text("application/json")); } PG_RETURN_TEXT_P(cstring_to_text(document->mediaType_.c_str())); } extern "C" Datum soda_document_get_varchar2(PG_FUNCTION_ARGS) { DbmsSoda::DocumentDescriptor *document = DbmsSoda::lookup_document(PG_GETARG_INT32(0)); DbmsSoda::validate_document_data_type(document->contentDataType_, DbmsSoda::kDocVarchar2, "SODA_DOCUMENT_T.GET_VARCHAR2"); if (document->contentIsNull_) { PG_RETURN_NULL(); } PG_RETURN_TEXT_P(cstring_to_text(document->content_.c_str())); } extern "C" Datum soda_document_get_version(PG_FUNCTION_ARGS) { DbmsSoda::DocumentDescriptor *document = DbmsSoda::lookup_document(PG_GETARG_INT32(0)); if (document->versionIsNull_) { PG_RETURN_NULL(); } PG_RETURN_TEXT_P(cstring_to_text(document->version_.c_str())); } extern "C" Datum soda_collection_create_index(PG_FUNCTION_ARGS) { DbmsSoda::CollectionDescriptor descriptor = DbmsSoda::resolve_collection_from_handle(PG_GETARG_INT32(0)); text *specificationText = PG_GETARG_TEXT_PP(1); Jsonb *specificationJson = DbmsSoda::parse_metadata_json(specificationText); int spiStatus = SPI_OK_CONNECT; int32 resultValue; DbmsSoda::ensure_index_metadata_table(descriptor.schemaName_); spiStatus = SPI_connect(); if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errmsg("SPI_connect failed in SODA collection create_index"))); } resultValue = DbmsSoda::create_index(descriptor, specificationJson); SPI_finish(); PG_RETURN_DATUM(DbmsSoda::build_number_datum(resultValue)); } extern "C" Datum soda_collection_drop_index(PG_FUNCTION_ARGS) { DbmsSoda::CollectionDescriptor descriptor = DbmsSoda::resolve_collection_from_handle(PG_GETARG_INT32(0)); std::string indexName = DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(1)); bool forceValue = PG_ARGISNULL(2) ? false : PG_GETARG_BOOL(2); int spiStatus = SPI_OK_CONNECT; int32 resultValue; DbmsSoda::ensure_index_metadata_table(descriptor.schemaName_); spiStatus = SPI_connect(); if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errmsg("SPI_connect failed in SODA collection drop_index"))); } resultValue = DbmsSoda::drop_index(descriptor, indexName, forceValue); SPI_finish(); PG_RETURN_DATUM(DbmsSoda::build_number_datum(resultValue)); } extern "C" Datum soda_collection_get_index(PG_FUNCTION_ARGS) { DbmsSoda::CollectionDescriptor descriptor = DbmsSoda::resolve_collection_from_handle(PG_GETARG_INT32(0)); std::string indexName = DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(1)); std::string schemaName = PG_ARGISNULL(2) ? descriptor.schemaName_ : DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(2)); int spiStatus = SPI_OK_CONNECT; std::string specificationText; DbmsSoda::ensure_index_metadata_table(schemaName); spiStatus = SPI_connect(); if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errmsg("SPI_connect failed in SODA collection get_index"))); } if (!DbmsSoda::fetch_index_spec(schemaName, descriptor.collectionName_, indexName, &specificationText)) { SPI_finish(); PG_RETURN_NULL(); } SPI_finish(); PG_RETURN_TEXT_P(cstring_to_text(specificationText.c_str())); } extern "C" Datum soda_collection_list_indexes(PG_FUNCTION_ARGS) { DbmsSoda::CollectionDescriptor descriptor = DbmsSoda::resolve_collection_from_handle(PG_GETARG_INT32(0)); int spiStatus = SPI_OK_CONNECT; std::vector specificationValues; DbmsSoda::ensure_index_metadata_table(descriptor.schemaName_); spiStatus = SPI_connect(); if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errmsg("SPI_connect failed in SODA collection list_indexes"))); } specificationValues = DbmsSoda::list_index_specs(descriptor); SPI_finish(); std::vector specificationDatums; specificationDatums.reserve(specificationValues.size()); for (const std::string &specificationValue : specificationValues) { specificationDatums.push_back(CStringGetTextDatum(specificationValue.c_str())); } PG_RETURN_ARRAYTYPE_P(construct_array(specificationDatums.empty() ? nullptr : specificationDatums.data(), static_cast(specificationDatums.size()), TEXTOID, -1, false, TYPALIGN_INT)); } extern "C" Datum soda_collection_get_name(PG_FUNCTION_ARGS) { DbmsSoda::CollectionDescriptor descriptor = DbmsSoda::resolve_collection_from_handle(PG_GETARG_INT32(0)); PG_RETURN_TEXT_P(cstring_to_text(descriptor.collectionName_.c_str())); } extern "C" Datum soda_collection_get_metadata(PG_FUNCTION_ARGS) { DbmsSoda::CollectionDescriptor descriptor = DbmsSoda::resolve_collection_from_handle(PG_GETARG_INT32(0)); PG_RETURN_TEXT_P(cstring_to_text(DbmsSoda::jsonb_to_text_copy(descriptor.metadataJson_).c_str())); } extern "C" Datum soda_collection_truncate(PG_FUNCTION_ARGS) { DbmsSoda::CollectionDescriptor descriptor = DbmsSoda::resolve_collection_from_handle(PG_GETARG_INT32(0)); int spiStatus = SPI_connect(); std::string truncateSql = "TRUNCATE TABLE " + DbmsSoda::build_qualified_name(descriptor.schemaName_, descriptor.tableName_); int executeStatus = SPI_OK_UTILITY; if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed in SODA collection truncate"))); } executeStatus = SPI_execute(truncateSql.c_str(), false, 0); if (executeStatus != SPI_OK_UTILITY) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SODA collection truncate failed"), errdetail("spi_status=%d", executeStatus))); } SPI_finish(); PG_RETURN_DATUM(DbmsSoda::build_number_datum(1)); } extern "C" Datum soda_collection_find(PG_FUNCTION_ARGS) { DbmsSoda::CollectionDescriptor descriptor = DbmsSoda::resolve_collection_from_handle(PG_GETARG_INT32(0)); PG_RETURN_INT32(DbmsSoda::create_operation(descriptor)); } extern "C" Datum soda_collection_find_one_internal(PG_FUNCTION_ARGS) { DbmsSoda::CollectionDescriptor descriptor = DbmsSoda::resolve_collection_from_handle(PG_GETARG_INT32(0)); std::string keyValue = DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(1)); int spiStatus = SPI_connect(); bool foundDocument = false; DbmsSoda::DocumentDescriptor document; if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errmsg("SPI_connect failed in SODA collection find_one"))); } DbmsSoda::validate_raw_key_value(descriptor, keyValue); document = DbmsSoda::fetch_single_document( descriptor, DbmsSoda::quoted_column(descriptor.keyColumnName_) + " = " + DbmsSoda::quote_literal_value(keyValue), true, false, false, &foundDocument); SPI_finish(); if (!foundDocument) { PG_RETURN_NULL(); } PG_RETURN_INT32(DbmsSoda::register_document(document)); } extern "C" Datum soda_collection_insert_one(PG_FUNCTION_ARGS) { DbmsSoda::CollectionDescriptor descriptor = DbmsSoda::resolve_collection_from_handle(PG_GETARG_INT32(0)); DbmsSoda::DocumentDescriptor document = *DbmsSoda::lookup_document(PG_GETARG_INT32(1)); int spiStatus = SPI_connect(); if (document.contentIsNull_) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA document content must not be null"))); } if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errmsg("SPI_connect failed in SODA collection insert_one"))); } (void) DbmsSoda::insert_document(descriptor, document, false); SPI_finish(); PG_RETURN_DATUM(DbmsSoda::build_number_datum(1)); } extern "C" Datum soda_collection_insert_one_and_get_internal(PG_FUNCTION_ARGS) { DbmsSoda::CollectionDescriptor descriptor = DbmsSoda::resolve_collection_from_handle(PG_GETARG_INT32(0)); DbmsSoda::DocumentDescriptor document = *DbmsSoda::lookup_document(PG_GETARG_INT32(1)); int spiStatus = SPI_connect(); DbmsSoda::DocumentDescriptor resultDocument; if (document.contentIsNull_) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA document content must not be null"))); } if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errmsg("SPI_connect failed in SODA collection insert_one_and_get"))); } resultDocument = DbmsSoda::insert_document(descriptor, document, false); SPI_finish(); PG_RETURN_INT32(DbmsSoda::register_document(resultDocument)); } extern "C" Datum soda_collection_save(PG_FUNCTION_ARGS) { DbmsSoda::CollectionDescriptor descriptor = DbmsSoda::resolve_collection_from_handle(PG_GETARG_INT32(0)); DbmsSoda::DocumentDescriptor document = *DbmsSoda::lookup_document(PG_GETARG_INT32(1)); int spiStatus = SPI_connect(); if (document.contentIsNull_) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA document content must not be null"))); } if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errmsg("SPI_connect failed in SODA collection save"))); } (void) DbmsSoda::save_document(descriptor, document, false); SPI_finish(); PG_RETURN_DATUM(DbmsSoda::build_number_datum(1)); } extern "C" Datum soda_collection_save_and_get_internal(PG_FUNCTION_ARGS) { DbmsSoda::CollectionDescriptor descriptor = DbmsSoda::resolve_collection_from_handle(PG_GETARG_INT32(0)); DbmsSoda::DocumentDescriptor document = *DbmsSoda::lookup_document(PG_GETARG_INT32(1)); int spiStatus = SPI_connect(); DbmsSoda::DocumentDescriptor resultDocument; if (document.contentIsNull_) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA document content must not be null"))); } if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errmsg("SPI_connect failed in SODA collection save_and_get"))); } resultDocument = DbmsSoda::save_document(descriptor, document, false); SPI_finish(); PG_RETURN_INT32(DbmsSoda::register_document(resultDocument)); } extern "C" Datum soda_collection_get_data_guide(PG_FUNCTION_ARGS) { DbmsSoda::CollectionDescriptor descriptor = DbmsSoda::resolve_collection_from_handle(PG_GETARG_INT32(0)); int spiStatus = SPI_connect(); std::string guideText; if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errmsg("SPI_connect failed in SODA get_data_guide"))); } guideText = DbmsSoda::get_data_guide(descriptor, 1, 0); SPI_finish(); PG_RETURN_TEXT_P(cstring_to_text(guideText.c_str())); } extern "C" Datum soda_collection_create_view_from_dg(PG_FUNCTION_ARGS) { DbmsSoda::CollectionDescriptor descriptor = DbmsSoda::resolve_collection_from_handle(PG_GETARG_INT32(0)); text *_guideText = PG_ARGISNULL(1) ? nullptr : DatumGetTextPP(PG_GETARG_DATUM(1)); std::string viewName = DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(2)); bool materialize = PG_ARGISNULL(3) ? false : PG_GETARG_BOOL(3); int32 mvRefreshMode = PG_ARGISNULL(4) ? 1 : PG_GETARG_INT32(4); std::string pathValue = PG_ARGISNULL(5) ? "$" : DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(5)); bool resolveNameConflicts = PG_ARGISNULL(6) ? false : PG_GETARG_BOOL(6); int spiStatus = SPI_connect(); Oid argTypes[11] = {TEXTOID, TEXTOID, TEXTOID, JSONBOID, TEXTOID, BOOLOID, INT4OID, TEXTOID, BOOLOID, TEXTOID, BOOLOID}; Datum values[11]; char *guideCString = nullptr; const char nulls[11] = {' ', ' ', ' ', ' ', 'n', ' ', ' ', ' ', ' ', 'n', ' '}; std::string selectSql = "SELECT pg_catalog.dbms_json_create_view($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)"; text *prefixText = PG_ARGISNULL(7) ? nullptr : DatumGetTextPP(PG_GETARG_DATUM(7)); bool mixedCaseColumns = PG_ARGISNULL(8) ? false : PG_GETARG_BOOL(8); if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errmsg("SPI_connect failed in SODA create_view_from_dg"))); } if (_guideText == nullptr) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA create_view_from_dg requires data guide"))); } values[0] = CStringGetTextDatum(viewName.c_str()); values[1] = CStringGetTextDatum((descriptor.schemaName_ + "." + descriptor.tableName_).c_str()); values[2] = CStringGetTextDatum(descriptor.contentColumnName_.c_str()); guideCString = text_to_cstring(_guideText); values[3] = DirectFunctionCall1(jsonb_in, CStringGetDatum(guideCString)); pfree(guideCString); values[4] = (Datum) 0; values[5] = BoolGetDatum(materialize); values[6] = Int32GetDatum(mvRefreshMode); values[7] = CStringGetTextDatum(pathValue.c_str()); values[8] = BoolGetDatum(resolveNameConflicts); values[9] = prefixText == nullptr ? (Datum) 0 : PointerGetDatum(prefixText); values[10] = BoolGetDatum(mixedCaseColumns); if (SPI_execute_with_args(selectSql.c_str(), 11, argTypes, values, nulls, false, 0) != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errmsg("SODA create_view_from_dg failed"))); } SPI_finish(); PG_RETURN_DATUM(DbmsSoda::build_number_datum(1)); } extern "C" Datum soda_operation_key(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::OperationState *operation = DbmsSoda::lookup_operation(handleValue); operation->key_ = DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(1)); DbmsSoda::validate_raw_key_value(operation->collection_, operation->key_); operation->keyList_.clear(); PG_RETURN_INT32(handleValue); } extern "C" Datum soda_operation_keys(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::OperationState *operation = DbmsSoda::lookup_operation(handleValue); ArrayType *keyArray = PG_GETARG_ARRAYTYPE_P(1); operation->key_.clear(); operation->keyList_ = DbmsSoda::read_text_array(keyArray); for (const std::string &keyValue : operation->keyList_) { DbmsSoda::validate_raw_key_value(operation->collection_, keyValue); } PG_RETURN_INT32(handleValue); } extern "C" Datum soda_operation_filter(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::OperationState *operation = DbmsSoda::lookup_operation(handleValue); std::string filterSpec = DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(1)); (void) DbmsSoda::parse_json_string(filterSpec); operation->filterSpec_ = filterSpec; PG_RETURN_INT32(handleValue); } extern "C" Datum soda_operation_limit(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::OperationState *operation = DbmsSoda::lookup_operation(handleValue); int32 limitValue = PG_GETARG_INT32(1); operation->limit_ = limitValue; PG_RETURN_INT32(handleValue); } extern "C" Datum soda_operation_skip(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::OperationState *operation = DbmsSoda::lookup_operation(handleValue); int32 skipValue = PG_GETARG_INT32(1); operation->skip_ = skipValue; PG_RETURN_INT32(handleValue); } extern "C" Datum soda_operation_version(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::OperationState *operation = DbmsSoda::lookup_operation(handleValue); operation->version_ = DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(1)); PG_RETURN_INT32(handleValue); } extern "C" Datum soda_operation_hint(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::OperationState *operation = DbmsSoda::lookup_operation(handleValue); operation->hint_ = DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(1)); PG_RETURN_INT32(handleValue); } extern "C" Datum soda_operation_acquire_lock(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::OperationState *operation = DbmsSoda::lookup_operation(handleValue); operation->acquireLock_ = true; PG_RETURN_INT32(handleValue); } extern "C" Datum soda_operation_as_of_scn(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::OperationState *operation = DbmsSoda::lookup_operation(handleValue); Numeric scnValue = DatumGetNumeric(PG_GETARG_DATUM(1)); ErrorSaveContext escontext = {T_ErrorSaveContext}; operation->asOfScn_ = numeric_int8_safe(scnValue, (Node *) &escontext); operation->asOfScnIsSet_ = true; PG_RETURN_INT32(handleValue); } extern "C" Datum soda_operation_as_of_timestamp(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::OperationState *operation = DbmsSoda::lookup_operation(handleValue); operation->asOfTimestamp_ = DbmsSoda::datum_to_text_copy(PG_GETARG_DATUM(1)); PG_RETURN_INT32(handleValue); } extern "C" Datum soda_operation_sample(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::OperationState *operation = DbmsSoda::lookup_operation(handleValue); double samplePct = DatumGetFloat8(PG_GETARG_DATUM(1)); if (samplePct < 0.000001 || samplePct >= 100.0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA sample percentage is out of range"), errdetail("pct=%g", samplePct))); } operation->samplePct_ = samplePct; operation->sampleSeedIsSet_ = !PG_ARGISNULL(2); operation->sampleSeed_ = PG_ARGISNULL(2) ? 0 : PG_GETARG_INT32(2); operation->sampleMethod_ = PG_ARGISNULL(3) ? 0 : PG_GETARG_INT32(3); operation->sampleIsSet_ = true; PG_RETURN_INT32(handleValue); } extern "C" Datum soda_operation_count(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::OperationState *operation = DbmsSoda::lookup_operation(handleValue); int spiStatus = SPI_connect(); std::string whereClause = DbmsSoda::build_operation_where_clause(*operation, true); std::string countSql = "SELECT count(*) FROM " + DbmsSoda::build_qualified_name(operation->collection_.schemaName_, operation->collection_.tableName_); bool isNull = false; if (!whereClause.empty()) { countSql += " WHERE " + whereClause; } DbmsSoda::validate_operation_execution(*operation, false); if (operation->skip_ > 0 || operation->limit_ >= 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA count does not allow skip or limit"))); } if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errmsg("SPI_connect failed in SODA operation count"))); } if (SPI_execute(countSql.c_str(), !operation->sampleIsSet_, 1) != SPI_OK_SELECT || SPI_processed != 1) { SPI_finish(); ereport(ERROR, (errmsg("SODA operation count failed"))); } int64 countValue = DatumGetInt64(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isNull)); SPI_finish(); PG_RETURN_DATUM(DbmsSoda::build_number_datum(countValue)); } extern "C" Datum soda_operation_get_data_guide(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::OperationState *operation = DbmsSoda::lookup_operation(handleValue); int32 formatValue = PG_ARGISNULL(1) ? 1 : PG_GETARG_INT32(1); int32 flagValue = PG_ARGISNULL(2) ? 0 : PG_GETARG_INT32(2); int spiStatus = SPI_connect(); std::string guideText; if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errmsg("SPI_connect failed in SODA operation get_data_guide"))); } DbmsSoda::validate_operation_execution(*operation, false); guideText = DbmsSoda::get_data_guide(operation->collection_, formatValue, flagValue); SPI_finish(); PG_RETURN_TEXT_P(cstring_to_text(guideText.c_str())); } extern "C" Datum soda_operation_get_one_internal(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::OperationState *operation = DbmsSoda::lookup_operation(handleValue); int spiStatus = SPI_connect(); std::string whereClause = DbmsSoda::build_operation_where_clause(*operation, true); bool foundDocument = false; DbmsSoda::DocumentDescriptor document; if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errmsg("SPI_connect failed in SODA operation get_one"))); } DbmsSoda::validate_operation_execution(*operation, true); document = DbmsSoda::fetch_single_document(operation->collection_, whereClause, true, operation->acquireLock_, operation->sampleIsSet_, &foundDocument); SPI_finish(); if (!foundDocument) { PG_RETURN_NULL(); } PG_RETURN_INT32(DbmsSoda::register_document(document)); } extern "C" Datum soda_operation_get_cursor(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::OperationState *operation = DbmsSoda::lookup_operation(handleValue); int spiStatus = SPI_connect(); std::string whereClause = DbmsSoda::build_operation_where_clause(*operation, true); std::string selectSql = DbmsSoda::build_document_select_sql(operation->collection_, whereClause, operation->limit_, operation->skip_, true, operation->acquireLock_); DbmsSoda::CursorState cursor; if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errmsg("SPI_connect failed in SODA operation get_cursor"))); } DbmsSoda::validate_operation_execution(*operation, true); if (operation->acquireLock_ && (operation->skip_ > 0 || operation->limit_ >= 0)) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA acquire_lock does not allow skip or limit"))); } if (SPI_execute(selectSql.c_str(), !operation->acquireLock_ && !operation->sampleIsSet_, 0) != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errmsg("SODA operation get_cursor failed"))); } cursor.handle_ = DbmsSoda::nextCursorHandle_++; cursor.position_ = 0; for (uint64 rowIndex = 0; rowIndex < SPI_processed; ++rowIndex) { cursor.documents_.push_back(DbmsSoda::build_document_from_row(SPI_tuptable, rowIndex)); } SPI_finish(); DbmsSoda::cursorRegistry_[cursor.handle_] = cursor; PG_RETURN_INT32(cursor.handle_); } extern "C" Datum soda_operation_remove(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::OperationState *operation = DbmsSoda::lookup_operation(handleValue); int spiStatus = SPI_connect(); std::string whereClause = DbmsSoda::build_operation_where_clause(*operation, false); std::string deleteSql = "DELETE FROM " + DbmsSoda::build_qualified_name(operation->collection_.schemaName_, operation->collection_.tableName_); if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errmsg("SPI_connect failed in SODA operation remove"))); } DbmsSoda::validate_operation_execution(*operation, false, false); if (!whereClause.empty()) { deleteSql += " WHERE " + whereClause; } if (SPI_execute(deleteSql.c_str(), false, 0) != SPI_OK_DELETE) { SPI_finish(); ereport(ERROR, (errmsg("SODA operation remove failed"))); } uint64 removedCount = SPI_processed; SPI_finish(); PG_RETURN_DATUM(DbmsSoda::build_number_datum(removedCount)); } extern "C" Datum soda_operation_replace_one(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::OperationState *operation = DbmsSoda::lookup_operation(handleValue); DbmsSoda::DocumentDescriptor document = *DbmsSoda::lookup_document(PG_GETARG_INT32(1)); int spiStatus = SPI_connect(); DbmsSoda::DocumentDescriptor resultDocument; if (operation->key_.empty()) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA operation replace_one requires key()"))); } DbmsSoda::validate_operation_execution(*operation, false, false); if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errmsg("SPI_connect failed in SODA operation replace_one"))); } resultDocument = DbmsSoda::update_document_by_key(operation->collection_, operation->key_, document, false); SPI_finish(); PG_RETURN_DATUM(DbmsSoda::build_number_datum(resultDocument.key_.empty() ? 0 : 1)); } extern "C" Datum soda_operation_replace_one_and_get_internal(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::OperationState *operation = DbmsSoda::lookup_operation(handleValue); DbmsSoda::DocumentDescriptor document = *DbmsSoda::lookup_document(PG_GETARG_INT32(1)); int spiStatus = SPI_connect(); DbmsSoda::DocumentDescriptor resultDocument; if (operation->key_.empty()) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SODA operation replace_one_and_get requires key()"))); } DbmsSoda::validate_operation_execution(*operation, false, false); if (spiStatus != SPI_OK_CONNECT) { ereport(ERROR, (errmsg("SPI_connect failed in SODA operation replace_one_and_get"))); } resultDocument = DbmsSoda::update_document_by_key(operation->collection_, operation->key_, document, false); SPI_finish(); if (resultDocument.key_.empty()) { PG_RETURN_NULL(); } PG_RETURN_INT32(DbmsSoda::register_document(resultDocument)); } extern "C" Datum soda_cursor_next_internal(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::CursorState *cursor = DbmsSoda::lookup_cursor(handleValue); if (cursor->position_ >= cursor->documents_.size()) { PG_RETURN_NULL(); } PG_RETURN_INT32(DbmsSoda::register_document(cursor->documents_[cursor->position_++])); } extern "C" Datum soda_cursor_has_next(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); DbmsSoda::CursorState *cursor = DbmsSoda::lookup_cursor(handleValue); PG_RETURN_BOOL(cursor->position_ < cursor->documents_.size()); } extern "C" Datum soda_cursor_close(PG_FUNCTION_ARGS) { int32 handleValue = PG_GETARG_INT32(0); (void) DbmsSoda::lookup_cursor(handleValue); DbmsSoda::cursorRegistry_.erase(handleValue); PG_RETURN_BOOL(true); }