#include "../nlohmann/json-schema.hpp" #include "dbms_json_schema.hpp" extern "C" { #include "utils/builtins.h" #include "utils/elog.h" #include "utils/fmgroids.h" #include "catalog/pg_type_d.h" #include "utils/jsonb.h" #include "funcapi.h" } // extern "C" #include #include #include #include #include #include #include extern "C" { PG_FUNCTION_INFO_V1(dbms_json_schema_is_schema_valid); PG_FUNCTION_INFO_V1(dbms_json_schema_is_schema_valid2); PG_FUNCTION_INFO_V1(dbms_json_schema_is_valid); PG_FUNCTION_INFO_V1(dbms_json_schema_validate_report); PG_FUNCTION_INFO_V1(dbms_json_schema_get_version); } #define RUDB_DBMS_JSON_SCHEMA_VERSION "1.0.0" #define DBMS_JSON_SCHEMA_VALID 1 #define DBMS_JSON_SCHEMA_INVALID 0 #define DBMS_JSON_SCHEMA_RAISE_NONE 0 #define DBMS_JSON_SCHEMA_RAISE_ERROR 1 namespace DbmsJsonSchema { using JsonDocument = nlohmann::json; using JsonValidator = nlohmann::json_schema::json_validator; struct ValidationIssue { std::string schemaPath_; std::string instancePath_; std::string code_; std::string error_; }; struct ValidationResult { bool schemaValid_{false}; bool dataValid_{false}; JsonDocument errorsReport_; std::string reportText_; }; class CollectingErrorHandler : public nlohmann::json_schema::error_handler { public: explicit CollectingErrorHandler(const JsonDocument *schema_document) : schemaDocument_(schema_document) { } std::vector issues_; void error(const nlohmann::json::json_pointer &ptr, const JsonDocument &instance, const std::string &message) override { issues_.push_back(buildIssue(ptr, schemaDocument_, instance, message)); } private: const JsonDocument *schemaDocument_{nullptr}; static bool isnumerictoken(const std::string &token) { return !token.empty() && std::all_of(token.begin(), token.end(), [](unsigned char ch) { return std::isdigit(ch) != 0; }); } static std::vector splitpointertokens(const nlohmann::json::json_pointer &ptr) { std::vector tokens; std::string pointerString = ptr.to_string(); if (pointerString.empty()) { return tokens; } std::size_t startPos = 1; while (startPos <= pointerString.size()) { std::size_t slashPos = pointerString.find('/', startPos); std::string token = pointerString.substr(startPos, slashPos - startPos); std::size_t replacePos = 0; while ((replacePos = token.find("~1", replacePos)) != std::string::npos) { token.replace(replacePos, 2, "/"); replacePos += 1; } replacePos = 0; while ((replacePos = token.find("~0", replacePos)) != std::string::npos) { token.replace(replacePos, 2, "~"); replacePos += 1; } tokens.push_back(token); if (slashPos == std::string::npos) { break; } startPos = slashPos + 1; } return tokens; } static std::string buildpropertyschemapath(const std::vector &tokens, bool appendType, bool parentOnly) { std::string schemaPath = "$"; std::size_t limit = tokens.size(); if (parentOnly && limit > 0) { limit -= 1; } for (std::size_t index = 0; index < limit; ++index) { if (isnumerictoken(tokens[index])) { schemaPath += ".items"; } else { schemaPath += ".properties." + tokens[index]; } } if (parentOnly) { schemaPath += ".properties"; } else if (appendType) { schemaPath += ".type"; } return schemaPath; } static std::string jsonpointertostring(const nlohmann::json::json_pointer &ptr) { std::vector tokens = splitpointertokens(ptr); std::string pointerString = "$"; for (const std::string &token : tokens) { if (isnumerictoken(token)) { pointerString += "[" + token + "]"; } else { pointerString += "." + token; } } return pointerString; } static std::string jsonvaluetypename(const JsonDocument &value) { switch (value.type()) { case JsonDocument::value_t::null: return "null"; case JsonDocument::value_t::object: return "object"; case JsonDocument::value_t::array: return "array"; case JsonDocument::value_t::string: return "string"; case JsonDocument::value_t::boolean: return "boolean"; case JsonDocument::value_t::number_integer: case JsonDocument::value_t::number_unsigned: case JsonDocument::value_t::number_float: return "number"; case JsonDocument::value_t::binary: return "binary"; case JsonDocument::value_t::discarded: return "discarded"; } return "unknown"; } static std::string resolveexpectedtypefromschema(const JsonDocument *schema_document, const std::vector &tokens) { const JsonDocument *currentNode = schema_document; if (currentNode == nullptr) { return ""; } for (const std::string &token : tokens) { if (isnumerictoken(token)) { if (!currentNode->is_object() || !currentNode->contains("items")) { return ""; } currentNode = &(*currentNode)["items"]; } else { if (!currentNode->is_object() || !currentNode->contains("properties")) { return ""; } const JsonDocument &propertiesNode = (*currentNode)["properties"]; if (!propertiesNode.is_object() || !propertiesNode.contains(token)) { return ""; } currentNode = &propertiesNode[token]; } } if (!currentNode->is_object() || !currentNode->contains("type")) { return ""; } if ((*currentNode)["type"].is_string()) { return (*currentNode)["type"].get(); } return ""; } static ValidationIssue buildIssue(const nlohmann::json::json_pointer &ptr, const JsonDocument *schema_document, const JsonDocument &instance, const std::string &message) { ValidationIssue issue; std::vector tokens = splitpointertokens(ptr); issue.instancePath_ = jsonpointertostring(ptr); issue.schemaPath_ = "$"; if (message.rfind("unexpected instance type", 0) == 0) { std::string expectedType = resolveexpectedtypefromschema(schema_document, tokens); issue.code_ = "JZN-00503"; issue.schemaPath_ = buildpropertyschemapath(tokens, true, false); issue.error_ = "invalid type found, actual: " + jsonvaluetypename(instance) + ", expected: " + (expectedType.empty() ? "unknown" : expectedType); } else if (message.rfind("required property '", 0) == 0) { issue.code_ = "JZN-00515"; issue.schemaPath_ = "$.required"; issue.error_ = message; } else if (message.rfind("validation failed for additional property '", 0) == 0) { issue.code_ = "JZN-00514"; issue.error_ = message; } else { issue.code_ = "JZN-00501"; issue.error_ = message; } return issue; } }; static void noopFormatCheck(const std::string &format_name, const std::string &format_value) { (void) format_name; (void) format_value; } static void noopContentCheck(const std::string &content_encoding, const std::string &content_media_type, const JsonDocument &instance_value) { (void) content_encoding; (void) content_media_type; (void) instance_value; } static char * jsonbtocstringcopy(Jsonb *jsonb_value) { char *jsonCString = JsonbToCString(NULL, &jsonb_value->root, VARSIZE(jsonb_value)); if (jsonCString == nullptr) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("DBMS_JSON_SCHEMA.IS_SCHEMA_VALID failed to serialize jsonb"))); } return jsonCString; } static JsonDocument parsejsondocument(const char *json_data) { try { return JsonDocument::parse(json_data); } catch (const std::exception &ex) { ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid JSON input"), errdetail("%s", ex.what()))); } return JsonDocument(); } static bool isschemavaliddocument(const JsonDocument &schemaDocument) { JsonValidator metaValidator(nullptr, noopFormatCheck, noopContentCheck); nlohmann::json_schema::basic_error_handler metaErrorHandler; JsonValidator validator(nullptr, noopFormatCheck, noopContentCheck); metaValidator.set_root_schema(nlohmann::json_schema::draft7_schema_builtin); metaValidator.validate(schemaDocument, metaErrorHandler); if (metaErrorHandler) { ereport(LOG, (errmsg("DBMS_JSON_SCHEMA schema meta-validation"), errdetail("status=invalid"))); return false; } validator.set_root_schema(schemaDocument); return true; } static JsonDocument builderrorsreport(const CollectingErrorHandler &errorHandler) { JsonDocument reportDocument = JsonDocument::object(); JsonDocument issuesArray = JsonDocument::array(); std::set invalidProperties; reportDocument["valid"] = errorHandler.issues_.empty(); if (!errorHandler.issues_.empty()) { JsonDocument rootIssue = JsonDocument::object(); rootIssue["schemaPath"] = "$"; rootIssue["instancePath"] = "$"; rootIssue["code"] = "JZN-00501"; rootIssue["error"] = "JSON schema validation failed"; issuesArray.push_back(rootIssue); } for (const ValidationIssue &issue : errorHandler.issues_) { if (issue.code_ == "JZN-00503" && issue.instancePath_.rfind("$.", 0) == 0) { invalidProperties.insert(issue.instancePath_.substr(2)); } } for (const std::string &invalidProperty : invalidProperties) { JsonDocument propertyIssue = JsonDocument::object(); propertyIssue["schemaPath"] = "$.properties"; propertyIssue["instancePath"] = "$"; propertyIssue["code"] = "JZN-00514"; propertyIssue["error"] = "invalid properties: ''" + invalidProperty + "''"; issuesArray.push_back(propertyIssue); } for (const ValidationIssue &issue : errorHandler.issues_) { JsonDocument issueDocument = JsonDocument::object(); issueDocument["schemaPath"] = issue.schemaPath_; issueDocument["instancePath"] = issue.instancePath_; issueDocument["code"] = issue.code_; issueDocument["error"] = issue.error_; issuesArray.push_back(issueDocument); } reportDocument["errors"] = issuesArray; return reportDocument; } static std::string jsonquotestring(const std::string &value) { return JsonDocument(value).dump(); } static std::string serializereporttext(const CollectingErrorHandler &errorHandler) { std::string reportText = "{\"valid\":"; std::set invalidProperties; reportText += errorHandler.issues_.empty() ? "true" : "false"; reportText += ",\"errors\":["; if (!errorHandler.issues_.empty()) { reportText += "{\"schemaPath\":\"$\",\"instancePath\":\"$\",\"code\":\"JZN-00501\",\"error\":\"JSON schema validation failed\"}"; } for (const ValidationIssue &issue : errorHandler.issues_) { if (issue.code_ == "JZN-00503" && issue.instancePath_.rfind("$.", 0) == 0) { invalidProperties.insert(issue.instancePath_.substr(2)); } } for (const std::string &invalidProperty : invalidProperties) { if (reportText.back() != '[') { reportText += ","; } reportText += "{\"schemaPath\":\"$.properties\",\"instancePath\":\"$\",\"code\":\"JZN-00514\",\"error\":"; reportText += jsonquotestring("invalid properties:\n'" + invalidProperty + "'"); reportText += "}"; } for (const ValidationIssue &issue : errorHandler.issues_) { if (reportText.back() != '[') { reportText += ","; } reportText += "{\"schemaPath\":"; reportText += jsonquotestring(issue.schemaPath_); reportText += ",\"instancePath\":"; reportText += jsonquotestring(issue.instancePath_); reportText += ",\"code\":"; reportText += jsonquotestring(issue.code_); reportText += ",\"error\":"; reportText += jsonquotestring(issue.error_); reportText += "}"; } reportText += "]}"; return reportText; } static ValidationResult validatejsondocument(const JsonDocument &dataDocument, const JsonDocument &schemaDocument) { ValidationResult result; JsonValidator validator(nullptr, noopFormatCheck, noopContentCheck); CollectingErrorHandler errorHandler(&schemaDocument); result.schemaValid_ = isschemavaliddocument(schemaDocument); if (!result.schemaValid_) { result.dataValid_ = false; result.errorsReport_ = JsonDocument::object({ {"valid", false}, {"errors", JsonDocument::array()} }); return result; } validator.set_root_schema(schemaDocument); validator.validate(dataDocument, errorHandler); result.dataValid_ = errorHandler.issues_.empty(); result.errorsReport_ = builderrorsreport(errorHandler); result.reportText_ = serializereporttext(errorHandler); ereport(LOG, (errmsg("DBMS_JSON_SCHEMA validation result"), errdetail("schema_valid=%s, data_valid=%s, issues=%zu", result.schemaValid_ ? "true" : "false", result.dataValid_ ? "true" : "false", errorHandler.issues_.size()))); return result; } static ValidationResult validatecstringinput(const char *json_data, const char *json_schema) { JsonDocument dataDocument = parsejsondocument(json_data); JsonDocument schemaDocument = parsejsondocument(json_schema); ereport(LOG, (errmsg("DBMS_JSON_SCHEMA validation text input"), errdetail("json_length=%zu, schema_length=%zu", strlen(json_data), strlen(json_schema)))); return validatejsondocument(dataDocument, schemaDocument); } static Jsonb * jsondocumenttojsonb(const JsonDocument &document) { std::string jsonText = document.dump(); Datum jsonbDatum = DirectFunctionCall1(jsonb_in, CStringGetDatum(jsonText.c_str())); return DatumGetJsonbP(jsonbDatum); } static text * jsondocumenttotext(const JsonDocument &document) { return cstring_to_text(document.dump(-1, ' ', false, JsonDocument::error_handler_t::strict).c_str()); } static bool isschemavalidinternal(Jsonb *json_schema) { char *jsonCString = jsonbtocstringcopy(json_schema); JsonDocument schemaDocument; bool resultValue = false; ereport(LOG, (errmsg("DBMS_JSON_SCHEMA.IS_SCHEMA_VALID input"), errdetail("schema_length=%zu", strlen(jsonCString)))); schemaDocument = parsejsondocument(jsonCString); resultValue = isschemavaliddocument(schemaDocument); if (!resultValue) { ereport(LOG, (errmsg("DBMS_JSON_SCHEMA.IS_SCHEMA_VALID meta-schema check"), errdetail("status=invalid"))); } else { ereport(LOG, (errmsg("DBMS_JSON_SCHEMA.IS_SCHEMA_VALID result"), errdetail("status=valid"))); } if (jsonCString != nullptr) { pfree(jsonCString); } return resultValue; } static ValidationResult isvalidinternal(Jsonb *json_data, Jsonb *json_schema) { char *dataCString = jsonbtocstringcopy(json_data); char *schemaCString = jsonbtocstringcopy(json_schema); JsonDocument dataDocument; JsonDocument schemaDocument; ValidationResult validationResult; ereport(LOG, (errmsg("DBMS_JSON_SCHEMA.IS_VALID input"), errdetail("json_length=%zu, schema_length=%zu", strlen(dataCString), strlen(schemaCString)))); dataDocument = parsejsondocument(dataCString); schemaDocument = parsejsondocument(schemaCString); validationResult = validatejsondocument(dataDocument, schemaDocument); if (dataCString != nullptr) { pfree(dataCString); } if (schemaCString != nullptr) { pfree(schemaCString); } return validationResult; } } // namespace DbmsJsonSchema /* * @qdb_func: dbms_json_schema_is_schema_valid(jsonb) * @ora_func: DBMS_JSON_SCHEMA.IS_SCHEMA_VALID(JSON) */ Datum dbms_json_schema_is_schema_valid(PG_FUNCTION_ARGS) { Jsonb *jsonSchema = nullptr; bool isValid = false; ereport(LOG, (errmsg("DBMS_JSON_SCHEMA.IS_SCHEMA_VALID call"), errdetail("nargs=%d, arg0_is_null=%s", PG_NARGS(), PG_ARGISNULL(0) ? "true" : "false"))); if (PG_ARGISNULL(0)) { ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("ORA-64403: input cannot be NULL"))); } jsonSchema = PG_GETARG_JSONB_P_COPY(0); isValid = DbmsJsonSchema::isschemavalidinternal(jsonSchema); if (jsonSchema != nullptr) { pfree(jsonSchema); } PG_RETURN_INT32(isValid ? DBMS_JSON_SCHEMA_VALID : DBMS_JSON_SCHEMA_INVALID); } Datum dbms_json_schema_is_schema_valid2(PG_FUNCTION_ARGS) { int32 serviceArg = 0; if (PG_NARGS() != 2) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("DBMS_JSON_SCHEMA.IS_SCHEMA_VALID2 accepts exactly 2 arguments"))); } if (!PG_ARGISNULL(1)) { serviceArg = PG_GETARG_INT32(1); } (void) serviceArg; { LOCAL_FCINFO(fcinfo2, 1); InitFunctionCallInfoData(*fcinfo2, nullptr, 1, InvalidOid, nullptr, nullptr); fcinfo2->args[0].value = PG_GETARG_DATUM(0); fcinfo2->args[0].isnull = PG_ARGISNULL(0); return dbms_json_schema_is_schema_valid(fcinfo2); } } Datum dbms_json_schema_is_valid(PG_FUNCTION_ARGS) { Jsonb *jsonData = nullptr; Jsonb *jsonSchema = nullptr; int32 raiseErr = DBMS_JSON_SCHEMA_RAISE_NONE; DbmsJsonSchema::ValidationResult validationResult; ereport(LOG, (errmsg("DBMS_JSON_SCHEMA.IS_VALID function call"), errdetail("nargs=%d, arg0_is_null=%s, arg1_is_null=%s, arg2_is_null=%s", PG_NARGS(), PG_ARGISNULL(0) ? "true" : "false", PG_ARGISNULL(1) ? "true" : "false", (PG_NARGS() > 2 && PG_ARGISNULL(2)) ? "true" : "false"))); if (PG_ARGISNULL(0) || PG_ARGISNULL(1)) { ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("ORA-64403: input cannot be NULL"))); } if (PG_NARGS() > 2 && !PG_ARGISNULL(2)) { raiseErr = PG_GETARG_INT32(2); } if (raiseErr != DBMS_JSON_SCHEMA_RAISE_NONE && raiseErr != DBMS_JSON_SCHEMA_RAISE_ERROR) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("DBMS_JSON_SCHEMA.IS_VALID invalid raise_err"), errdetail("raise_err=%d", raiseErr))); } jsonData = PG_GETARG_JSONB_P_COPY(0); jsonSchema = PG_GETARG_JSONB_P_COPY(1); validationResult = DbmsJsonSchema::isvalidinternal(jsonData, jsonSchema); if (jsonData != nullptr) { pfree(jsonData); } if (jsonSchema != nullptr) { pfree(jsonSchema); } if (!validationResult.schemaValid_ && raiseErr == DBMS_JSON_SCHEMA_RAISE_ERROR) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("JSON schema validation failed"), errdetail("raise_err=RAISE_ERROR requested exception for invalid schema"))); } PG_RETURN_INT32(validationResult.dataValid_ ? DBMS_JSON_SCHEMA_VALID : DBMS_JSON_SCHEMA_INVALID); } Datum dbms_json_schema_validate_report(PG_FUNCTION_ARGS) { char *jsonSchemaCString = nullptr; Jsonb *jsonDataJsonb = nullptr; Jsonb *jsonSchemaJsonb = nullptr; char *jsonDataCString = nullptr; DbmsJsonSchema::ValidationResult validationResult; bool useJsonbInput = false; ereport(LOG, (errmsg("DBMS_JSON_SCHEMA.VALIDATE_REPORT call"), errdetail("nargs=%d, arg0_is_null=%s, arg1_is_null=%s", PG_NARGS(), PG_ARGISNULL(0) ? "true" : "false", PG_ARGISNULL(1) ? "true" : "false"))); if (PG_ARGISNULL(0) || PG_ARGISNULL(1)) { PG_RETURN_NULL(); } useJsonbInput = get_fn_expr_argtype(fcinfo->flinfo, 0) == JSONBOID && get_fn_expr_argtype(fcinfo->flinfo, 1) == JSONBOID; if (useJsonbInput) { jsonDataJsonb = PG_GETARG_JSONB_P_COPY(0); jsonSchemaJsonb = PG_GETARG_JSONB_P_COPY(1); jsonDataCString = DbmsJsonSchema::jsonbtocstringcopy(jsonDataJsonb); jsonSchemaCString = DbmsJsonSchema::jsonbtocstringcopy(jsonSchemaJsonb); } else { text *jsonDataText = PG_GETARG_TEXT_PP(0); text *jsonSchemaText = PG_GETARG_TEXT_PP(1); jsonDataCString = text_to_cstring(jsonDataText); jsonSchemaCString = text_to_cstring(jsonSchemaText); } validationResult = DbmsJsonSchema::validatecstringinput(jsonDataCString, jsonSchemaCString); ereport(LOG, (errmsg("DBMS_JSON_SCHEMA.VALIDATE_REPORT result"), errdetail("valid=%s", validationResult.dataValid_ ? "true" : "false"))); if (jsonDataCString != nullptr) { pfree(jsonDataCString); } if (jsonSchemaCString != nullptr) { pfree(jsonSchemaCString); } if (jsonDataJsonb != nullptr) { pfree(jsonDataJsonb); } if (jsonSchemaJsonb != nullptr) { pfree(jsonSchemaJsonb); } PG_RETURN_TEXT_P(cstring_to_text(validationResult.reportText_.c_str())); } Datum dbms_json_schema_get_version(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_JSON_SCHEMA_VERSION)); }